swaf/src/components/SessionComponent.ts

57 lines
1.6 KiB
TypeScript

import ApplicationComponent from "../ApplicationComponent";
import session from "express-session";
import config from "config";
import RedisComponent from "./RedisComponent";
import flash from "connect-flash";
import {Express, Router} from "express";
export default class SessionComponent extends ApplicationComponent<void> {
private readonly storeComponent: RedisComponent;
public constructor(storeComponent: RedisComponent) {
super();
this.storeComponent = storeComponent;
}
public async start(app: Express, router: Router): Promise<void> {
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;
let _flash: any = null;
res.locals.flash = () => {
if (!_flash) {
_flash = {
info: req.flash('info'),
success: req.flash('success'),
warning: req.flash('warning'),
error: req.flash('error'),
};
}
return _flash;
};
next();
});
}
public async stop(): Promise<void> {
}
}