7

I have a chat, and I need to manage unique connections. I searched around, but the solutions that I have found all appear to be deprecated.

So, how would I get a socket's session ID with Socket.IO?

I'm using Node.js, Express.js and Socket.IO.

hexacyanide
  • 88,222
  • 31
  • 159
  • 162
viniciuswebdev
  • 1,286
  • 1
  • 11
  • 20

1 Answers1

10

Use the Socket.IO authentication setting, and pass the cookies to the cookie parser middleware from Express. Once the cookie is parsed, you can get the session ID of the client, and fetch the associated session from the session store, whether it is a memory story or other type of store.

// we need to use the same secret for Socket.IO and Express
var parseCookie = express.cookieParser(secret);
var store = /* your MemoryStore, RedisStore, etc */;

io.set('authorization', function(handshake, callback) {
  if (handshake.headers.cookie) {
    // pass a req, res, and next as if it were middleware
    parseCookie(handshake, null, function(err) {
      handshake.sessionID = handshake.signedCookies['connect.sid'];
      // or if you don't have signed cookies
      handshake.sessionID = handshake.cookies['connect.sid'];

      store.get(handshake.sessionID, function (err, session) {
        if (err || !session) {
          // if we cannot grab a session, turn down the connection
          callback('Session not found.', false);
        } else {
          // save the session data and accept the connection
          handshake.session = session;
          callback(null, true);
        }
      });
    });
  } else {
    return callback('No session.', false);
  }
  callback(null, true);
});

Each time a client attempts to connect, the authorization function is run. It takes the handshake header cookies (handshake.headers.cookies), and passes them to express.cookieParser(). The cookie parser then finds the session ID, and then searches the store for the associated session. Then, we store the associated session into handshake.session, so we can access it like this:

app.get('/', function(req, res) {
  req.session.property = 'a value';
});

io.sockets.on('connection', function(socket) {
  var session = socket.handshake.session;
  session.property // a value
});
johnc
  • 39,385
  • 37
  • 101
  • 139
hexacyanide
  • 88,222
  • 31
  • 159
  • 162
  • Thanks for help! But Im getting "TypeError: Cannot read property 'connect.sid' of undefined", you now what im doing wrong? – viniciuswebdev Sep 29 '13 at 21:00
  • The cookie name might vary. It might be `express.sid` instead, but you should check with a browser to verify. – hexacyanide Sep 29 '13 at 21:02
  • With console.log(handshake.signedCookies); it show "{}" and console.log(handshake.cookie) show "undefined". I do not know if I'm forgetting to add something. Thanks! – viniciuswebdev Sep 29 '13 at 21:05
  • It's actually `cookies` instead of `cookie`, sorry about the typographic error. – hexacyanide Sep 29 '13 at 21:06