class AddResetTokenToUsers < ActiveRecord::Migration[7.0]
def change
add_column :users, :reset_token, :string
add_index :users, :reset_token, unique: true
end
end
class PasswordsController < ApplicationController
def send_reset_link
user = User.find_by(email: params[:email])
if user
user.update(reset_token: SecureRandom.hex(20))
UserMailer.password_reset(user).deliver_later
end
redirect_to root_path, notice: "If your email exists in our system, a reset link has been sent."
end
def reset
user = User.find_by(reset_token: params[:token])
if user
user.update(password: params[:password], reset_token: nil)
redirect_to login_path, notice: "Password reset successfully!"
else
redirect_to root_path, alert: "Invalid or expired token."
end
end
end
This snippet lets you generate secure, one-time-use tokens for password resets without Devise. It stores the token in the database, checks its validity, and clears it after use. The send_reset_link
action sends the reset link, and the reset action verifies and updates the password.
Martin Sojka, Maker of CodeSnips