Unable to save variables in express session
I am trying to create session based authentication for my web application. 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 also have middleware that guarantees user authentication when accessing protected 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 function authenticate
. Thank you in advance.
EDIT:
This is how I use my middleware:
router.use(validateRequest);
source to share
You don't have req
in another function as it is out of scope . You can put req in the global scope, then you can access it in any other function global.req=req
and then refer to it in another function with global.req
as the function will have req passed to the scope and not the top frame
Now I realized that the router is running until req.session.user
set toresult
source to share