2

I am using Node.JS (0.10.28), Passport.JS (0.2.0) + Passport-Google (0.3.0), and Passport.SocketIO (3.0.1).


Currently, I am able to access the user created by Passport.JS in my app's paths by using req.user:

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

Using Passport.SocketIO, I am also able to access the user in:

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

  //...
});

It is also possible to edit req.user and 'save' it by using req._passport.session.user.property = new_property_value in the app.get/post/all(...) scope. The updates then show up in io.sockets.on(...) user object.

My question is: Is it possible to edit and 'save' socket.handshake.user in the io.sockets.on(...) scope so that the updated user will show the changes in req.user in app.get/post/all(...)? I have tried the following to no avail:

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', ...}
});
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
rgajrawala
  • 2,148
  • 1
  • 22
  • 35

1 Answers1

2

Use Socket.io-Sessions (written by the same author who made Passport.SocketIO) to change socket.handshake.user in io.sockets.on(...).

Code should look like this:

// 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', ...}
});
rgajrawala
  • 2,148
  • 1
  • 22
  • 35