9

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");
laggingreflex
  • 32,948
  • 35
  • 141
  • 196
egidra
  • 8,537
  • 19
  • 62
  • 89

3 Answers3

28

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);  
});
Michael
  • 2,826
  • 4
  • 25
  • 18
user568109
  • 47,225
  • 17
  • 99
  • 123
  • 16
    Christ, thank god `isAuthenticated()` is **completely undocumented**. It's like the entire point of the library. Some day I'm going to find this Jared Hanson guy, send a drone with a big rubber hand on it to his house, and just smack him repeatedly for trolling the world with Passport. Thanks. – Jason C Dec 09 '16 at 01:45
3

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.

Brandon Joyce
  • 3,100
  • 24
  • 25
2

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);  
});
cyberbobjr
  • 239
  • 2
  • 6