ruby-on-rails 使用Devise锁定用户帐户后,向用户发送电子邮件

js81xvg6  于 2023-10-21  发布在  Ruby
关注(0)|答案(2)|浏览(120)

使用Rails的devise gem,有没有一种方法可以在用户的帐户被锁定时向用户发送电子邮件?我还没有看到任何由Devise触发回调的例子,但可能是我想多了。
我能想到的唯一一件事就是找到具有最近updated_at属性的用户帐户,并确定是否发送了锁定电子邮件,但这似乎效率低下。

yebdmbv4

yebdmbv41#

一旦登录方法中的failed_attempts> Devise.maximum_attempts,您可以发送电子邮件,然后覆盖Deviseactive_for_authentication方法,因此当帐户被锁定时,只需检查它是否处于激活状态以进行身份验证,这样您的用户每次尝试登录时都不会发送电子邮件,如下所示:

if active_for_authentication?
  if user.failed_attempts >= Devise.maximum_attempts
    user.lock_access!(send_instructions: true)
  else
    user.increment_failed_attempts
  end
end

def active_for_authentication?
  super && your_condition_is_valid?
end
des4xlb0

des4xlb02#

我知道这是一个老问题,但我今天遇到了它,我想我会分享一些解决方案。

解决方案一

Devise有一个内置的工作流程。您可以打开Devise Initializer并设置config.unlock_strategy = :email。也可以设置为:both。这将触发您正在查找的电子邮件。

方案二

无论出于何种原因,如果您只是想告诉用户他们的帐户已被锁定而不产生解锁令牌,则可以将以下内容添加到User模型中:

after_commit :send_account_locked_email, if: -> { locked_at_was_previously_changed? && locked_at.present? }

def send_account_locked_email
  # Call your mailer here.
end

相关问题