import store from 'connect-redis';
import { release } from 'cpb-common';
import session from 'express-session';
import Redis from 'ioredis';
const RedisStore = store(session),
redisSettings = {
host: process.env.REDIS_HOST || 'localhost',
port: process.env.REDIS_PORT || 6379,
connectionName: release,
dropBufferSupport: true,
db: process.env.REDIS_DB || 10,
password: process.env.REDIS_AUTH,
showFriendlyErrorStack: true,
};
if (process.env.REDIS_TLS) {
// process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
redisSettings.tls = {
ca: process.env.REDIS_TLS,
};
}
const client = new Redis(redisSettings);
/**
* checks request for the session presence
* @throws {Error}
*/
function checkSession(req, res, next) {
if (!req.session) next(new Error(`[SessionMiddleware][checkSession] lost session`));
next();
}
/**
* ### Redis Session Middleware.
* @param {Express} app
* @return {Express} app
*/
export default app => {
console.info(`[middleware/session] redisSettings`, { redisSettings });
/**
* attaches redis session middleware (ideally it should work in multi-server setup)
*/
app.use(
session({
cookie: { maxAge: 1666666 },
resave: false,
saveUninitialized: true,
secret: '66666666666',
store: new RedisStore({
client,
prefix: `session/${release}/${app.get('nodeEnv')}/`,
disableTTL: true,
logErrors: true,
}),
}),
);
app.use(checkSession);
return app;
};