使用 Rails 的
devise
gem,有没有办法在用户的帐户被锁定时向用户发送电子邮件?我还没有看到任何由 Devise 触发回调的例子,但可能是我想太多了。
我唯一能想到的是找到具有最近
updated_at
属性的用户帐户并确定存储是否发送了锁定电子邮件,但这似乎效率低下。
一旦登录方法中的 failed_attempts 大于 Devise.maximum_attempts,您就可以删除电子邮件,然后覆盖
Devise
的 active_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
我知道这是一个老问题,但我今天遇到了这个问题,我想分享一些解决方案。
Devise 有一个内置的工作流程。您可以打开 Devise Initializer 并设置
config.unlock_strategy = :email
。您也可以将其设置为:both
。这将触发您正在寻找的电子邮件。
如果出于某种原因,您只是想告诉用户他们的帐户已被锁定而不生成解锁令牌,您可以将以下内容添加到您的用户模型中:
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