Reputation: 575
How do I get logged in user data without making any request to any route (endpoint) ?
//how about I want to get logged in user's id here?
router.get('/',function(req,res,next){
//usually we get data here
}
I know we can the user's object using req.user.id
or store it to res.locals.userId = req.user.id
Upvotes: 0
Views: 75
Reputation: 707228
Your server can host zillions of users (it is multi-user). So, when you're not in a specific request from a specific user, there is no single "current" or "logged in" user.
Only when processing a request are you doing something on behalf of a specific user and thus there is a specific user associated with that request.
Depending upon how your login works, you may have a session store of some kind that has all the currently logged in users in it. The currently logged in user is typically figured out in a request by looking at a session cookie (for that request) and then looking up that session cookie in a local session store to get the user info from the session store.
If the point that you want the user info is in the establishment of a socket.io connection, then you can get access to the cookies at the time the socket.io connection is established via client.request.headers.cookie
. Using the cookies, you should be able to get your login session and then get access to any other session info you want (just the same as a normal http request).
io.on('connection', function(client) {
var cookie = client.request.headers.cookie;
// using the cookie, you should then be able to get to your login session
// using the session, you should be able to get to any other login data
});
A conceptual thing to remember is that the creation of a socket.io connection (which is based on a webSocket) always starts with a normal HTTP request (which is then protocol upgraded to a webSocket connection). As such, all the normal HTTP things are available at that time (such as cookies, headers, etc...).
If you have not yet implemented any sort of user authentication (that sets the above cookie), then you will need to either have the user authenticate before creating the socket.io connection (so the cookie is there when you access it above) or you will need to implement user authentication as part of the socket.io connection process which is something that is supported via socket.io middleware.
If you're having trouble accessing the cookie from passport, then see this: How to access Cookie set with Passport.js.
Upvotes: 1
Reputation: 1557
You could use express middleware and check for the user's id before any route is handled, then redirect accordingly.
Upvotes: 0