Session Values getting reset after redirect rails

2019-08-03 20:02发布

问题:

I am using devise 3.5.1, rails 4.0.0 and ruby 2.0.0-p0.

If a user is not signed in and tries to open a private page which requires authentication, let's say lvh.me:3000/users/1/edit, then devise will add users/1/edit in session against the key user_return_to. The problem is that when the user gets redirected to the login page after authentication failure then user_return_to value in session gets reset.

I have this problem all over my app. If I store a value in session and redirect to another path from the same action then the session value disappears.

Note: I have upgraded my rails app from (rails 3.0.4, ruby 1.8.7) to (rails 4.0.0, ruby 2.0.0).

Sorry for any ambiguities in the question. If you have any question please comment it.

UPDATE:

In my application controller, I've added a before filter to authenticate user. Only relevant code is shown in application controller.

application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery

  before_filter :authenticate_user!, :unless => :devise_controller?

  # rest of the code

end

I'm using a custom failure class which inherits Devise::FailureApp. The code looks like this.

custom_failure.rb

class CustomFailure < Devise::FailureApp
  def redirect_url
    eval "new_user_session_path"
  end

  def redirect
    store_location!
    flash[:alert] = i18n_message
    # session[:user_return_to] returns '/foobar' here.
    redirect_to redirect_url
  end

end

I have commented a line in above code. session[:user_return_to] is available at that line but after the redirect on very next line, the session[:user_return_to] becomes nil.

I've upgraded devise from 1.5.3 to 3.5.1.

回答1:

I'm adding the solution here in case anybody else encounters the same problem.

I had a resource named asset in my application and it was conflicting with the asset pipeline. The session was getting reset whenever my URL contained 'assets' e.g. '/assets'. So if you have a resource named asset then you have to change the prefix of your asset pipeline. To do so, add the following line in your application.rb file.

config.assets.prefix = '/static_assets'

Also you have to rename the asset pipeline folder to static_assets.

Please note that this solution only applies if you have a resource named Asset in your application and the rails version is 3.1+