Skip to content

Notify users via email when their passwords change

Omar Abdel-Wahab edited this page Jul 30, 2014 · 7 revisions

For security purposes, sometimes you need to notify users when their passwords change. The following code has been tested with Rails 4.0.4 and Devise 3.2.4, 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: "[email protected]"

  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.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
  # Overridden to notify users with password changes
  def update_with_password(params, *options)
    if super
      # TODO schedule this in the background
      UserMailer.password_changed(self.id).deliver
    end
  end
end
Clone this wiki locally