Class: RuboCop::Cop::Betterment::UnscopedFind

Inherits:
RuboCop::Cop
  • Object
show all
Defined in:
lib/rubocop/cop/betterment/unscoped_find.rb

Constant Summary collapse

MSG =
<<~MSG.freeze
  Records are being retrieved directly using user input.
  Please query for the associated record in a way that enforces authorization (e.g. "trust-root chaining").

  INSTEAD OF THIS:
  Post.find(params[:post_id])

  DO THIS:
  current_user.posts.find(params[:post_id])

  See here for more information on this error:
  https://github.com/Betterment/rubocop-betterment/blob/master/README.md#bettermentunscopedfind
MSG
METHOD_PATTERN =
/^find_by_(.+?)(!)?$/.freeze
FINDS =
%i(find find_by find_by! where).freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = nil, options = nil) ⇒ UnscopedFind

Returns a new instance of UnscopedFind.



31
32
33
34
35
# File 'lib/rubocop/cop/betterment/unscoped_find.rb', line 31

def initialize(config = nil, options = nil)
  super(config, options)
  config = @config.for_cop(self)
  @unauthenticated_models = config.fetch("unauthenticated_models", [])
end

Instance Attribute Details

#unauthenticated_modelsObject

Returns the value of attribute unauthenticated_models.



5
6
7
# File 'lib/rubocop/cop/betterment/unscoped_find.rb', line 5

def unauthenticated_models
  @unauthenticated_models
end

Instance Method Details

#on_send(node) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rubocop/cop/betterment/unscoped_find.rb', line 37

def on_send(node)
  _, _, *arg_nodes = *node
  return unless
    (
        find?(node) ||
        custom_scope_find?(node) ||
        static_method_name(node.method_name)
    ) && !@unauthenticated_models.include?(get_root_token(node))

  add_offense(node, message: MSG) if find_param_arg(arg_nodes)
end