Reputation: 7635
I am using passport.js and express4.js. I would like to know if there is an automatic way to verify if the client as opened a session with passport.js when he try to access a view?
Actually I am doing like this to verify if the client can access an url:
router.get('/[0-9]{3}/', function(req, res, next){
var path_codecs = req.originalUrl.split('/')[2];
if (!req.user) {
res.redirect('/login');
}
if (req.user.dataValues.codecs !== path_codecs) {
next();
}
res.render('decoupage')
});
Do I have to do this verification at each view I want to restrict to session user or is there a more automatic way to define what views can be accessed and not?
Upvotes: 0
Views: 39
Reputation: 29261
You can use req.user
(which Passport will set after a successful authentication).
I usually use this in a thin middleware like so:
function isAuthenticatedMiddleware (req, res, next) {
if (req.user) { return next(); }
next('AuthenticationError');
}
router.get('/[0-9]{3}/', isAuthenticatedMiddleware, function(req, res, next){
You can easily add this to all routes on a router with express's router.all
router.all('*', isAuthenticatedMiddleware);
Upvotes: 3