Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Rack session cookie expiration programmatically

I'm using Rack to try to implement "Remember Me" functionality in my Sinatra app.

I'm able to set the session cookie to expire when the session ends or in X seconds time but I'd like to do both.

For example, if a user has clicked "remember me" then I wish for their session to end after X seconds. Eg, my app.rb has a line that looks like this:

use Rack::Session::Cookie, :expire_after => 2592000, #30 days in seconds
                           :secret => MY_SECRET

I've tried to do the following when the user logs in:

if (!remember_me)
  env['rack.session.options'][:expire_after] = nil
end

However, this does not set the cookie value.

How to set this?

like image 868
Gerard Avatar asked Jun 16 '10 13:06

Gerard


1 Answers

I was trying to do the exact same thing and I figured out what the problem for me was. The session cookie gets set on every request if you have an expire_after time set. So when you say if (!remember_me), for that request the cookie's expire time gets set to nil. However, on the very next request, the session cookie is reinitialized with an expire time of 2592000. It seems the fix is to not set a default expire_after time and instead say:

# don't set default expire time
use Rack::Session::Cookie, :secret => MY_SECRET


if(remember_me) 
  env['rack.session.options'][:expire_after] = 2592000 
end

I have unfortunately not figured out how to have a default expire_after time and to permanently extend that time programatically.

like image 130
chris Avatar answered Sep 19 '22 15:09

chris