18

启用可确认模块后,Devise 将不允许未经确认的用户在预定义的时间段过后登录。取而代之的是,用户会被重定向回登录页面,并显示一条闪现消息“您必须在继续之前确认您的帐户”。

这是一个不受欢迎的交互模型,因为快速通知没有提供足够的空间来正确地向用户解释访问被拒绝的原因、“确认您的帐户”是什么意思、提供重新发送确认的链接以及如何检查的说明你的垃圾邮件文件夹等等。

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

4

3 回答 3

27

抱歉,起初我以为您的意思是在注册后而不是登录后。因此,下面的内容适用于如何在注册后指导用户,而您需要为登录做的是创建一个自定义的 Devise::FailureApp

请参阅 wiki 页面: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

对于注册后的自定义重定向:

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

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

config/routes.rb

  devise_for :users, :controllers => { :registrations => "users/registrations" }

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

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

在这种情况下,对于我的应用程序,我的设计模型是用户,因此如果您的模型命名不同,您可能需要更改该命名空间。我希望我的用户被重定向到signed_up_path,但您可以将其更改为您想要的路径。

于 2012-02-10T07:48:01.537 回答
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

这对我有用,而且似乎微创。在我的应用程序中,新会话总是必须通过sessions#create,用户总是使用他们的电子邮件地址登录,所以这可能比你的情况更简单。

您当然可以在该方法 redirect_to中使用您想要的任何位置。对我来说是合乎逻辑的选择,因为它为用户提供了获得确认的资源。 check_user_confirmationnew_confirmation_path

于 2013-10-17T17:58:00.220 回答
0

这是我的解决方案,您需要在会话下方的设计语言环境中添加 :unconfirmed 消息。

在 app/controllers/sessions_controller.rb

  def check_user_confirmation
    user = User.where(email: params[:user][:email]).take

    unless user && user.confirmed?
      set_flash_message! :alert, :unconfirmed
      expire_data_after_sign_in!
      respond_with user, location: after_inactive_sign_up_path_for(user)
    end
  end

  protected

  def after_inactive_sign_up_path_for(resource)
    new_user_session_path
  end
于 2017-08-11T03:30:17.307 回答