how to determine logged in user in a mean stack application

763 views Asked by At

I'm writing an app based on mean.js boiler plate

In my server code (express) I need to make some decisions which are based on knowing who the logged in user is

I have passport local accounts implemented.

How can I determine in the server code the identity of the current logged in user?

2

There are 2 answers

0
pgrodrigues On BEST ANSWER

If you are using passport you just have to access req.user as it was already mentioned.

Taking a look at your gist, my guess is that some of your routes are defined much earlier than app.use(passport.initialize()); and app.use(passport.session());, which means that if you receive a request to get /opportunity_ids (for example), req.user is yet to be populated.

If you go a little bit further in the stack you will notice that all the other routes are injected after passport is initialized in the line:

// Globbing routing files
config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
    require(path.resolve(routePath))(app);
});

The solution would be to put all your custom routes defined before passport initilization in ./app/routes/**/ and let the route files be automatically globbed. req.user won't be undefined.

The order in which each middleware is placed is extremely important and might produce unexpected behavior if that order is changed.

1
Bidhan On

If a user is logged in, passport.js will create a user object for every request. It sets the user as a property on the request(req.user). You can access any properties of the user through that object. For example: req.user.username, req.user.email etc.