· 8 years ago · Nov 29, 2017, 10:08 AM
1const cookie = require('cookie-signature');
2const uid = require('uid-safe');
3
4function SessionMiddleWare(cookieKey, cookieLength, secretKey) {
5 const sessionStore = {}
6
7 const destroy = (key) => {
8 delete sessionStore[key];
9 }
10 return async (req, res, next) => {
11 let signedCookie = req.cookies[cookieKey];
12 if (signedCookie != undefined) {
13 const unsignedCookie = cookie.unsign(signedCookie, secretKey);
14 if (unsignedCookie && sessionStore[unsignedCookie] != undefined) {
15 req.session = sessionStore[unsignedCookie] || {
16 "destroy": destroy.bind(this, unsignedCookie)
17 };
18 return next();
19 }
20 }
21
22 const unsignedCookie = await uid(cookieLength);
23 signedCookie = cookie.sign(unsignedCookie, secretKey);
24 sessionStore[unsignedCookie] = {
25 "destroy": destroy.bind(this, unsignedCookie)
26 };
27 req.session = sessionStore[unsignedCookie];
28 res.cookie(cookieKey, signedCookie, {});
29 next();
30 }
31}
32
33module.exports = SessionMiddleWare;