-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Notify users via email when their passwords change
Moncef Belyamani edited this page Mar 28, 2015
·
7 revisions
For security purposes, sometimes you need to notify users when their passwords change. 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!