How to know if user is logged in with passport.js?
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});
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 %}
It is not explicitly documented but there is a isAuthenticated()
method which is inserted into req
by passport.
Can be used as follows,
req.isAuthenticated() // returns true if auth, false if not
// auth.jsmodule.exports = { ensureAuthenticated: (req, res, next) => { if (req.isAuthenticated()) { return next() } res.redirect('/login') // if not auth }, forwardAuthenticated: (req, res, next) => { if (!req.isAuthenticated()) { return next() } res.redirect('/dashboard'); // if auth }}
// app.jsapp.get('/dashboard', ensureAuthenticated, (req, res) => res.render('dashboard'))app.get('/login', forwardAuthenticated, (req, res) => res.render('login'))app.get('/register', forwardAuthenticated, (req, res) => res.render('register'))