Accessing the “session key” cookie name from anywhere in Rails

落花浮王杯 提交于 2020-01-11 18:52:46

问题


We are building a plugin for Rails to be used within iframe Facebook applications, and at one point we need to check if Rail's session id cookie as been set or not.

By default, this cookie is named _myprojectname_session, what we need to find out is the actual name of the cookie itself. So if it's not set, we can do some redirects to make sure the cookies are set.

How do we access the damn name of the cookie from anywhere? Or at least from within a controller?


回答1:


Rails.application.config.session_options[:key]



回答2:


I found the solution. In Rails 2.3.2 at least the session key in set in config/initializers/session_store.rb like this:

ActionController::Base.session = {
  :key         => '_myapp_session',
  :secret      => '[...]'
}

And you can read the value like this:

ActionController::Base.session_options[:key]

From Base.session to Base.session_options automagically, doesn't make much sense, and it caused me a big headache... lol




回答3:


To access the name of the session cookie from within the view or the controller, you can say:

request.session_options[:session_key]

and then to access the raw value of that cookie, being an empty array if it's not set, you use:

request.cookies[ request.session_options[:session_key] ]

The cookie name ( aka session_key ) is set in your config/environment.rb file.

  config.action_controller.session = {     
    :session_key => '_project_session',
    :secret      => 'long-secret-key'
  }



回答4:


In my experience, if there is an underscore in the key, IE SOMETIMES does not set the cookies. In other words, use 'projectsession' instead of '_project_session'.




回答5:


I think that the session key is stored in a variable called ENV_SESSION_KEY




回答6:


Note also this bug which affects tests around session_options in some versions of Rails 2.x: https://rails.lighthouseapp.com/projects/8994/tickets/2303-testrequest-doesnt-initialize-session_options




回答7:


In Rails 3/4 I'm using this:

request.env["rack.request.cookie_hash"]

This is a hash that contains all the cookies for current user including the one for session. The hash has as a key the name of the cookie, and as a value the value of the cookie




回答8:


I couldn't work out how to do this in rails 3 :-(

Eventually I ended up putting this in config/initializers/session_store.rb

SESSION_KEY = '_myapp_session'
MyApp::Application.config.session_store :cookie_store, :key => SESSION_KEY

and then accessing this where needed, eg in a view...

<%= ::ENV_SESSION_KEY %>


来源:https://stackoverflow.com/questions/1001597/accessing-the-session-key-cookie-name-from-anywhere-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!