Forgotten Password Recovery Email With Devise And Rails

Dmitry Sychev
2 min readFeb 8, 2021

Sometimes we forget our passwords. It happens, we’re all humans or at least androids smart enough to beat capchas. In any case, I’ve covered a fantastic authorization gem Devise in my previous weeks blog, which you can find here. Assuming that all of the initial steps are done, in this weeks blog I’m going to cover how to wire up the ‘Forgot your password?’ function to send out an email to our apps user in order to reset their password.

If you’ve ran the command below.

rails g devise:install

You may have noticed that one of the prompts after the installation is to add an action_mailer config in your config/environments/development.rb file.

Lets open up that file and add a few more lines besides what’s suggested above.

config/environments/development.rb
config.action_mailer.delivery_method = :sendmail
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_options = {from: 'example@email.com'}
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'example.com',
user_name: Rails.application.credentials.gmail[:email],
password: Rails.application.credentials.gmail[:password],
authentication: 'plain',
enable_starttls_auto: true }
config.action_mailer.default_url_options = {:host =>'localhost:3000'}

The file should look like the above example once you’re done. Replace the example portions with your own information. You may also notice that for the user_name and password fields I’m using Rails.application.credentials. This is the way Rails keeps encrypted secrets in your app, as you don’t want to expose sensitive information like passwords in a plain state. Here’s how you go about setting up those credentials. The terminal command below is for VS Code as an editor for the credentials file, if you’re using something else replace ‘code’ with your editor.

EDITOR='code --wait' bin/rails credentials:edit

Edit the file accordingly.

At this point, if you fire up your app and click the ‘Forgot your password?’ link from any of the sign in route or go directly to localhost:3000/users/password/new. You should see a prompt that looks similar to the one below.

Upon entering a users email. They’ll receive an email with password reset instructions. Behind the scenes, Devise will generate a unique password reset token and assign in to the user that performed the request. Once our user clicks the link in their email, that token is pushed up as params back to Devise which will handle the password reset functionality.

--

--