Skip to content

Notify users via email when their passwords change

whiteskull edited this page Apr 12, 2017 · 7 revisions

For security purposes, sometimes you need to notify users when their passwords change.

Since Devise 3.5.3 this functionality has been built-in, but it is disabled by default. To enable it, open config/initializers/devise.rb and make this change and restart your app (and spring):

  # Send a notification email when the user's password is changed
-  # config.send_password_change_notification = false
+  config.send_password_change_notification = true

You can customize the password change email by editing the devise/mailer/password_change.html.erb template.

If you are using a version of Devise earlier than 3.5.3, then upgrade and make the change detailed above.

DEPRECATED INSTRUCTIONS

These are the instructions to enable this functionality if you are stuck on an earlier version of Devise (pre-3.5.3).

The following code has been tested with Rails 4.1.5 and Devise 3.4.1, assuming your Devise model is named User.

To do so, you need to generate a new mailer. Let's call it UserMailer:

rails g mailer user_mailer password_changed

Add some code:

# app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
  default from: "some-email@your-domain.ext"

  def password_changed(id)
    @user = User.find(id)
    mail to: @user.email, subject: "Your password has changed"
  end
end

Then add some content to the email template:

<%# app/views/user_mailer/password_changed.html.erb %>
<h2>Your password has changed</h2>
<hr>
<p>Hi <%= @user.email %>,</p>
<p>We wanted to let you know that your password was changed.</p>

Now configure your model:

# app/models/user.rb
class User < ActiveRecord::Base
  after_update :send_password_change_email, if: :needs_password_change_email?

  private

  # Change the logic here depending on how you use Devise.
  # For example, if you allow users to be created with just an email,
  # then this will always return true, so you'll need another thing to
  # check instead of `persisted?`
  #
  # The idea is that you want to differentiate between users who are signing
  # up for the first time (because `encrypted_password_changed?` will be true
  # for them), and those who are changing their password after having created
  # it for the first time.
  def needs_password_change_email?
    encrypted_password_changed? && persisted?
  end
   
  def send_password_change_email
    UserMailer.password_changed(id).deliver
  end
end

Voila!

Clone this wiki locally
You can’t perform that action at this time.