Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix N+1 SQL query by creating a user validator to call current_user a single time. #23057

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Create validator to reduce unneeded SQL queries
  • Loading branch information
petecheslock committed Jan 11, 2023
commit b677187280abb6d66c165098f9d8faac067fe6bc
31 changes: 20 additions & 11 deletions app/controllers/api/base_controller.rb
Expand Up @@ -126,20 +126,29 @@ def require_not_suspended!
render json: { error: 'Your login is currently disabled' }, status: 403 if current_user&.account&.suspended?
end

def require_user!
if !current_user
render json: { error: 'This method requires an authenticated user' }, status: 422
elsif !current_user.confirmed?
render json: { error: 'Your login is missing a confirmed e-mail address' }, status: 403
elsif !current_user.approved?
render json: { error: 'Your login is currently pending approval' }, status: 403
elsif !current_user.functional?
render json: { error: 'Your login is currently disabled' }, status: 403
else
update_user_sign_in
module UserValidator
class << self
def validate(user)
return [:unprocessable_entity, 'This method requires an authenticated user'] unless user

return [:forbidden, 'Your login is missing a confirmed e-mail address'] unless user.confirmed?

return [:forbidden, 'Your login is currently pending approval'] unless user.approved?

return [:forbidden, 'Your login is currently disabled'] unless user.functional?

[]
end
end
end

def require_user!
error_code, message = UserValidator.validate(current_user)
return render json: { error: message }, status: error_code if error_code

update_user_sign_in
end

def render_empty
render json: {}, status: 200
end
Expand Down