如何在使用allow_unconfirmed_access时扩展Devise SessionsController #create?

时间:2016-04-08 18:30:56

标签: ruby-on-rails devise

在我的Rails项目中,我正在使用Devise,我在设计初始化程序中打开了allow_unconfirmed_access,如下所示:

config.allow_unconfirmed_access_for = 1.day

这很有效。如果用户未通过确认电子邮件确认其帐户,他们仍可以24小时登录。在此之后,如果他们尝试登录,Devise会处理它并发出一条flash消息并返回401,不允许登录。

我希望能够加入这个并添加一个步骤来自动重新发送确认电子邮件,但我无法弄清楚我的生活在哪里。

2 个答案:

答案 0 :(得分:0)

您可以扩展Devise :: SessionsController以添加此行为:

class Users::SessionsController < Devise::SessionsController
  before_action :resend_confirmation_email_if_unsent, on: :create

  def resend_confirmation_email
    @user = resource  # resource is a devise controller helper method

    unless @user.active_for_authentication?
      @user.resend_confirmation_instructions  # Resets token

      # Or, if you don't want to reset the tokn
      # @user.send_confirmation_instructions
    end
    # ....
  end

答案 1 :(得分:0)

我知道这是一个老问题,但我想我也可以回答它,因为我处理同样的情况。

Anthony E的答案几乎是正确的,但它错过了在创建操作开始之前未定义resource的事实,因此此时资源为nil。我的解决方案是:

class Users::SessionsController < Devise::SessionsController
  before_action :resend_confirmation_email_if_needed, on: :create

  def resend_confirmation_email_if_needed
    @user = resource_class.find_by_email(resource_params[:email])
    unless @user.nil? || @user.active_for_authentication?
      @user.resend_confirmation_instructions
    end
  end
end

我不确定以这种方式检索用户是否是个好主意。如果super do |resource|为此工作会更容易,但只有在成功登录时才会运行,但事实并非如此。

希望这有帮助!

相关问题