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

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

目前,我可以通过使用req.user在我的应用程序path中访问由Passport.JS创build的用户:

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

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

我的问题是:是否有可能在io.sockets.on(...)作用域中编辑和“保存” socket.handshake.user ,以便更新后的用户将在app.get/post/all(...)显示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', ...} }); 

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

代码应该像这样:

 // 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', ...} });