Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to know if user is logged in with passport.js?

How to know if user is logged in with passport.js?

Problem

I've been reading passport.js info and samples for two days, but I'm not sure after that I did all the process of authenticating.

How do I know if I'm Logged in, for example, I'll have a navigation bar with a login or logout button, is there some variable like code below?

if (login)
   
else 
   
Problem courtesy of: RMontes13

Solution

If user is logged in, passport.js will create user object in req for every request in express.js, which you can check for existence in any middleware:

if (req.user) {
    // logged in
} else {
    // not logged in
}

You can create simple express.js middleware for that, that will check if user is logged in, and if not - will redirect to /login page:

function loggedIn(req, res, next) {
    if (req.user) {
        next();
    } else {
        res.redirect('/login');
    }
}

And use it:

app.get('/orders', loggedIn, function(req, res, next) {
    // req.user - will exist
    // load user orders and render them
});
Solution courtesy of: moka

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to know if user is logged in with passport.js?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×