Handle expired Devise session with a redirect when using js format
09 Jun 2015

Handle expired Devise session with a redirect when using js format

While working on a side project of mine I got a problem. I am using mostly JS format for the AJAX requests. So I decided to redirect the users back to the login page if the sessions expires.

To achieve that you can do this:

Change forgery form :exception to :reset_session.

# /app/controllers/application_controller.rb
protect_from_forgery with: :reset_session

Add these three lines in devise.rb.

#  /config/initializers/devise.rb
config.warden do |manager|
    manager.failure_app = HubsFailureApp
  end

Add the following code at your lib folder.

#  /lib/hubs_failure_app.rb
class HubsFailureApp < Devise::FailureApp

  def respond
    if request.format == :js
      js_failure
    else
      super
    end
  end

  def js_failure
    session[:previous_url] = request.referrer
    self.status = 401
    self.content_type = 'application/javascript'
    self.response_body = "window.location = '#{new_user_session_url}'"
  end

end

Note that the session[:previous_url] must be set to request.referrer otherwise it`ll be set to '/unauthorized' which is no good.

Thanks to Mikhail Nikalyukin for the protip.

P.S. I`m pretty new to Rails and maybe will find a better way in the future for this kinda stuff.