scttnlsn / backbone.io

Backbone.js sync via Socket.IO
http://scttnlsn.github.io/backbone.io
540 stars 66 forks source link

Express Sessions #45

Closed blargism closed 11 years ago

blargism commented 11 years ago

It looks the the cookie key and the express session key are no longer one to one.

The cookie

{
  "connect.sid": "s:hi78yqZc1l3xq1oPBpGbC-cW.3K/mgvtRukv5jW3lJHkXnZiIysXCXCQ59rCqqL0r7S0"
}

The session object

{
  "sessions": {
    "hi78yqZc1l3xq1oPBpGbC-cW": {
      "cookie":{
        "originalMaxAge":null,
        "expires":null,
        "httpOnly":true,
        "path":"/"
      }
    }
}

Notice that the full cookie key contains the session id between "s:" and a ".". I have yet to dive into the express code on this but, it seems the cookie key is no longer a direct match to a session key within an express memory store.

The following made it work, but a more elegant solution may be in order.

middleware/session.js

    return function(req, res, next) {
        var c = req.cookies[options.key];
        // get the session key between "s:" and "."
        req.sessionID = c.substring(2, c.indexOf('.');

        if (req.sessionID) {
            options.store.load(req.sessionID, function(err, session) {
                if (err) return next(err);
                if (!session) return next(new Error('Session not found'));
                req.session = session;
                next();
            });
        } else {
            next();
        }
    };
scttnlsn commented 11 years ago

The latest version (0.4.0) was just updated to work with Express 3.