Question

We're using Node + Connect to manage sessions for our app, which is a single-page application (SPA) built with Backbone.js. I'm trying to write some code which will check from the client if the session is still valid. I know I can do it in Node itself, but as this is an SPA, I need to be able to do it completely client-side.

My first thought was to read the connect.sid cookie with jQuery and if it wasn't there, then that would mean that the session is expired. Unfortunately, that session cookie is protected with the HttpOnly flag and for good reason. I don't want to disable that.

My second thought was to write a second, parallel cookie every time the connect.sid cookie is written. This second cookie would only store the expire date of the session cookie and would set HttpOnly to false so that the client could read it.

So my question is, how do I go about writing that second cookie, or is there a better solution for being able to detect session expiration status from the browser?

I know how to write cookies with Node, but I'm not sure where to put the code so that it will fire every time that Connect writes the main connect.sid session cookie. Additionally, I would like to be to read the expire date of the session cookie so that I can write it in my parallel cookie.

UPDATE: To be clear, I'm not looking to read the expiration date of the session. I know that JS cannot access the expires date of a cookie. I just want to see whether or not the cookie exists, as it will only exist when it's valid and therefore its absence is enough data for me.

Était-ce utile?

La solution

updated after clarifications in comments

Add another middleware right next to your session middleware. Excerpt below assumes express, but if you are using connect without express you should be able to interpret accordingly.

app.use(connect.session(sessionOptions));
app.use(function (req, res, next) {
   res.cookie("sessionIsAlive", "1", {
     //just make sure this matches your expiration time of the real session cookie
     expires: new Date(Date.now() + 900000),
     httpOnly: false
  });
  next();
});

Then you can check for the existence of that via javascript in the browser. And just FYI connect writes a new cookie with an updated expiration time on every response. That's how the "expires after N minutes of inactivity" behavior is implemented.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top