1

I'm user passport.js for authentication for both express and socket.io servers. I've got this working through the use of passportSocketIo. When an authenticated user hits the server they are successfully deserialized and the success callback is hit.

However, I now want to access the deserialized users details and attach them to the socket for using in the core server functionality. Can anyone tell me where I can find these details?

For context, the implementation looks like this...

 passportSocketIo.authorize({
      cookieParser: cookieParser,       // the same middleware you registrer in express
      key:          'auth',       // the name of the cookie where express/connect stores its session_id
      secret:       'keyboard cat',    // the session_secret to parse the cookie
      store:        tediousConfig,        // we NEED to use a sessionstore. no memorystore please
      success:      onAuthorizeSuccess,  // *optional* callback on success - read more below
      fail:         onAuthorizeFail,     // *optional* callback on fail/error - read more below
    })(socket, next);

The success function is basic. I can find the deserialized user in the data parameter here, but in here I don't have access to the socket to permanently attach these details to.

function onAuthorizeSuccess(data, accept){
  const userId = data.user.id
  console.log(`User connected: ${userId}`)
  accept()
}

This function runs fine and I can access the user ID within the success function (as seen in the console.log).

One solution may be to also pass the socket into the success function and attach the details in here, but I don't understand where the 'data' and 'accept' parameters come from sufficiently well to be able to also pass these in.

There may also quite possibly be a much simpler solution to what I'm trying to do!

Any help gratefully received

cYee
  • 1,915
  • 1
  • 16
  • 24

2 Answers2

0

You can access your user object, which passport has added in for you by using:-

socket.request.user

Here is the link to the doc: https://github.com/jfromaniello/passport.socketio#socketrequestuser-as-of-v1

Here is the exact doc incase any changes to the doc

socket.handshake.user (prior to v1)
This property was removed in v1. See socket.request.user

socket.request.user (as of v1)
This property is always available from inside a io.on('connection') handler. If the user is authorized via passport, you can access all the properties from there. Plus you have the socket.request.user.logged_in property which tells you whether the user is currently authorized or not.

Note: This property was named socket.handshake.user prior to v1
cYee
  • 1,915
  • 1
  • 16
  • 24
-1

If anyone else comes across this I just accessed the socket with the user appended in a later io.use middleware.