Last active
August 29, 2015 14:12
-
-
Save alanjames1987/b88ff9422775deaddc21 to your computer and use it in GitHub Desktop.
Express / Socket.IO Session Sync
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
| var cookie = require('cookie'); | |
| var cookieParser = require('cookie-parser'); | |
| var _sessionStore; | |
| var _sessionSecret; | |
| function plugin(data) { | |
| // store the Express session cookie name, session store, and session secret for use later | |
| _sessionCookie = data.name || 'connect.sid'; | |
| _sessionStore = data.store; | |
| _sessionSecret = data.secret; | |
| function middleware(socket, next) { | |
| // create a refreshSession function on the socket | |
| // this function should be run each time a session needs to be refreshed on the socket | |
| socket.refreshSession = function(callback) { | |
| // cookie not found | |
| if (!socket.handshake.headers.cookie) { | |
| callback(true, null); | |
| return; | |
| } | |
| var handshakeCookies; | |
| var handshakeCookie; | |
| var sessionId; | |
| try { | |
| // get the session ID if it exists | |
| handshakeCookies = cookie.parse(socket.handshake.headers.cookie); | |
| handshakeCookie = handshakeCookies[_sessionCookie]; | |
| sessionId = cookieParser.signedCookie(handshakeCookies[_sessionCookie], _sessionSecret); | |
| } catch (e) { | |
| callback(true, null); | |
| return; | |
| } | |
| // cookie invalid | |
| // this can happen when the cookie parser can't parse the signed cookie | |
| if (handshakeCookie === sessionId) { | |
| callback(true, null); | |
| return; | |
| } | |
| // cookie is signed correctly | |
| // pull the session information from the session store using the sessionId | |
| _sessionStore.load(sessionId, function(err, session) { | |
| if (err || !session) { | |
| callback(err, session); | |
| return; | |
| } | |
| // add the session data to the socket | |
| socket.session = session; | |
| callback(err, session); | |
| return; | |
| }); | |
| }; | |
| // run refreshSession on the socket to create the inital session data | |
| socket.refreshSession(function(err, result) { | |
| if (err || !result) { | |
| next(); | |
| return; | |
| } | |
| next(); | |
| return; | |
| }); | |
| } | |
| return middleware; | |
| } | |
| module.exports = plugin; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment