How to protect routes in express.js?
14,594
I'm not familiar with Meteor, but you can do something like the following, assuming you want to make pages available to only authenticated users (passport).
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated())
return next();
else
// Return error content: res.jsonp(...) or redirect: res.redirect('/login')
}
app.get('/account', ensureAuthenticated, function(req, res) {
// Do something with user via req.user
});
The ensureAuthenticated
function is just an example, you can define your own function. Calling next()
continues the request chain.
Author by
Sato
Updated on September 06, 2022Comments
-
Sato over 1 year
For example, in Meteor, there's something like
Router.plugin('ensureSignedIn'); Router.plugin('ensureSignedIn', { except: ['home', 'atSignIn', 'atSignUp', 'atForgotPassword'] });
So unsigned user cannot access other routes except above four.
How to do this in express.js? I'm using passport.js also.