module.exports = SessionSockets; function SessionSockets(io, sessionStore, cookieParser, key) { key = typeof key === 'undefined' ? 'connect.sid' : key; var sessionSockets = this; this.on = function(event, callback) { return bind(event, callback, io.sockets); }; this.of = function(namespace) { return { on: function(event, callback) { return bind(event, callback, io.of(namespace)); } }; }; this.getSession = function(socket, callback) { cookieParser(socket.handshake, {}, function () { sessionStore.load(findCookie(socket.handshake), function (session) { callback(session); }); }); }; function bind(event, callback, namespace) { namespace.on(event, function (socket) { sessionSockets.getSession(socket, function (session) { callback(socket, session); }); }); } function findCookie(handshake) { if (handshake) return (handshake.secureCookies && handshake.secureCookies[key]) || (handshake.signedCookies && handshake.signedCookies[key]) || (handshake.cookies && handshake.cookies[key]); } }