Search code examples
node.jsexpressmean-stackmeanjs

how to determine logged in user in a mean stack application


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?


Solution

  • 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.