如何在请求之外以快速方式访问会话?

发布于 2024-11-16 02:36:16 字数 240 浏览 2 评论 0原文

我知道我可以使用

function(req, res) {
    req.session
}

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

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

I know that I can use

function(req, res) {
    req.session
}

using express. However I need to access the session outside of the response function. How would I go about doing that?

I'm using socket.io to pass information for adding posts and comments. So when I receive the socket.io message on the server-side, I need to verify the person posting the information by using the session. However since this is being done via socket.io there is no req/res.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

鸠书 2024-11-23 02:36:16

我想我有不同的答案。

code:

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 处定义一个会话密钥,就像:

code:

req.session.userEmail;

最后,你可以这样得到它:

code:

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

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

I think I have a different answer.

code:

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

then you should define a session key at req,just like :

code:

req.session.userEmail;

finally,you can get it this way:

code:

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

I had test it yesterday, it worked well.

薄荷梦 2024-11-23 02:36:16

使用 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' );

Using socket.io, I've done this in a simple way. I assume you have an object for your application let's say MrBojangle, for mine it's called 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;                                                               
};

Then on your authorization method, I'm using MongoDB for session storage:

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

Then before saving a record in the model, you can do:

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

月野兔 2024-11-23 02:36:16

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

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

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

I believe checking socket.handshake should get you the session:

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

When the client establishes a socket connection with your socket.io server, the client sends a WebSocket handshake request. What I'm doing above is grabbing the session ID from the handshake.

悲念泪 2024-11-23 02:36:16

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

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

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

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

Assuming your socket.io code looks kinda like this:

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

The request is client.request as shown in the example above.

Edit:
As a separate thing, maybe this would help:
https://github.com/aviddiviner/Socket.IO-sessions

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文