Using Node.js and Express, I want to have users who are not logged in always redirected to the main page. What is the simplest way of achieving this? Ideally I'd not have to add code to every route checking whether someone's logged in.
I work on node a long time ago but it should works
function requireLogin(req, res, next) {
if (req.session.loggedIn) {
next(); // allow the next route to run
} else {
// require the user to log in
res.redirect("/"); // or render a form, etc.
}
}
// Automatically apply the `requireLogin` middleware to all
// routes starting with `/`
app.all("/*", requireLogin, function(req, res, next) {
next(); // if the middleware allowed us to get here,
// just move on to the next route handler
});
It depends on how you define 'not logged in', but say that status is stored in req.session. In that case, you could add a middleware that will redirect not-logged-in users to a login page:
app.use(function(req, res, next) {
if (req.path === '/loginpage') // pass requests for login page
next();
else
if (! req.session || req.session.isLoggedIn !== true) // check logged in status
res.redirect('/loginpage'); // redirect to login page when not logged in
else
next(); // else just pass the request along
});
app.get('/loginpage', function(req, res) {
res.send('login page');
});
You can user something like passport.It makes checking the authorized routes a lot simpler
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login') //Or whatever your main page is
};
You can now check your routes like this
app.get('/account',ensureAuthenticated,routes.account);