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-02-18 09:03:21 +01:00
|
|
|
|
|
|
|
const TWO_DAYS = 48 * 60 * 60 * 1000;
|
2021-05-05 14:56:09 +02:00
|
|
|
const HOUR = 60 * 60 * 1000;
|
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;
|
2021-04-22 10:07:10 +02:00
|
|
|
const { db } = config.session;
|
2021-05-05 14:56:09 +02:00
|
|
|
const age = config.session.ttlHours * HOUR || TWO_DAYS;
|
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
|
|
|
// @ts-ignore
|
|
|
|
knex,
|
2021-02-18 09:03:21 +01:00
|
|
|
});
|
|
|
|
} else {
|
|
|
|
store = new session.MemoryStore();
|
|
|
|
}
|
2021-08-12 15:04:37 +02:00
|
|
|
return session({
|
2021-02-18 09:03:21 +01:00
|
|
|
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,
|
|
|
|
},
|
|
|
|
});
|
2021-04-22 10:07:10 +02:00
|
|
|
}
|
|
|
|
export default sessionDb;
|