Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Grabbing existing session on page reload with express/connect-redis

Grabbing existing session on page reload with express/connect-redis

Problem

Using connect, express, and socket.io, I'm trying to allow my application to grab the session details when reconnecting. My sessions obviously work while the client is connected, but if I refresh the page on my browser, it forgets everything.
My session cookie is definitely the same, so it's not that.

My code's a big mish-mash of snippets I've taken from a number of different sources, since there doesn't seem to be one complete example application out there. :-/

What am I missing..?

var qs      = require('querystring'),
    express = require('express'),
    app     = express.createServer(),
    io      = require('socket.io').listen(app.listen(8000)),
    routes  = require('./routes'),
    pCookie = require('connect').utils.parseCookie,
    Session = require('connect').middleware.session.Session,
    RedStore= require('connect-redis')(express),
    sStore  = new RedStore();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({ store: sStore, secret: 'tehsecretz' }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

app.get('/', routes.index);

io.sockets.on('connection', function (client) {
    var hs = client.handshake,
        session = hs.session;

    console.log('A socket connected called: ' + hs.sessionId);

    var intervalId = setInterval(function() {
        hs.session.reload(function() {
            hs.session.touch().save();
        });
    }, 60 * 1000);

    if (!session.userName) {
        // Prompts the user for a name on the frontend
        client.emit('need-to-register');
    }

    client.on('message', function(msg, c) {
        console.log(session);
        console.log(msg);
    });

    client.on('register-user', function(data, fn) {
        // This retrieves the user's name
        // and - hopefully - saves it to the session.

        data = qs.parse(data);
        session.userName = data.username;

        hs.session.save();
        console.log('Saving: ', session);

        fn('ok');
    });

    client.on('disconnect', function() {
        clearInterval(intervalId);
    });
});

io.set('authorization', function (data, accept) {
    if (data.headers.cookie) {
        data.cookie = pCookie(data.headers.cookie);
        data.sessionId = data.cookie['connect.sid'];

        data.sessionStore = sStore;
        sStore.get(data.sessionId, function (err, session) {
            if (err || !session) {
                accept('Error', false);
            } else {
                console.log(data.sessionId, session);
                data.session = new Session(data, session);
                accept(null, true);
            }
        });
    } else {
        return accept('No cookie transmitted', false);
    }
});

Thanks for any help provided!

Problem courtesy of: Morgon

Solution

Ugh. So in Daniel Baulig's post on the subject, he referenced the identifier sessionID. I figured that was just poor convention (as I'm used to camelCase) and promptly changed it to sessionId in my code.

As I was debugging, I turned on MONITORing on my redis instance and noticed the session was being written to sess:undefined.

Turns out sessionID is special and is referenced internally as the actual identifier. Changing all instances of sessionId to sessionID allows me to have a better clue as to who is connecting!

Solution courtesy of: Morgon

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Grabbing existing session on page reload with express/connect-redis

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×