Search code examples
javascriptnode.jspassport.jspassport-local

Get the current user outside of a route using Passport.js


I am using the latest version of Express (4.x) and Passport.js (0.13) in my Node.js application. I can get the current user object inside of a route by using req.user and working with the object, which works. However, for situations outside of routing, is there a method I can call or global object I can access which contains the same information?

The reason I want to do this is I have a Socket.io listener which waits for a message string to be sent. It then gets the currently logged in user, gets their ID and uses that for the database association. This takes place outside of a route obviously.


Solution

  • Passport.js uses session to deserialize the user and have it store at express.js req object. So to authenticate the user in Socket.io, you need to find the session using the cookie, lookup the session in the session store and finally get the user from the session.

    You can use Socket.io middlewares to achieve this. Here is a pseudo-code to get you started:

    var io = require('socket.io')();
    io.use( (socket, next) => {
      if (socket.request.headers.cookie) {
        // find the session id in cookie
        const sessionID = socket.request.headers.cookie['connect.sid']
    
        // lookup the sessionID in session store
        MongoStore.get(sessionID, (err, session) => {
          // get the userID from the session
          const userID = session.passport.user;
          // Lookup user using the UserID
          User.find(userID, (err, user) => {
    
             //save the user in socket
             socket.user = user;
             next();
          })
    
        })
      }
      next(new Error('Authentication error'));
    });