'Send email to user once their account is locked using Devise

Using the devise gem for Rails, is there a way to send an email to a user whenever their account has been locked? I haven't seen any examples of callbacks triggered by Devise just yet, but it's possible that I'm overthinking it.

The only thing that I can imagine is finding user accounts that have a recent updated_at attribute and determining storing whether or not a lockout email was sent, but this seems to be inefficient.



Solution 1:[1]

You can sand email once the failed_attempts are > of Devise.maximum_attempts in your login method, then override Devise's active_for_authentication method, so when an account is locked simply check if it is active for authentication so that email is not sent every time your user try to login, like this:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joe