设计:在用户身份验证失败时重定向到不同的路径

Devise: Redirect to different path on failed user authentication

我正在努力寻找自定义 authenticate_user! 的方法,以便在用户未登录时重定向到测试版注册页面,而不是重定向到登录页面。

有没有办法通过在 authenticate_user! 方法中添加类似下面的内容来有条件地更改指向 beta 注册页面的重定向路径?

ENV['BETA_MODE'] ? redirect_to beta_signup_path : redirect_to login_path

您需要将自定义设计控制器添加到您的应用中。您可以按照以下步骤操作;

config/routes.rb文件中;

devise_for :users, controllers: { registrations: "registrations" }

将以下控制器内容添加到app/controllers/registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
  protected

  def after_sign_up_path_for(resource)
    ENV['BETA_MODE'] ? beta_signup_path : login_path
  end
end

更多:https://github.com/plataformatec/devise/wiki/how-to:-redirect-to-a-specific-page-on-successful-sign-up-(registration)

我找到了这里提到的第一个修复程序 https://groups.google.com/forum/#!topic/plataformatec-devise/qymDM9u9n6Y

我在 config/initializers/devise.rb 中定义了自定义身份验证失败 class,如下所示:

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

之后,我在 /vendor 中创建了一个名为 custom_authentication_failure.rb 的文件。该文件的内容如下所示:

class CustomAuthenticationFailure < Devise::FailureApp
  protected

  def redirect_url
    ENV['BETA_MODE'] ? beta_signup_path : new_user_session_path
  end
end

我还需要在 config/application.rb 中添加它,因为它还不存在:

config.autoload_paths += %W(#{config.root}/vendor)