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

RMontes13 picture RMontes13 · Sep 11, 2013 · Viewed 83.4k times · Source

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)
   <button>logout</button>
else 
   <button>login</button>

Answer

moka picture moka · Sep 11, 2013

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
});