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");
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");
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.path === '/' || req.path === '/login')
next();
else
ensureAuthenticated(req,res,next);
});
It's enough as long as you aren't leaking a route somewhere. Just make sure your routes are in the proper order.
//checks to be sure users are authenticated
app.all("*", function(req, res, next){
if (!req.user)
res.send(403);
else
next();
});
//additional routes will require authentication due to the order of middleware
app.get("/admin", ....
However, if you moved the admin route above the global one, the admin route would no longer be protected. You might want to purposefully put your login page earlier so it doesn't require authentication for example.
A correction for user568109's answer, with express 4 the code must be like this :
app.all('*', function(req,res,next) {
if (req.path === '/' || req.path === '/login')
next();
else
ensureAuthenticated(req,res,next);
});