2020-04-22 15:52:17 +02:00
|
|
|
import ApplicationComponent from "../ApplicationComponent";
|
|
|
|
import session from "express-session";
|
|
|
|
import config from "config";
|
|
|
|
import RedisComponent from "./RedisComponent";
|
|
|
|
import flash from "connect-flash";
|
2020-07-11 11:46:16 +02:00
|
|
|
import {Router} from "express";
|
2020-04-22 15:52:17 +02:00
|
|
|
|
|
|
|
export default class SessionComponent extends ApplicationComponent<void> {
|
|
|
|
private readonly storeComponent: RedisComponent;
|
|
|
|
|
|
|
|
public constructor(storeComponent: RedisComponent) {
|
|
|
|
super();
|
|
|
|
this.storeComponent = storeComponent;
|
|
|
|
}
|
|
|
|
|
2020-07-11 11:46:16 +02:00
|
|
|
public async init(router: Router): Promise<void> {
|
2020-04-22 15:52:17 +02:00
|
|
|
router.use(session({
|
|
|
|
saveUninitialized: true,
|
|
|
|
secret: config.get('session.secret'),
|
|
|
|
store: this.storeComponent.getStore(),
|
|
|
|
resave: true,
|
|
|
|
cookie: {
|
|
|
|
httpOnly: true,
|
|
|
|
secure: config.get('session.cookie.secure'),
|
|
|
|
},
|
|
|
|
rolling: true,
|
|
|
|
}));
|
|
|
|
|
|
|
|
router.use(flash());
|
|
|
|
|
|
|
|
router.use((req, res, next) => {
|
|
|
|
if (!req.session) {
|
|
|
|
throw new Error('Session is unavailable.');
|
|
|
|
}
|
|
|
|
|
|
|
|
res.locals.session = req.session;
|
|
|
|
|
2020-07-06 10:42:46 +02:00
|
|
|
let _flash: any = {};
|
|
|
|
res.locals.flash = (key?: string) => {
|
|
|
|
if (key !== undefined) {
|
|
|
|
if (_flash[key] === undefined) _flash[key] = req.flash(key) || null;
|
|
|
|
return _flash[key];
|
|
|
|
}
|
|
|
|
|
|
|
|
if (_flash._messages === undefined) {
|
|
|
|
_flash._messages = {
|
2020-04-22 15:52:17 +02:00
|
|
|
info: req.flash('info'),
|
|
|
|
success: req.flash('success'),
|
|
|
|
warning: req.flash('warning'),
|
|
|
|
error: req.flash('error'),
|
|
|
|
};
|
|
|
|
}
|
2020-07-06 10:42:46 +02:00
|
|
|
return _flash._messages;
|
2020-04-22 15:52:17 +02:00
|
|
|
};
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|