I'm trying to use a authenticateUser() middleware before loading all of my pages. Instead of including it in each call (as in app.get('/', authenticateUser, function()...)), I tried setting it with app.use(authenticateUser) right before calling app.use(app.router).
This didn't work, however. authenticateUser is basically:
if (req.session.loginFailed) {
next()
else {
if (req.session.user_id) {
...
if (userAuthenticated) {
next();
} else {
req.session.loginFailed = true;
console.log('setting loginFailed to true');
res.redirect('/login');
}
}
}
And then in app.get('/login') I set req.session.loginFailed to be false;
This should work, but I only want to call it on an app.get() or app.post() etc. for one of my actual pages. I think its getting called lots of times for many different requests (because upon loading one page, 'setting loginFailed to true' is called many times)
Is there a better way to do this? Or should I simply be calling it before every page on my site?