Created
May 30, 2016 01:24
-
-
Save seveibar/348490b72855e7d7948c6c6542532357 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
Hot Session Middleware | |
A hot session only exists on the server, we track it and expire it. It is cookie-less, | |
however the client needs to keep sending their token. It's basically a cookie without | |
cookies. | |
TODO This is not distributed, it can only be run on a single server, and a server restart | |
will cause all sessions to disappear. | |
*/ | |
var sessions = {}; | |
function getRandomKey(){ | |
var text = ""; | |
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; | |
for( var i=0; i < 20; i++ ){ | |
text += possible.charAt(Math.floor(Math.random() * possible.length)); | |
} | |
return text; | |
} | |
/* | |
The middleware creates a req.session object which can store variables associated | |
with this user. | |
req.session.key is a reserved variable which allows the client to access it's | |
variables. | |
req.session.expiresAt is a reserved variable for when the session is no longer | |
valid | |
*/ | |
function createHotSessionMiddleware(){ | |
return function(req, res, next){ | |
if (req.body && req.body.session && sessions[req.body.session]){ | |
req.session = sessions[req.body.session]; | |
}else if (req.query && req.query.session && sessions[req.query.session]){ | |
req.session = sessions[req.query.session]; | |
} | |
if (!req.session || new Date() > req.session.expiresAt){ | |
var key = getRandomKey(); | |
var expirationDate = new Date(); | |
expirationDate.setDate(expirationDate.getDate() + 30); | |
sessions[key] = { | |
key: key, | |
expiresAt: expirationDate | |
}; | |
req.session = sessions[key]; | |
} | |
next(); | |
} | |
} | |
module.exports = createHotSessionMiddleware; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment