14

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Gerard
  • 4,818
  • 5
  • 51
  • 80

3 Answers3

4

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.

chris
  • 6,653
  • 6
  • 41
  • 54
0

Chris' answer actually didn't work for me. I found that I had to make sure that I included the original session 'options' with the new 'expire_after' value, so instead of:

env['rack.session.options'][:expire_after] = 2592000

I would use:

env['rack.session.options'].merge! expire_after: 2592000

and be sure to put the use Rack::Session::Cookie statement (without an expire_after setting) in you configure block, if you are using Sinatra.

This did the trick.

Gus Shortz
  • 1,711
  • 1
  • 15
  • 24
  • Don't forget that if you then subsequently set/delete anything in the session hash, the cookie will revert to the default expiry date (i.e. a session cookie). To make it persist through subsequent changes, you'll need to store a flag marking the "remember me" status within the session hash itself as well. – Richard Fairhurst Oct 07 '13 at 19:18
0

This probably has to be done before the session is loaded.

See Rack::Session::Cookie#load_session and Rack::Session::Cookie#commit_session

Rishav Rastogi
  • 15,484
  • 3
  • 42
  • 47