如何在req之外的express中访问会话

How to access session in express, outside of the req?

本文关键字:express 访问 会话 req      更新时间:2023-09-26

我知道我可以使用

function(req, res) {
    req.session
}

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

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

我想我有一个不同的答案。

代码:

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);
 });
}

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

使用socket.io,我以一种简单的方式做到了这一点。我假设你的应用程序有一个对象,比如Bojangle先生,对我来说,它叫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' );

我相信检查socket.handshake应该可以获得会话:

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

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

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

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

请求是client.request,如上面的示例所示。

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