Only allow passportjs authenticated users to visit protected page
Problem
Is placing this code inside of a route enough to protect pages from unauthenticated users?
if (!req.user) return res.send(401, "Not allowed in");
Problem courtesy of: egidra
Solution
You can use req.isAuthenticated()
to check if the request is authenticated or not.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login')
}
app.get('/server', ensureAuthenticated, routes.server.get);
app.get('/login', routes.login.get);
Or like this
app.all('*', function(req,res,next){
if (req.params === '/' || req.params === '/login')
next();
else
ensureAuthenticated(req,res,next);
});
Solution courtesy of: user568109
Discussion
View additional discussion.