user938363
user938363

Reputation: 10350

session become nil in application controller

In our Rails 4.2 app, a method view_handler in module's application controller is getting nil with session variables. Here is the code structure:

class my_module < ApplicationController
  def view_handler
    #access session[:page_step] which is defined in controller.
  end
end 

Default cookie store is used for the session:

Rails.application.config.session_store :cookie_store, key: '_my_app_session'

We verified that this is not a scope issue because the problem remains the same when view_handler is moved into main app's application controller.

In debug with application controller, the session object exists but with nil value:

>session.present? #false
>session.nil? #true
>session[:page_step] #nil

Here is the session object in debug. @delegate which holds app defined session variables is empty:

enter image description here

Also in debug, the session[:page_step] re-surfaces again late in controller action. Somehow the session[:page_step] (and other session variables) becomes nil in application controller and re-surface in controller. Since by default session variables in application controller are available in RAILS, what could cause them becoming nil in application controller?

Upvotes: 1

Views: 2568

Answers (1)

wes.hysell
wes.hysell

Reputation: 1209

It's possible that you are experiencing a CSRF Issue.

If the security token doesn't match what was expected, the session will be reset

To check if it is a CSRF issue, you can temporarily disable the protect_from_forgery line in your ApplicationController

Additionally, make sure your configuration for Session Storage is complete with secret keys in config/secrets.yml for non-production environments and as an environment variable for your production.

Secret keys can be generated with as follows in a console:

$ rake secret
82d58d3dfb91238b495a311eb8539edf5064784f1d58994679db8363ec241c745bef0b446bfe44d66cbf91a2f4e497d8f6b1ef1656e3f405b0d263a9617ac75e

Each time a new secret key is used, older sessions using other keys will not validate and the result of the session will be nil.

Comments directly from generated file config/secrets.yml (Rails 4.2):

# Be sure to restart your server when you modify this file.

# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!

# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.

# Make sure the secrets in this file are kept private
# if you're sharing your code publicly.

Upvotes: 2

Related Questions