1

我正在使用 Node.JS (0.10.28)、Passport.JS (0.2.0) + Passport-Google (0.3.0) 和 Passport.SocketIO (3.0.1)。


目前,我可以使用以下方法访问由 Passport.JS 在我的应用程序路径中创建的用户req.user

app.get('/profile', function(req, res) {
  // send user data
  res.send(req.user);
});

使用 Passport.SocketIO,我还可以访问用户:

io.sockets.on('connection', function(socket) {
  // get user data
  console.log(socket.handshake.user);

  //...
});

也可以req.user通过req._passport.session.user.property = new_property_valueapp.get/post/all(...)范围内使用来编辑和“保存”它。然后更新显示在io.sockets.on(...)用户对象中。

我的问题是:是否可以socket.handshake.userio.sockets.on(...)范围内编辑和“保存”,以便更新后的用户将在req.user中显示更改app.get/post/all(...)?我尝试了以下方法无济于事:

io.sockets.on('connection', function(socket) {
  // rename username
  socket.handshake.user.username = 'new_username';

  //...
});

...

app.get('/profile', function(req, res) {
  // send user data
  res.send(req.user); // returns {..., username: 'old_username', ...}
});
4

1 回答 1

2

使用Socket.io-Sessions(由制作 Passport.SocketIO 的同一作者编写)更改socket.handshake.user.io.sockets.on(...)

代码应如下所示:

// initialization ...
// ...

io.sockets.on('connection', function(socket) {
  socket.handshake.getSession(function (err, session) {
    // socket.handshake.user is now session.passport.user

    socket.on(...) { ... }
    // ....

    // test username change
    session.passport.user.username = 'foobar';

    // save session
    //  note that you can call this anywhere in the session scope
    socket.handshake.saveSession(session, function (err) {
      if (err) { // Error saving!
        console.log('Error saving: ', err);
        process.exit(1);
      }
    });
  });
});

//...

app.get('/profile', function(req, res) {
  // send user data
  res.send(req.user); // returns {..., username: 'foobar', ...}
});
于 2014-06-03T06:06:14.757 回答