Migrating Away from Devise Part 3: Password Recovery
Published: January 02, 2025
This is the third part of a multi-part series about moving from devise to the Rails generated authentication system
- Part 1 - Setup and Sessions
- Part 2 - User Sign-in
- Part 3 - Password Recovery
- Part 4 - Email Confirmation Setup
- Part 5 - User Sign-up
- Part 6 - Trackable Module and Tests
The next feature to support is password recovery. Rails' authentication generator + has_secure_password
provides a lot of the plumbing for us.
These routes are added (reminder, we're putting these above the existing devise routes) based on the generator:
resources :passwords, only: [:new, :create, :edit, :update], param: :token
A PasswordsController
is a near copy/paste from the generator as well:
class PasswordsController < ApplicationController
rate_limit to: 10, within: 3.minutes, only: [:create, :update], with: lambda {
redirect_to new_password_path, alert: "Try again later."
}
before_action :set_user_by_token, only: [:edit, :update]
def new
end
def edit
end
def create
if (user = User.find_by(email: params.expect(:email)))
UserMailer.reset_password_instructions(user).deliver_later
end
redirect_to new_session_path, notice: "Password reset instructions sent (if user with that email address exists)."
end
def update
if @user.update(password_params)
redirect_to new_session_path, notice: "Password has been reset."
else
redirect_to edit_password_path(params[:token]), alert: "Passwords did not match."
end
end
private
def password_params
params.expect(:password, :password_confirmation)
end
def set_user_by_token
@user = User.find_by_password_reset_token!(params[:token])
rescue ActiveSupport::MessageVerifier::InvalidSignature
redirect_to new_password_path, alert: "Password reset link is invalid or has expired."
end
end
The biggest change from the default is the email uses UserMailer.reset_password_instructions
. Instead of a dedicated password mailer, I chose to use an existing UserMailer
.
def reset_password_instructions(user)
@user = user
mail subject: "Reset your password", to: user.email
end
The email view is a reused template from devise with a change to the link to point to the new controller.
<p><%= link_to 'Change my password', edit_password_url(@user.password_reset_token) %></p>
The controller views are also copy/pasted devise views that already exist with the form pointing to passwords_path
and password_path(params[:token])
for the new and edit actions, respectively.