简体   繁体   中英

How to set session[:expires] in rack session (Sinatra)

You can set a session expiry for a Sinatra app when you set up the session engine:

  use Rack::Session::Cookie, :expire_after => 60*60*3, :secret => 'xxxx'

But I want to enable a longer session for certain users. Say two weeks.

    session[:expires] = ?? #how and where do I put this.?

Do I need to set on each call (before do?) or is once good enough? Is session[:expires] the right thing to set?

First make sure you don't set an expire_after value with the use Rack::Session::Cookie command, then put use Rack::Session::Cookie in your configure block. Next create an "expiry time" variable (let's say expiry_time for this example) or setting in config . Now for each user, when they login, retrieve their expiry_time setting and issue the following command:

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

That should do what you are asking.

If this doesn't work for you, try putting the env...merge! command in a before block.

I tried to do this via an after filter in Sinatra but it didn't work, I guess it sets the session after after filters have run, so I knocked up a quick Rack filter and it appears to work.

require 'sinatra'

class SessionExpiryModifier
  def initialize(app,options={})
    @app,@options = app,options
  end
  def call(env)
    warn env["rack.session.options"].inspect
    t = Time.now.to_i.even? ? 10 : 60
    env["rack.session.options"].merge! :expire_after => 60 * 60 * t
    @app.call env
  end
end

configure do
  use Rack::Session::Cookie,
  :expire_after => 60*60*3, 
  :secret => 'xxxx' * 10
  use SessionExpiryModifier
end

get "/" do
  session[:usr] = Time.now
  env["rack.session.options"].inspect
end

However, that makes it a lot harder to get a conditional from the Sinatra app into the Rack filter to decide on which branch to take, but that depends on what your condition is. Perhaps inject something into the headers that the filter can read to make the decision.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM