Create a gist now

Instantly share code, notes, and snippets.

Node.js Session handling, used @ cacodaemon.de
module.exports.Session = function () {
var getRandom = function () {
return Math.floor(Math.random() * 1e16).toString(36);
}
this.sessionId = getRandom() + '-' + new Date().getTime().toString(36) + '-' + getRandom();
this.doDestroy = false;
this.toString = function () {
return this.sessionId;
}
this.getTime = function () {
return parseInt(this.sessionId.split('-')[1], 36);
}
}
var Session = require('./Session.js').Session
module.exports.SessionHandler = function (cookieName, maxAge, checkInterval) {
var cookieName = cookieName ? cookieName : 'SESSION';
var maxAge = maxAge ? maxAge * 1000 : 600000; //10 minutes
var checkInterval = checkInterval ? checkInterval : 1000; //default 1 sec.
var sessions = new Array();
this.forEachSession = function (callback) {
for (var key in sessions) {
callback(sessions[key]);
}
}
this.deleteSession = function (session) {
if (sessions[session]) {
delete sessions[session];
return true;
}
return false;
}
this.getSession = function (request, response) {
var cookie = request.headers.cookie;
if (cookie && cookie.indexOf(cookieName) !== -1) { //cookie found
var start = cookie.indexOf(cookieName) + cookieName.length + 1;
var end = cookie.indexOf('; ', start);
end = end === -1 ? cookie.length : end;
var value = cookie.substring(start, end);
if (sessions[value]) {
return sessions[value];
}
}
var session = new Session();
response.setHeader('Set-Cookie', [cookieName + '=' + session + ';Max-Age=' + maxAge / 1000]);
return sessions[session] = session;
}
//garbage collection
setInterval(function () {
var now = new Date().getTime();
for (var key in sessions) {
var session = sessions[key];
if (session.doDestroy) {
delete sessions[key];
}
if (now - session.getTime() > maxAge) {
delete sessions[key];
}
}
}, checkInterval);
}
var http = require('http');
var url = require("url");
var SessionHandler = require('./SessionHandler.js').SessionHandler;
var sessionHandler = new SessionHandler();
http.createServer(function (request, response) {
var query = url.parse(request.url, true).query;
var session = sessionHandler.getSession(request, response);
if (!session.name && query.name) {
session.name = query.name;
}
response.writeHead(200, {'Content-Type': 'text/html'});
if (session.name) {
response.end('<h1>Hello ' + session.name + '!</h1>');
}
else {
response.end('<h1>Who are you?</h1>');
}
}).listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment