tdc
tdc

Reputation: 5464

determine when cookie will expire with node Request module

I'm writing an app that builds an API through scraping an external domain. In order to scrape the domain, my server must be authorized ( with a session cookie ).

I'm using the request module with a cookie jar to maintain the cookies across requests.

I want to set up some Node router middleware so that, if/when the session expires, I can re-run my authentication method. Think something like this:

export function validate(req, res, next) {
    const cookie = cookieJar.getCookie('**target domain**');
    const COOKIE_IS_EXPIRED = // ???
    if ( COOKIE_IS_EXPIRED ) {
        authenticate().then(next);
    } else {
        next();
    }
}

When I log out the contents of cookieJar.getCookies() my result is something like the following:

[ Cookie="lw_opac_1=1483019929431275955; Expires=Wed, 29 Mar 2017 13:58:49 GMT; Max-Age=7776000; Path=/opac; hostOnly=true; aAge=0ms; cAge=6345ms",
  Cookie="lw_opac=ta4tscsejs6c94ngikt7hlbcn0; Path=/; hostOnly=true; aAge=0ms; cAge=6347ms" ]

how can I validate when that both cookies are close to / have expired, and then re-run my auth function?

Thanks!

Upvotes: 1

Views: 4385

Answers (2)

shivshankar
shivshankar

Reputation: 2135

@rsp answer correct. But if you are going to maintain access security token you should move on csrf token which automatically maintain client side cookie and generate token for new session. For more detail http://www.senchalabs.org/connect/csrf.html

Upvotes: 1

rsp
rsp

Reputation: 111316

You can use the cookie module from npm to parse the cookies.

So, for example when you have a string like you posted:

var c = "lw_opac_1=1483019929431275955; Expires=Wed, 29 Mar 2017 13:58:49 GMT; Max-Age=7776000; Path=/opac; hostOnly=true; aAge=0ms; cAge=6345ms";

then running:

console.log(cookie.parse(c));

will result in printing:

{ lw_opac_1: '1483019929431275955',
  Expires: 'Wed, 29 Mar 2017 13:58:49 GMT',
  'Max-Age': '7776000',
  Path: '/opac',
  hostOnly: 'true',
  aAge: '0ms',
  cAge: '6345ms' }

You can use the Max-Age and Expires fields and use moment to parse them and compare them to the current time.

With moment you can compare the given date with today and get the number of hours or days of the difference. For example this:

moment().isAfter(someDate);

will tell you if that date has already passed (so if it's the expiration date then it will tell you if the cookie has expired).

See:

Upvotes: 3

Related Questions