开发者

Set Rack session cookie expiration programmatically

开发者 https://www.devze.com 2023-01-03 12:01 出处:网络
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.

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 cli开发者_如何学Gocked "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?


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.


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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号