I am trying to implement a session time out for a nodejs + express + passport app. I am using setTimeOut() to call a method where I am calling req.session.destroy() and req.logout() (for logging out passport session) to invalidate the session.
I am passing in the req and res to setTimeOut - setTimeOut(timeOutMethod, 10000, req, res). I see the session being set to null. I verified the request objects during different times, and they match.
I want to be able to call /logout endpoint in the timeOutMethod() (this is a callback for the setTimeOut()) or go back to the main page, but there will be no context. I can't use a res object to redirect the user. The app actually crashes at this point.
Is there anyway we can redirect or refresh the page so that user the sent back to the login screen?
Can someone please help me with this? Thanks a ton in advance!
:Code:
router.get(callback_url, passport.authenticate(login_strategy, {failureFlash: true, failureRedirect: '/page'}),
function (req, res) {
if(req && req.session){//max timeout is set to 1 min for testing...
setTimeout(sessionTimeOut, 1 * 60 * 1000, req, res);
}
res.redirect('/');
});
// a callback for session timeout...
function sessionTimeOut(req, res){
if (req.session) {
req.session.destroy(err => {
if (err) {
//log statements
}
else {
//log statements
if (req.user) {
//remove passport.js session user value if present
req.logout();
}
}
});
req.session = null;
}
else {
//log statements
}
res.redirect('/page');
}
//error thrown when es.redirect('/page') as we don't have the context here.
_http_outgoing.js:561
[0] throw new ERR_HTTP_HEADERS_SENT('set');
[0] ^
[0]
[0] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[0] at ServerResponse.setHeader (_http_outgoing.js:561:11)