ExEdzy
ExEdzy

Reputation: 129

How to get cookie expiration time in Rails?

I readed here: Get cookie expiration

that only name and value are sent to the server so no other cookie data is available.

That means that there is no way to get the expiration date of the cookie? So i have to save that date in my database, if i need it later?

Upvotes: 5

Views: 4486

Answers (2)

Michael Trojanek
Michael Trojanek

Reputation: 1943

While the accepted answer is right, I came here because I wanted to make sure that my application sets a permanent cookie (with a expiration date in the far future) and not a normal one.

If you want to verify that this is the case (and you do not care about the exact expiration date), you can set an expectation like this (the example uses the Mocha gem):

ActionDispatch::Cookies::PermanentCookieJar.any_instance.expects(:[]=).with(:key, "value").once

This expectation will pass with exactly one call of cookies.permanent[:key] = "value" but will fail for cookies[:key] = "value".

It also works for signed cookies (cookies.permanent.signed[:key] = "value"). However, note that a signed cookie will have its value encrypted based on your application's secret_key_base, so you will have to adjust the expectation to something like

ActionDispatch::Cookies::PermanentCookieJar.any_instance.expects(:[]=).with(:key, anything).once

instead.

Upvotes: 0

Stefan
Stefan

Reputation: 114188

That's right, only cookie-name and cookie-value are returned.

This is not a shortcoming of Rails or PHP, it is defined this way in RFC 6265:

Notice that the cookie attributes are not returned. In particular, the server cannot determine from the Cookie header alone when a cookie will expire, for which hosts the cookie is valid, for which paths the cookie is valid, or whether the cookie was set with the Secure or HttpOnly attributes.

Upvotes: 11

Related Questions