How to know if user is logged in with passport.js?
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>
Solution 1:
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 2:
If you would like to use it in your templates as your code sample seems to indicate you can create some middleware such as this:
app.use(function (req, res, next) {
res.locals.login = req.isAuthenticated();
next();
});
Place that code somewhere after you have setup passport.
And then use it in your template (swig example)
{% if login %}
<button>logout</button>
{% else %}
<button>login</button>
{% endif %}