首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Node.JS + Passport.SocketIO:编辑和保存`socket.handshake.user`属性

Node.JS + Passport.SocketIO:编辑和保存`socket.handshake.user`属性
EN

Stack Overflow用户
提问于 2014-06-02 06:09:05
回答 1查看 1.6K关注 0票数 2

我使用的是Node.JS (0.10.28)、Passport.JS (0.2.0) +Passport-Google0.3.0和Passport.SocketIO (3.0.1)。

目前,我可以通过使用Passport.JS访问应用程序路径中的req.user创建的用户

代码语言:javascript
复制
app.get('/profile', function(req, res) {
  // send user data
  res.send(req.user);
});

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

代码语言:javascript
复制
io.sockets.on('connection', function(socket) {
  // get user data
  console.log(socket.handshake.user);

  //...
});

还可以通过在req.user作用域中使用req._passport.session.user.property = new_property_value来编辑app.get/post/all(...)并保存它。然后,更新将显示在io.sockets.on(...)用户对象中。

我的问题是:是否可以在socket.handshake.user范围内编辑和“保存”io.sockets.on(...),以便更新的用户能够在app.get/post/all(...)中显示req.user中的更改?我尝试了以下几点,但没有结果:

代码语言:javascript
复制
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', ...}
});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-03 06:06:14

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

代码应该如下所示:

代码语言:javascript
复制
// 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', ...}
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23988240

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档