Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renewing/Refreshing Express Session

In my app I restrict some access to some actions and pages if a user is not logged in. I have:

var restrict = function(req, res, next) {
    if (!req.user) {
      console.log("USER isn't logged in.")
      return res.status(403).send('Access or action denied, please log in'); 
    }
    next();
}


app.get('/stocks', restrict, MainHandler.findAllStocksFromUser);
app.get('/stocks/:id', MainHandler.findStockByIdAndDates);
app.put('/stocks/:id/stockActions', restrict, MainHandler.handleStockAction);

I'm essentially trying to refresh a session everytime the client makes a request to the server so that the server doesn't logout the user/destroy the session when it shouldn't. For testing, I want the session to expire/the user to be logged out if 20 seconds go by without the user making an requests to the server. I have:

    app.use(session({secret: 'secret', saveUninitialized: true, resave: true, expires: new Date(Date.now() + (20000))}));

Then I try to use middleware to refresh the expiration date every time the use makes a request:

// Session-persisted message middleware
app.use(function(req, res, next){
  req.session.cookie.expires = new Date(Date.now() + 20000);
  next();
});

But if I log in from the client, and click around, causing requests to the server, I still get the log-in error on the client after 20 seconds, despite trying to "refresh" the session in the middleware. I have also tried using maxAge using the same strategy with the middleware. Any ideas? Thanks!

like image 686
gcc Avatar asked Aug 09 '15 20:08

gcc


People also ask

What is req session in express?

The session middleware handles all things for us, i.e., creating the session, setting the session cookie and creating the session object in req object. Whenever we make a request from the same client again, we will have their session information stored with us (given that the server was not restarted).

How do I keep a session alive in node JS?

Try something like: app. use( session( { secret: 'keyboard cat', cookie: { maxAge: 60000 }, rolling: true, resave: true, saveUninitialized: false } ) );

What is Express-session in node JS?

The express-session module provides a method and properties that can set and get the values from the session. Express Sessions are used in a Node js web application to maintain the state of a user. To install express-session, type the npm install express-session –save command in your terminal or command-line tools.


2 Answers

You can try define your session as follows

app.use (
   session ({
      secret: "secret",
      saveUninitialized: true,
      resave: true,
      cookie: {
         expires: 20 * 1000
      }
   })
);

and then refresh the session using

req.session.touch()

or you could define your session as

app.use (
   session ({
      secret: "secret",
      saveUninitialized: false,
      resave: true,
      rolling: true,
      cookie: {
         expires: 20 * 1000
      }
   })
);

and it will renew the session automatically and it will only expire when it has been idle for the value in the expires variable

like image 63
TheLovelySausage Avatar answered Oct 03 '22 04:10

TheLovelySausage


express-session supports a duration-based maxAge setting, which will work better than setting a fixed date for all sessions. So your middleware usage should instead look like:

app.use(session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true,
  maxAge: 20000
}));

Next, to update the expiration of the session, you can just call req.session.touch(); if that is all you're doing to the session and its contents.

The documentation has a lot of other good information on controlling session expiration and related topics.

like image 44
mscdex Avatar answered Oct 03 '22 04:10

mscdex