如何在socket.io事件中访问快速会话?

时间:2014-03-23 15:18:49

标签: node.js session express websocket socket.io

我目前正在玩express和socket.io并构建了一个只接受来自已登录用户的socket.io连接的应用程序。我举了一个简单的例子。请参阅 io.sockets.on('连接')部分,尤其是:

var express = require('express');

var app = express();
var http = require('http').createServer(app);

var io = require('socket.io').listen(http);

var sessionStore = new express.session.MemoryStore();

io.set('authorization', function (handshake, accept)
{
    // I got this from a gist.
    // Don't know the link anymore, though.
    var cookies = require('express/node_modules/cookie').parse(handshake.headers.cookie);
    var parsed = require('express/node_modules/connect/lib/utils').parseSignedCookies(cookies, 'SESSION_SECRET');

    sessionStore.get(parsed.sid, function (error, session)
    {
        if (error != null)
        {
            accept(error, false);
            return;
        }

        if (session != null && session.user != null)
        {
            accept(null, true);
        }
        else
        {
            accept('Not a logged in user.', false);
        }
    });
});

io.sockets.on('connection', function (socket)
{
    // client with an user object in his session (= logged in)
    // connected. But how can I access this session in here?
});

app.use(express.cookieParser('COOKIE_SECRET'));

app.use(express.session({
    secret: 'SESSION_SECRET',
    key: 'sid',
    store: sessionStore
}));

app.use(express.urlencoded());
app.use(express.json());

app.get('/', function (request, response)
{
    response.sendfile('static/index.html');
});

app.post('/', function (request, response)
{
    request.session.user = null;

    var post = request.body;

    if (post.username === 'admin' && post.password === 'admin')
    {
        request.session.user = post;
    }

    response.redirect('/');
});

http.listen(80);

一切都在这一点上起作用。只有在会话中有用户的用户(=他们已经登录)才能通过socket.io连接。但是,我目前仍然坚持客户实际这样做,因为我无法在这一点上获得会话。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

如果我已经理解了这个问题,那么您希望稍后使用socket对象进行快速会话。你可以这样做:

if (session != null && session.user != null){
   accept(null, true);
   handshake.session = session;
}

你可以通过这样做来访问它:

socket.handshake.session

希望这会起作用

答案 1 :(得分:0)

您可以使用passport.socketio