Skip to content

Instantly share code, notes, and snippets.

@leonardofaria
Forked from willywg/UserMailer.rb
Last active February 18, 2016 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonardofaria/d2eab320056a9f93a3f3 to your computer and use it in GitHub Desktop.
Save leonardofaria/d2eab320056a9f93a3f3 to your computer and use it in GitHub Desktop.
Mass password reset and email notification for Devise 3.5.1 with Rails 4.x
namespace :device do
desc "Mass password reset and send email instructions"
task mass_password_reset: :environment do
model = ENV['MODEL'] || 'User'
begin
model_mailer = "#{model}Mailer".constantize
model = model.constantize
model.where(id: 1).each do |record|
raw, enc = Devise.token_generator.generate(model, :reset_password_token)
record.reset_password_token = enc
record.reset_password_sent_at = Time.now.utc
record.save
# Send change notification (Ensure you have created #{model}Mailer e.g. UserMailer)
model_mailer.password_reset(record, raw).deliver_now
end
rescue Exception => e
puts "Error: #{e.message}"
end
end
end
<p>Hello <%= @resource.email %>!</p>
<p>Someone has requested a link to change your password. You can do this through the link below.</p>
<p><%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %></p>
<p>If you didn't request this, please ignore this email.</p>
<p>Your password won't change until you access the link above and create a new one.</p>
# Send password reset notification
# path: app/mailers/user_mailer.rb
class UserMailer < ActionMailer::Base
default :from => "no-reply@example.com"
def password_reset(user, token)
@resource = user
@token = token
mail(:to => user.email,
:subject => 'Password Reset Notification')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment