Getting the current user in express.js, while using socket.io?

前端 未结 1 1707
时光取名叫无心
时光取名叫无心 2021-01-25 02:01

I\'m using the express framework, and part of my web app uses socket.io to enable real-time chat. I need to get the current user\'s username, and create a room with him in it. T

1条回答
  •  终归单人心
    2021-01-25 02:29

    This has been asked a few times but the older answers I found do not work anymore. The answer lies in parsing socket.handshake.headers.cookie but this is hacky and will depend on the internals of express-session.

    Anyways, this should work for now with Express 4 and socket.io 1.1:

    var express   = require('express'),
        session   = require('express-session'),
        cookie    = require('cookie'),
        signature = require('cookie-signature');
    
    var app    = express(), 
        store  = new session.MemoryStore(),
        secret = 'session-secret-key',
        name   = 'connect.sid';
    
    app.use(session({
      name:   name,
      secret: secret,
      store:  store,
      resave: true,
      saveUninitialized: true
    }));
    
    var server = require('http').createServer(app),
        io     = require('socket.io')(server);
    
    io.on('connection', function(socket) {
      if (socket.handshake && socket.handshake.headers && socket.handshake.headers.cookie) {
        var raw = cookie.parse(socket.handshake.headers.cookie)[name];
        if (raw) {
          // The cookie set by express-session begins with s: which indicates it
          // is a signed cookie. Remove the two characters before unsigning.
          socket.sessionId = signature.unsign(raw.slice(2), secret) || undefined;
        }
      }
      if (socket.sessionId) {
        store.get(socket.sessionId, function(err, session) {
          console.log(session);
        });
      }
    });
    

    0 讨论(0)
提交回复
热议问题