Reputation: 61
What I am trying to do is
-> use a logic form which posts to '/check_user'
-> check_user has logic to generate session and it creates the session perfectly
-> then it redirects to '/chat' which is restricted by verify() function
-> verify checks the session if persists (AT THIS POINT SESSION IS ALWAYS UNDEFINED FOR SOME REASON)
--> check_user does create session and it persists there but when redirected to '/chat' and hits verify, the session is lost.
Here is the code snippet I am using, I am not using any templating engines but plain HTML files. Any help is highly appreciated. Thanks!
app.use(express.static(__dirname + '/public'));
app.get('/login', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});
app.get('/chat', verify, function(req, res){
res.sendfile(__dirname + '/public/chat.html');
});
// when login form is posted to check_user, handle the username and passwords validation.
app.post('/check_user', function(req, res){
req.session.regenerate(function(){
req.session.user = "test";
//debugging codes debug code 1
console.log("3");
console.log(req.session.user);
//End debugging codes
res.redirect('/chat');
});
});
function verify(req, res, next) {
console.log(req.session.user);
if (req.session.user) {
console.log("1");//debug code 2
next();
} else {
console.log("2");//debug code 3
req.session.error = 'Access denied!';
res.redirect('/login');
}
};
Upvotes: 1
Views: 1429
Reputation: 61
Fixed! it. The problem was I was using res.render after ajax submit. I used window.location on ajax submit and it worked.
And another thing I found out is,
removing this closure made my session persistant throughout my application
req.session.regenerate(function(){
});
Upvotes: 1