ruby 49 lines · 9 steps

Password resets with signed global IDs in Rails

A password reset flow that encodes the user in a signed, expiring token instead of storing reset records in the database.

Explained by highlit
1class PasswordResetsController < ApplicationController
2 RESET_PURPOSE = :password_reset
3 RESET_EXPIRY = 15.minutes
4 
5 def create
6 user = User.find_by(email: params[:email].to_s.downcase.strip)
7 
8 if user
9 sgid = user.to_sgid(expires_in: RESET_EXPIRY, for: RESET_PURPOSE)
10 reset_url = edit_password_reset_url(token: sgid.to_s)
11 UserMailer.with(user: user, reset_url: reset_url).password_reset.deliver_later
12 end
13 
14 redirect_to new_session_path, notice: "If that account exists, we've emailed a reset link."
15 end
16 
17 def edit
18 @user = authenticated_user
19 return if @user
20 
21 redirect_to new_password_reset_path, alert: "That reset link is invalid or has expired."
22 end
23 
24 def update
25 @user = authenticated_user
26 
27 unless @user
28 redirect_to new_password_reset_path, alert: "That reset link is invalid or has expired."
29 return
30 end
31 
32 if @user.update(password_params)
33 reset_session
34 redirect_to new_session_path, notice: "Your password has been reset. Please sign in."
35 else
36 render :edit, status: :unprocessable_entity
37 end
38 end
39 
40 private
41 
42 def authenticated_user
43 GlobalID::Locator.locate_signed(params[:token], for: RESET_PURPOSE)
44 end
45 
46 def password_params
47 params.require(:user).permit(:password, :password_confirmation)
48 end
49end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Signed global IDs let you carry a verified, expiring user reference in a URL without a database column.
  2. 2Returning the same generic response whether or not the account exists prevents user enumeration.
  3. 3Scoping tokens with a purpose stops a token minted for one action from being replayed for another.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Password resets with signed global IDs in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code