Skip to content

Instantly share code, notes, and snippets.

@antishok
Created August 18, 2019 21:11
Show Gist options
  • Save antishok/4f1864be2d9a9331b8d8e812d26397dd to your computer and use it in GitHub Desktop.
Save antishok/4f1864be2d9a9331b8d8e812d26397dd to your computer and use it in GitHub Desktop.
express-ws session example
const path = require('path');
const express = require('express');
const expressWs = require('express-ws');
const bodyParser = require('body-parser');
const expressSession = require('express-session');
const KnexSessionStore = require('connect-session-knex')(expressSession);
const passport = require('passport');
const app = express();
expressWs(app);
if (config.behindProxy) { app.enable('trust proxy'); }
app.set('view engine', 'pug');
app.use('/static', express.static(path.join(__dirname, 'public')));
app.use(expressSession({
store: new KnexSessionStore({knex}),
cookie: {maxAge: 60 * 24 * 60 * 60 * 1000},
secret: '...',
saveUninitialized: false,
resave: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
/********************* ROUTES *********************/
app.use('/auth', require('./routes/auth')(db));
app.use('/', require('./routes/index')(db));
app.use('/ws', require('./routes/ws')(db));
app.use(errorHandlers.router);
app.use(errorHandlers.errorHandler);
/**************************************************/
const port = config.httpPort || 8080;
const host = config.behindProxy ? '127.0.0.1' : '0.0.0.0';
logger.info(`...`);
logger.info(`*** MODE: ${process.env.NODE_ENV === 'production' ? 'PRODUCTION': 'DEVELOPMENT'} ***`);
app.listen(port, host, () => {
logger.info(`[HTTP] Listening on ${host}:${port}`);
});
// middleware for routes that require authentication (being logged-in)
const errors = require('./errors');
module.exports = requireAuth;
function requireAuth(req, res, next) {
if (!req.isAuthenticated()) {
if (req.accepts('html', 'json') === 'html') {
return res.redirect('/auth/login');
}
return next( errors.PermissionDeniedError(`Authentication is required`) );
}
res.locals.user = req.user; // expose user object to views
next();
}
const requireAuth = require('../lib/requireAuth');
const router = require('express-promise-router')();
module.exports = function ws_routes(db) {
router.use( requireAuth );
router.ws('/:role/:callId', ...);
router.ws('/calls', ...);
return router;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment