使用可确认设计 - 当用户尝试使用未经证实的电子邮件登录时,将用户重定向到自定义页面

Tob*_*hen 17 ruby ruby-on-rails devise devise-confirmable

启用可确认模块后,Devise将不允许未经确认的用户在预定义的时间段过后登录.而是将用户重定向回登录页面,并显示"您必须先确认帐户才能继续".

这是一种不受欢迎的交互模型,因为闪存通知没有提供足够的空间来向用户正确解释访问被拒绝的原因,"确认您的帐户"的含义,提供重新发送确认的链接以及如何检查的说明您的垃圾邮件文件夹等.

有没有办法可以更改此行为以重定向到特定的URL?

JDu*_*til 27

抱歉,一开始我认为你的意思是注册后没有登录.因此,下面的内容适用于如何在注册后引导用户以及您需要为登录做什么就是创建自定义Devise :: FailureApp

请参阅维基页面:https://github.com/plataformatec/devise/wiki/How-To : -Redirect- to-a-specific-page- when- the-user-can-not-be- authenticated

然后在https://github.com/plataformatec/devise/blob/master/lib/devise/failure_app.rb中的自定义FailureApp覆盖redirect_url方法中:

  def redirect_url
    if warden_message == :unconfirmed
      custom_redirect_path
    else
      super
    end
  end
Run Code Online (Sandbox Code Playgroud)

注册后的自定义重定向:

after_inactive_sign_up_path_for在RegistrationsController中有一个控制器方法,您可以覆盖它来完成此操作.

首先在路由中,您需要指定使用自定义控制器:

config/routes.rb:

  devise_for :users, :controllers => { :registrations => "users/registrations" }
Run Code Online (Sandbox Code Playgroud)

其次,您创建从普通控制器继承的自定义控制器,以覆盖该方法:

app/controllers/users/registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController

  protected

  def after_inactive_sign_up_path_for(resource)
    signed_up_path
  end

end
Run Code Online (Sandbox Code Playgroud)

在这种情况下,对于我的App,我的Devise模型是User,因此如果模型的命名方式不同,您可能希望更改该命名空间.我希望将我的用户重定向到signed_up_path,但您可以将其更改为所需的路径.


Han*_*ack 10

我刚刚做了这个,但采取了不同的方法.

在app/controllers/sessions_controller.rb中:

class SessionsController < Devise::SessionsController

  before_filter :check_user_confirmation, only: :create

  #
  # other code here not relevant to the example
  #

private

  def check_user_confirmation
    user = User.find_by_email(params[:email])
    redirect_to new_confirmation_path(:user) unless user && user.confirmed?
  end
end
Run Code Online (Sandbox Code Playgroud)

这对我有用,似乎微创.在我的应用程序中,新会话始终必须通过sessions#create,用户始终使用他们的电子邮件地址登录,因此这可能比您的更简单.

您当然可以redirect_tocheck_user_confirmation方法中找到您想要的任何位置. new_confirmation_path对我来说是合乎逻辑的选择,因为它为用户提供了获得确认的资源.