Class: RuboCop::Cop::DevDoc::Auth::LoadResourceCurrentUserGuard

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/dev_doc/auth/load_resource_current_user_guard.rb

Overview

Require an early-return nil-guard before using ‘current_user` inside the load-resource lifecycle method, and forbid safe-navigation (`&.`).

## Rationale ‘glib_load_resource` (or a similarly named hook) runs before the Pundit policy. At that point `current_user` may still be nil — an anonymous visitor hasn’t been denied yet. Code that calls ‘current_user.foo` without guarding first crashes for anonymous visitors; code that uses `current_user&.foo` hides the problem with soft nil-handling instead of making it explicit.

The correct pattern is an early-return guard at the top of any branch that needs ‘current_user`:

✔️
def glib_load_resource
  return unless current_user

  @post = current_user.posts.find(params[:id])
end

Guarded branches within a case/if are also fine:

✔️
def glib_load_resource
  case action_name.to_sym
  when :new, :create
    return unless current_user
    @post = current_user.posts.new
  when :index
    # Nothing to do
  end
end

❌ Safe navigation — hides the pre-auth nil risk
def glib_load_resource
  @post = current_user&.posts&.find(params[:id])
end

❌ Unguarded — crashes for anonymous visitors
def glib_load_resource
  @post = current_user.posts.find(params[:id])
end

## Configuration ‘LoadResourceMethodNames` (default: `[glib_load_resource]`) — list of method names where the guard rule applies. Projects standardising on a different lifecycle method can add it here.

NOTE: The cop performs structural analysis of the method body and does not track aliasing. If you assign ‘current_user` to a local variable and then call methods on that variable, the cop will not flag it —reviewers must catch that pattern manually.

Examples:

# bad — safe navigation inside load hook
def glib_load_resource
  @post = current_user&.posts&.find(params[:id])
end

# bad — unguarded call inside load hook
def glib_load_resource
  @post = current_user.posts.find(params[:id])
end

# good — guarded with early return
def glib_load_resource
  return unless current_user

  @post = current_user.posts.find(params[:id])
end

Constant Summary collapse

MSG_SAFE_NAV =
'Avoid `current_user&.` inside `%<method>s` — use ' \
'`return unless current_user` then `current_user.` instead.'.freeze
MSG_MISSING_GUARD =
'`current_user` is used without a prior ' \
'`return unless current_user` guard in `%<method>s`. ' \
'This method runs before the policy, so `current_user` may be nil.'.freeze
NIL_CHECK_METHODS =

Methods that test current_user for nil — not calls that risk NoMethodError.

%i[nil? blank? present? empty?].freeze

Instance Method Summary collapse

Instance Method Details

#on_def(node) ⇒ Object Also known as: on_defs



86
87
88
# File 'lib/rubocop/cop/dev_doc/auth/load_resource_current_user_guard.rb', line 86

def on_def(node)
  check_load_resource_method(node)
end