sample_rails_tailwind/app/controllers/password_resets_controller.rb
songtianlun 32ec61fe00 feat: add password reset functionality
- Implement password reset request and form
- Add user validation and expiration checks
- Create integration tests for password reset process

This commit introduces a complete password reset feature, allowing
users to reset their passwords securely. It includes necessary
validations to ensure the user is valid and the reset token has
not expired. Additionally, integration tests have been added to
verify the functionality and edge cases, enhancing overall
application security and user experience.
2025-01-08 11:44:42 +08:00

66 lines
1.6 KiB
Ruby

class PasswordResetsController < ApplicationController
before_action :get_user, only: [:edit, :update]
before_action :valid_user, only: [:edit, :update]
before_action :check_expiration, only: [:edit, :update]
include SessionsHelper
def new
end
def create
@user = User.find_by(email: params[:password_reset][:email].downcase)
if @user
@user.create_reset_digest
@user.send_password_reset_email
flash[:info] = "Email send with password reset instructions"
redirect_to root_url
else
flash.now[:danger] = "Email not found"
render 'new', status: :unprocessable_entity
end
end
def edit
end
def update
if params[:user][:password].empty?
@user.errors.add(:password, "can't be empty")
render 'edit', status: :unprocessable_entity
elsif @user.update(user_params)
forget(@user)
reset_session
@user.update_attribute(:reset_digest, nil)
log_in @user
flash[:success] = "Password has been reset"
redirect_to @user
else
render 'edit', status: :unprocessable_entity
end
end
private
def user_params
params.require(:user).permit(:password, :password_confirmation)
end
def get_user
@user = User.find_by(email: params[:email])
end
def valid_user
unless @user && @user.activated? &&
@user.authenticated?(:reset, params[:id])
redirect_to root_url
end
end
def check_expiration
if @user.password_reset_expired?
flash[:danger] = "Password reset has expired"
redirect_to new_password_reset_url
end
end
end