简体   繁体   中英

How To: Redirect to a specific page when the user can not be authenticated (devise rails gem)

I just figured this out, devise's instruction are not the best. I've answered my own question below

goes inside lib

  class CustomFailure < Devise::FailureApp
    def redirect_url
       new_user_session_url(:subdomain => 'secure')
    end

    # You need to override respond to eliminate recall
    def respond
      if http_auth?
        http_auth
      else
        redirect
      end
    end
  end

goes inside initializers

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

goes inside application.rb

config.autoload_paths << Rails.root.join('lib')

1st off the code will NOT redirect your routes if the user is not logged in. That is a separate issue that can be fixed inside a custom controller inherited to registrations_controller. What this WILL do is redirect when a login has failed by the user. IE you type in the wrong password > redirects to new page.

for the first branch of code create an app called custom_failure.rb inside the lib folder (top level) and paste that code within.

for the second branch of code go into

/Users/admin/acltc_projects/roomkick/config/initializers/devise.rb search for

warden do with cmd f or ctrl f and remove the # on the warden do and "end" line. paste the manager.failure_app = CustomFailure right below warden do. under config/locals in application.rb add config.autoload_paths << Rails.root.join('lib') inside your module. Finally go back to the app inside lib and modify the line new_user_session_url(:subdomain => 'secure') for the session_url you can modify this directly to whatever you want for a route. Restart your server and test the app. Upvote if this helped!

check devise documentation https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated

If a user is not authenticatable you can redirect to a specific page.

For this example we want to use the entire URL with a particular sub-domain. Devise uses the path not the entire URL by default. The workaround is to use a custom failure app inherited from Devise failure app.

class CustomFailure < Devise::FailureApp
    def redirect_url
       new_user_session_url(:subdomain => 'secure')
    end

    # You need to override respond to eliminate recall
    def respond
      if http_auth?
        http_auth
      else
        redirect
      end
    end
end

And add the following in config/initializers/devise.rb:

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

Hope it'll help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM