Refine controllers

This commit is contained in:
Manuel Bustillo 2024-11-19 00:32:24 +01:00
parent 134bf27955
commit 3e38630eb4
3 changed files with 18 additions and 25 deletions

View File

@ -2,34 +2,29 @@
class PasswordsController < ApplicationController
allow_unauthenticated_access
before_action :set_user_by_token, only: %i[ edit update ]
def new
end
before_action :set_user_by_token, only: :update
def create
if user = User.find_by(email_address: params[:email_address])
PasswordsMailer.reset(user).deliver_later
end
redirect_to new_session_path, notice: "Password reset instructions sent (if user with that email address exists)."
end
def edit
render json: {}, status: :ok
end
def update
if @user.update(params.permit(:password, :password_confirmation))
redirect_to new_session_path, notice: "Password has been reset."
render json: {}, status: :ok
else
redirect_to edit_password_path(params[:token]), alert: "Passwords did not match."
render json: { errors: @user.errors.full_messages }, status: :unprocessable_entity
end
end
private
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
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

View File

@ -1,23 +1,21 @@
# Copyright (C) 2024 Manuel Bustillo
class SessionsController < ApplicationController
allow_unauthenticated_access only: %i[ new create ]
rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_session_url, alert: "Try again later." }
def new
end
allow_unauthenticated_access only: :create
rate_limit to: 10, within: 3.minutes, only: :create,
with: -> { render json: { errors: ['Rate limit exceeded'] }, status: :too_many_requests }
def create
if user = User.authenticate_by(params.permit(:email_address, :password))
start_new_session_for user
redirect_to after_authentication_url
render json: {}, status: :created
else
redirect_to new_session_path, alert: "Try another email address or password."
render json: { errors: ['Invalid email address or password'] }, status: :unauthorized
end
end
def destroy
terminate_session
redirect_to new_session_path
render json: {}, status: :ok
end
end

View File

@ -1,8 +1,8 @@
# Copyright (C) 2024 Manuel Bustillo
Rails.application.routes.draw do
resource :session
resources :passwords, param: :token
resource :session, only: %i[create destroy]
resources :passwords, param: :token, only: %w[create update]
mount Rswag::Ui::Engine => '/api-docs'
mount Rswag::Api::Engine => '/api-docs'
resources :groups, only: :index