如何在快递中访问会话,在req之外?

时间:2011-06-18 17:10:18

标签: javascript node.js express socket.io

我知道我可以使用

function(req, res) {
    req.session
}

使用快递。但是我需要访问响应函数之外的会话。我该怎么做呢?

我正在使用socket.io来传递添加帖子和评论的信息。因此,当我在服务器端收到socket.io消息时,我需要使用会话验证发布信息的人。但是,由于这是通过socket.io完成的,因此没有req / res。

4 个答案:

答案 0 :(得分:10)

我想我有不同的答案。

代码:

var MongoStore = require('connect-mongo')(session);
var mongoStore = new MongoStore({
    db:settings.db,            //these options values may different
    port:settings.port,
    host:settings.host
})
app.use(session({
    store : mongoStore
    //here may be more options,but store must be mongoStore above defined
}));

然后你应该在req中定义一个会话密钥,就像:

代码:

req.session.userEmail;

最后,你可以这样做:

代码:

var cookie = require("cookie"); //it may be defined at the top of the file
io.on("connection",function(connection){

 var tS = cookie.parse(connection.handshake.headers.cookie)['connect.sid'];
 var sessionID = tS.split(".")[0].split(":")[1];
 mongoStore.get(sessionID,function(err,session){
      console.log(session.userEmail);
 });
}

我昨天测试了它,效果很好。

答案 1 :(得分:7)

使用socket.io,我以一种简单的方式完成了这项工作。我假设你的应用程序有一个对象,让我们说MrBojangle,因为它叫做Shished:

/**
 * Shished singleton. 
 *
 * @api public
 */
function Shished() {
};


Shished.prototype.getHandshakeValue = function( socket, key, handshake ) {                          
    if( !handshake ) {
        handshake = socket.manager.handshaken[ socket.id ];                                         
    }
    return handshake.shished[ key ];                                                                
};                                                                                                  

Shished.prototype.setHandshakeValue = function( socket, key, value, handshake ) {                   
    if( !handshake ) {
        handshake = socket.manager.handshaken[ socket.id ];                                         
    }
    if( !handshake.shished ) {
        handshake.shished = {};                                                                     
    }
    handshake.shished[ key ] = value;                                                               
};

然后在您的授权方法上,我使用MongoDB进行会话存储:

io.set('authorization', function(handshake, callback) {
    self.setHandshakeValue( null, 'userId', null, handshake );
    if (handshake.headers.cookie) {
        var cookie = connect.utils.parseCookie(handshake.headers.cookie);
        self.mongoStore()
        .getStore()
        .get(cookie['connect.sid'], function(err, session) {
            if(!err && session && session.auth && session.auth.loggedIn ) {
                self.setHandshakeValue( null,
                            'userId',
                            session.auth.userId,
                            handshake );
            }
        });
    }

然后在模型中保存记录之前,您可以执行以下操作:

model._author = shished.getHandshakeValue( socket, 'userId' );

答案 2 :(得分:1)

我相信检查socket.handshake可以让你参加会议:

io.sockets.on('connection', function(socket) { 
  console.log(socket.handshake.sessionID);
});

当客户端与socket.io服务器建立套接字连接时,客户端发送WebSocket握手请求。我上面所做的就是从握手中获取会话ID。

答案 3 :(得分:0)

假设你的socket.io代码看起来像这样:

io.on('connection',
function(client) {
  console.log(client.request)
});

请求为client.request,如上例所示。

编辑: 作为一个单独的事情,也许这会有所帮助: https://github.com/aviddiviner/Socket.IO-sessions