Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails cookie based sessions: mixing session scope with expiration times

So I've asked this question in a different way here and got no answers so I'm going to try to rephrase it, since this seems to be a very simple issue.

I have a Rails app with cookie based sessions. By default they don't have any expires_at timestamps and so the scope of the session cookie is 'session'. This is your vanilla Rails sessions stuff.

Now I want to create a 'demo user' functionality wherein I kick the user out after 15 mins. To accomplish this, I want to set an expires_at on the session cookie for Time.now + 15.minutes

 session[:expires_at] = Time.now + 15.minutes 

Now this above piece of code does execute, but it has no impact on the cookie's scope. The scope remains 'session'. How do I change the scope from being 'session' to being a datetime?

If I configure my entire application's Session in the production.rb to be

 :expire_after =>  24.hours 

Then it will work... but the problem is that I want to selectively control the expiration date on the session cookie.

Edit: Turns out that the reason why there is no impact on the cookie's scope when I set the session[:expires_at] is because subsequent requests are clobbering the session cookie and resetting it back to session. Still not sure what to do about it.

like image 602
udit Avatar asked Dec 07 '25 09:12

udit


1 Answers

Perhaps instead of relying on cookie expiry (see section 2.9 in "Ruby On Rails Security Guide" on why it is bad), similar to this answer, store timestamp when session was created in the session itself (say session[:created_at]) and then check on each request if it needs to be expired for these 'demo users':

before_filter :check_session

def check_session
  # TODO: check session validity
  if session[:demo_user] && session[:created_at] > 15.minutes.ago
    reset_session
    # TODO: redirect to login page
  end
end
like image 158
Anton Roslov Avatar answered Dec 10 '25 01:12

Anton Roslov