3

I am trying to build a session-based authentication for my web app. I have the following auth function:

function authenticate(req, res) {
  var body = req.body;

  getAuthUser(body.username, function (err, result) {

      if (hash(body.password) != result.password) {
          // invalid pass
          return;
      }

      req.session['user'] = result;
      res.redirect('/logged/panel');

      console.log(req.session); // 'user' session is displayed here
  });
}

I have also a middleware which ensures that user is authenticated when accessing secured content:

function validateRequest(req, res, next) {
  console.log(req.session); // 'user' session is not displayed here
  (req.session.user) ? next() : res.redirect('/login');
}

The problem is that my middleware does not see the stored variable by the authenticate function. Thank you in advance.

EDIT:

This is how I use my middleware:

router.use(validateRequest);

1 Answers1

2

You dont have req in the other function as it is out of scope. You can put req in global scope then you can access it in any other function global.req=req and then referencing to it in the other function with global.req as the function will have the req passed to in in scope instead of the one from the top frame

I now figured it out the router is running before req.session.user is set to result

mjz19910
  • 244
  • 1
  • 13