Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js run function on session expiry Express & Passport

I have got a maximum session time setup using the following code (with Express.js & Passport.js).

  app.use(express.session({
    cookie: {
      maxAge : 3600000
    }
  }));

I would like to run a function if a session expires (for my log file and analytics). Something along the lines of this:

app.use(express.session.onExpiry(function(user){
        console.log('User session for ' + user + ' has expired.')
    });
);
like image 452
Paul Avatar asked Nov 10 '22 09:11

Paul


1 Answers

What you're doing is setting a cookie "expires" parameter. Browser will clear the cookie up once it expires and you won't know about it — it simply will not arrive along with one of future requests.

Trick you can use to acutaly know if cookie is expired is to write a timestamp into a cookie and set its lifetime ("expires" value) to some faraway time (say, year 2037). This way you can manually check if you still want to treat a given cookie as valid or if you want to renew it.

Sadly, you'd have to write your own code along the lines of

app.use(function(req, res, next) {
    //Checking previously set cookie (if there is one)
    var session = JSON.parse(req.cookies['session'] || '');
    if (session && new Date(session.expires) < new Date()) {
        console.log('User session has expired.')
    }

    //Resetting the cookie
    res.cookie('session', JSON.stringify({ session: <sessionIDKeyHere>, expires: Date.now() + 3600000 }), {
        expires: new Date(2037, 0, 1),
        httpOnly: true,
        secure: true //Do you have https? If no, set to false
    });

    next();
});
like image 70
Arseny Smoogly Avatar answered Nov 14 '22 22:11

Arseny Smoogly