Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Issue with res.redirect in middleware

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?

like image 907
Varun Singh Avatar asked Feb 03 '23 09:02

Varun Singh


1 Answers

You are doing way too many checks out there in my opinion. Only one route should handle user login (check for user & pass, and store the username in the session if succeeded) and you should assign the auth middleware only on the routes that require auth (not all).

I've put up a simplified example so you can understand my point:

The login route

app.post('/login', function (req, res) {
  var variables_set = (req.body.user && req.body.pass);
  if (variables_set && (req.body.user === 'username') && (req.body.pass === 'password')) {
    req.session.username = req.body.user;
  } else {
    res.redirect('/login?failed=true'); 
  }
});

The auth middleware

if (!req.session.username) {
  res.redirect('/login');
} else {
  next();
}

You can see a more complete example in action in Alex Young's Nodepad application: https://github.com/alexyoung/nodepad (tutorials for that app here: http://dailyjs.com/tags.html#lmawa )

like image 108
alessioalex Avatar answered Feb 05 '23 14:02

alessioalex