2021-08-12 15:04:37 +02:00
|
|
|
import { Knex } from 'knex';
|
|
|
|
import session from 'express-session';
|
|
|
|
import knexSessionStore from 'connect-session-knex';
|
|
|
|
import { RequestHandler } from 'express';
|
2021-04-22 10:07:10 +02:00
|
|
|
import { IUnleashConfig } from '../types/option';
|
2021-11-02 15:13:46 +01:00
|
|
|
import { hoursToMilliseconds } from 'date-fns';
|
2021-02-18 09:03:21 +01:00
|
|
|
|
2021-04-22 10:07:10 +02:00
|
|
|
function sessionDb(
|
|
|
|
config: Pick<IUnleashConfig, 'session' | 'server' | 'secureHeaders'>,
|
2021-08-12 15:04:37 +02:00
|
|
|
knex: Knex,
|
|
|
|
): RequestHandler {
|
2021-02-18 09:03:21 +01:00
|
|
|
let store;
|
2022-06-03 11:50:58 +02:00
|
|
|
const { db, cookieName } = config.session;
|
2021-11-02 15:13:46 +01:00
|
|
|
const age =
|
|
|
|
hoursToMilliseconds(config.session.ttlHours) || hoursToMilliseconds(48);
|
2021-08-12 15:04:37 +02:00
|
|
|
const KnexSessionStore = knexSessionStore(session);
|
2021-02-18 09:03:21 +01:00
|
|
|
if (db) {
|
|
|
|
store = new KnexSessionStore({
|
|
|
|
tablename: 'unleash_session',
|
|
|
|
createtable: false,
|
2021-08-12 15:04:37 +02:00
|
|
|
knex,
|
2021-02-18 09:03:21 +01:00
|
|
|
});
|
|
|
|
} else {
|
|
|
|
store = new session.MemoryStore();
|
|
|
|
}
|
2021-08-12 15:04:37 +02:00
|
|
|
return session({
|
2022-06-03 11:50:58 +02:00
|
|
|
name: cookieName,
|
2021-02-18 09:03:21 +01:00
|
|
|
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,
|
|
|
|
},
|
|
|
|
});
|
2021-04-22 10:07:10 +02:00
|
|
|
}
|
2021-11-02 15:13:46 +01:00
|
|
|
|
2021-04-22 10:07:10 +02:00
|
|
|
export default sessionDb;
|