Skip to content

Instantly share code, notes, and snippets.

@jendiamond
Last active June 26, 2017 04:06
Show Gist options
  • Save jendiamond/418e7b09e0591626bd9af9625bef9590 to your computer and use it in GitHub Desktop.
Save jendiamond/418e7b09e0591626bd9af9625bef9590 to your computer and use it in GitHub Desktop.

Re-generating Forgot Password Emails With Devise

https://www.codeschool.com/blog/2012/10/02/re-generating-forgot-password-emails-with-devise/

Solution:

  1. Build a custom admin feature using the devise recoverable module.
  2. Documentation for this can be found at:
    http://rubydoc.info/github/plataformatec/devise/master/Devise/Models/Recoverable/ClassMethods
    Ruby (Object) send_reset_password_instructions(attributes = {})
  3. The method attempts to find a user by its email.
    If a record is found, it sends new password instructions.
    If no user is found, it returns a new user with an “email not found” error.
    Attributes must contain the user email.
  4. Recoverable is available to you if it’s included in your User model:
class User < ActiveRecord::Base 
  devise :database_authenticatable, :timeoutable, :registerable, :recoverable, :rememberable, :trackable ...
end

How to:

  1. Create a method in your controller that will call send_reset_password_instructions. In users_controller.rb, add:
def generate_new_password_email 
  user = User.find(params[:user_id]) 
  user.send_reset_password_instructions 
  flash[:notice] = "Reset password instructions have been sent to #{user.email}." 
  redirect_to admin_user_path(user) 
end
  1. Create a route in config/routes.rb:
namespace :admin do 
  resources :users, only: :show do 
    post :generate_new_password_email 
  end 
end
  1. Create a simple form on your user’s show page in the admin. app/assets/users/show.html.erb
<%=form_tag(admin_user_generate_new_password_email_path(@user)) do %> 
  <%=submit_tag 'Send Reset Password Email', class: 'button', :confirm => 'Are you sure you want to email reset password instructions?' %> 
<% end %>

That’s it! If you want to test this in your development environment,
you can configure your SMTP settings to send an email locally.
At the bottom of config/environments/development.rb, add:

config.action_mailer.default_url_options = { :host => 'localhost:3000' } 
config.action_mailer.delivery_method = :smtp config.action_mailer.perform_deliveries = true 
config.action_mailer.raise_delivery_errors = true 
config.action_mailer.default :charset => "utf-8" 
ActionMailer::Base.smtp_settings = { :address => "smtp.gmail.com", :port => 587, :authentication => :plain, :domain => 'gmail.com', :user_name => '[email protected]', :password => 'secret' }

Restart your local server.

From your user page in the admin panel, you can now hit the
“Send Reset Password Email” button, and a new reset password email will be sent to the user.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment