Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying the session data from inside the socket.io callback

I am currently using this stack expres, socket.io, sessionstore. I followed the article here http://www.danielbaulig.de/socket-ioexpress/. Well the problem is that i cannot modify the session values in socket.io callback.

Access from express side works well, the item get increased after each refresh.

app.get('/mysession', function(req, res) {
  req.session.item++;
  console.log(req.session);

  res.render('session.jade', {
    title: 'Sample title'
  });
});

Using in socket.io side it does not and here is the problem, maybe i am setting the wrong object.

var io = io.listen(app);
io.sockets.on('connection', function(socket) {
  var handshake = socket.handshake;
  onlineCount++;
  console.log('Well done id %s', handshake.sessionID);
  handshake.session.item++;

  console.log(handshake.session);

});

Here is bridge code.

io.set('authorization', function(data, accept) {
  if (data.headers.cookie) {
    data.cookie = parseCookie(data.headers.cookie);
    data.sessionID = data.cookie['express.sid'];
    sessionStore.get(data.sessionID, function(err, session) {
      if (err || !session) {
        accept('Error', false);
      } else {
        data.session = session;
        accept(null, true);
      }
    });
  } else {
    return accept('No cookie tansmitted', false);
  }
});
like image 605
Risto Novik Avatar asked Feb 02 '12 10:02

Risto Novik


2 Answers

The only way I found to make this work is to grab the cookie from the request object on the connect event, parse it with your favourite cookie parser (I use connect.utils.parseCookie), and set it on that socket so that I may access it in future events:

socket.on('connection', function(client) {
  var cookie = client.request.headers.cookie;
  var pcookie = connect.utils.parseCookie(cookie);
  var session_id = pcookie["connect.sid"];
  if (session_id) {
    sessionStore.get(session_id, function(err, sess) {
      // do whatever you want with sess here
      // ...
      // if you want to "save" the session for future events
      client.set('session_id', session_id);
    }
  }
});
like image 174
ziad-saab Avatar answered Nov 04 '22 13:11

ziad-saab


The sessionStore API changed a little bit, now its sessionStore.load(sessionId, cb) instead of .get.

like image 26
diversario Avatar answered Nov 04 '22 11:11

diversario