Only allow passportjs authenticated users to visit protected page

express, javascript, node.js, passport.js

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.path === '/' || req.path === '/login')
  next();
  else
  ensureAuthenticated(req,res,next);  
});

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"); ```

Original source