2021-04-22 10:07:10 +02:00
|
|
|
import { IUnleashConfig } from '../types/option';
|
|
|
|
import { IUnleashStores } from '../types/stores';
|
|
|
|
|
2021-02-18 09:03:21 +01:00
|
|
|
const session = require('express-session');
|
|
|
|
const KnexSessionStore = require('connect-session-knex')(session);
|
|
|
|
|
|
|
|
const TWO_DAYS = 48 * 60 * 60 * 1000;
|
2021-04-22 10:07:10 +02:00
|
|
|
function sessionDb(
|
|
|
|
config: Pick<IUnleashConfig, 'session' | 'server' | 'secureHeaders'>,
|
|
|
|
stores: Pick<IUnleashStores, 'db'>,
|
|
|
|
): any {
|
2021-02-18 09:03:21 +01:00
|
|
|
let store;
|
2021-04-22 10:07:10 +02:00
|
|
|
const { db } = config.session;
|
|
|
|
const age = config.session.ttlHours * 60000 || TWO_DAYS;
|
2021-02-18 09:03:21 +01:00
|
|
|
if (db) {
|
|
|
|
store = new KnexSessionStore({
|
2021-04-22 10:07:10 +02:00
|
|
|
knex: stores.db,
|
2021-02-18 09:03:21 +01:00
|
|
|
tablename: 'unleash_session',
|
|
|
|
createtable: false,
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
store = new session.MemoryStore();
|
|
|
|
}
|
|
|
|
const sessionMiddleware = session({
|
|
|
|
name: 'unleash-session',
|
|
|
|
rolling: false,
|
|
|
|
resave: false,
|
|
|
|
saveUninitialized: false,
|
|
|
|
store,
|
2021-04-22 10:07:10 +02:00
|
|
|
secret: [config.server.secret],
|
2021-02-18 09:03:21 +01:00
|
|
|
cookie: {
|
2021-04-22 10:07:10 +02:00
|
|
|
path:
|
|
|
|
config.server.baseUriPath === ''
|
|
|
|
? '/'
|
|
|
|
: config.server.baseUriPath,
|
|
|
|
secure: config.secureHeaders,
|
2021-02-18 09:03:21 +01:00
|
|
|
maxAge: age,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
return (req, res, next) => sessionMiddleware(req, res, next);
|
2021-04-22 10:07:10 +02:00
|
|
|
}
|
|
|
|
export default sessionDb;
|
|
|
|
module.exports = sessionDb;
|