Created
November 27, 2017 23:47
-
-
Save jodevsa/398de43a9ebffce4866af50d3802b060 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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