Last Updated: August 21, 2017
·
6.381K
· dpsk

Devise redirect AJAX request when session timed out(timeoutable module)

By default when devise session is already timed out, if user send an AJAX request devise responding with the 401 unathorized error, instead of redirect.
If you want redirect to the any page instead, you can use this little hack.

Devise config:

config.http_authenticatable = false
config.http_authenticatable_on_xhr = false
config.navigational_formats = ["*/*", :html, :js]

config.warden do |manager|
  manager.failure_app = CustomFailureApp
end

Put custom_failure_app.rb into your lib folder:

class CustomFailureApp < Devise::FailureApp
  def redirect_url
    if request.xhr?
      send(:"new_#{scope}_session_path", :format => :js)
    else
      super
    end
  end
end

And after that add sessions/new.js.haml into devise views folder. Put into your view redirect or other logic you want to execute. Simple root page redirect for example:

:javascript
  window.location = "/"

1 Response
Add your response

It was throw error like: ActionController::UnknownFormat (ActionController::UnknownFormat)

over 1 year ago ·