Based on a condition, I need to destroy user's current session, and redirect him to a login page with a message. I use flash
to have a show-once-only message. Everywhere, this works fine on my app except here, because here I use req.flash
after req.session.destroy()
.
How can I achieve this? I have tried placing req.flash()
before req.session.destroy()
but that does not work, I think because req.session.destroy()
clears the session where we just stored the flash message. Thanks.
if( req.session.adminUser.blocked ){
req.logout();
req.session.destroy(()=>{
req.flash("flashMessage", "You are blocked, Please contact admin");
req.session.save(function(){
res.redirect("/admin-panel/login");
return false;
});//session.save()
});
}
With this code, I get this error - Error: req.flash() requires sessions
. If I move the flash statement before the session.destroy
statement, then I do not get any error, but the message is not shown.
req.flash()
depends on a valid session, so if you destroy that session, the flash messages are destroyed as well.
It seems to me that it might actually be better to create a separate "blocked" page, and render that, instead of redirecting the blocked used back to the login page (where they can't log in anyway):
req.session.save(function(){
res.render("/admin-panel/blocked");
});
As a (less-pretty) alternative, you can pass a query string to the login page indicating that the user was blocked:
res.redirect("/admin-panel/login?blocked=true");
And use a check in the login-template to see if it should show a "you are blocked" message.