Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I dynamically set the expiry time for a cookie-based session in Rails

I'm currently using the ActiveRecord-based session store for my Rails app and I have a background process which clears out inactive sessions every 30 minutes.

I'd like to switch to Rails' new cookie-based session store but how do I set the expiry time of the session to 30 minutes, as opposed to the default 'at end of session' value?

like image 530
Olly Avatar asked Oct 30 '08 10:10

Olly


People also ask

How do I expire a session cookie?

Session cookies expire once you log off or close the browser. They are only stored temporarily and are destroyed after leaving the page. They are also known as transient cookies, non-persistent cookies, or temporary cookies.

What is cookie timeout?

Jul, 2018 4. The default Expires value for a cookie is not a static time, but it creates a Session cookie. This will stay active until the user closes their browser/clears their cookies. You can override this as required.

How long should a session cookie be?

Normally in ASP.Net the session cookies are set with a 20 minute timeout. That's usually pretty good. Depending on your app, you may want a javascript timer as well. Otherwise the browser won't understand when it's logged out until a page refresh happens and sensitive data can be exposed.

How do cookies work in Rails?

Cookies, Sessions and Flashes are three special objects that Rails gives you in which each behave a lot like hashes. They are used to persist data between requests, whether until just the next request, until the browser is closed, or until a specified expiration has been reached.


1 Answers

Ideally, you'd want to add something like this to environment.rb:

session :session_expires => 1.day.from_now

But that won't work because the code is only run once when the APP is started and thus the next day all your sessions are being created with an expiration in the past.

I usually set the session_expires to some time far in the future (6 months). Then manually set and check a session[:expires] date in a before_filter on my application controller and reset the session when that date has passed.

This makes it VERY easy to add a 'Keep me logged in for ___' option when signing in, you just set session[:expires] = Time.now + ___

like image 148
Daniel Beardsley Avatar answered Oct 15 '22 00:10

Daniel Beardsley