Skip to content

Instantly share code, notes, and snippets.

@jodevsa
Created November 27, 2017 23:47
Show Gist options
  • Save jodevsa/398de43a9ebffce4866af50d3802b060 to your computer and use it in GitHub Desktop.
Save jodevsa/398de43a9ebffce4866af50d3802b060 to your computer and use it in GitHub Desktop.
const cookie = require('cookie-signature');
const uid = require('uid-safe');
function SessionMiddleWare(cookieKey, cookieLength, secretKey) {
const sessionStore = {}
const destroy = (key) => {
delete sessionStore[key];
}
return async (req, res, next) => {
let signedCookie = req.cookies[cookieKey];
if (signedCookie != undefined) {
const unsignedCookie = cookie.unsign(signedCookie, secretKey);
if (unsignedCookie && sessionStore[unsignedCookie] != undefined) {
req.session = sessionStore[unsignedCookie] || {
"destroy": destroy.bind(this, unsignedCookie)
};
return next();
}
}
const unsignedCookie = await uid(cookieLength);
signedCookie = cookie.sign(unsignedCookie, secretKey);
sessionStore[unsignedCookie] = {
"destroy": destroy.bind(this, unsignedCookie)
};
req.session = sessionStore[unsignedCookie];
res.cookie(cookieKey, signedCookie, {});
next();
}
}
module.exports = SessionMiddleWare;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment