Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Only allow passportjs authenticated users to visit protected page

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.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Only allow passportjs authenticated users to visit protected page

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×