使用会话ID加载会话

时间:2014-05-09 17:50:45

标签: session sinatra rack

我有一个Sinatra应用程序,其中一个规则期望URL包含会话ID(从先前调用的URL返回)。如何使用会话ID引用的会话重载会话?

use Rack::Session::Pool

get "example/:session_id" do
  sessionId = params[:session_id]

  # how to reload the session now, using the sessionId?

end

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

路径中的会话ID

如果你必须使用路径中的会话ID,你可以使用这种hacky方式

# app.rb
require 'sinatra'

configure do
  use Rack::Session::Pool, :key => 'session_id'
end

get "/example/:session_id" do
  session.id = params[:session_id]
  session[:force_load] = 'force' # force session.load!()
  session.delete(:force_load)    # remove dummy value

  session[:count] = session[:count].to_i + 1
  session.inspect
end

请求参数中的会话ID

如果您愿意将false移至请求参数(查询参数或正文参数),则支持的方式是将:cookie_only选项设置为session_id

# app.rb
require 'sinatra'

configure do
  use Rack::Session::Pool, {
    :key => 'session_id', 
    :cookie_only => false, # adds request params as source for session id
  }
end

# works with /example?session_id=
get '/example' do
  session[:count] = session[:count].to_i + 1
  session.inspect
end

演示

$ ruby app.rb &> /dev/null  &

$ curl -i localhost:4567/example?session_id=

  HTTP/1.1 200 OK 
  Set-Cookie: session_id=2a06759c64c130bc45036076; path=/; HttpOnly

  {"count"=>1}

$ curl -i localhost:4567/example?session_id=2a06759c64c130bc45036076

  HTTP/1.1 200 OK 
  Set-Cookie: session_id=2a06759c64c130bc45036076; path=/; HttpOnly

  {"count"=>2}

$ kill %1