debian-mirror-gitlab/rubocop/cop/graphql/authorize_types.rb

51 lines
1.5 KiB
Ruby
Raw Normal View History

2019-09-30 21:07:59 +05:30
# frozen_string_literal: true
module RuboCop
module Cop
module Graphql
class AuthorizeTypes < RuboCop::Cop::Cop
MSG = 'Add an `authorize :ability` call to the type: '\
'https://docs.gitlab.com/ee/development/api_graphql_styleguide.html#type-authorization'
# We want to exclude our own basetypes and scalars
2021-06-08 01:23:25 +05:30
ALLOWED_TYPES = %w[BaseEnum BaseScalar BasePermissionType MutationType SubscriptionType
2021-04-17 20:07:23 +05:30
QueryType GraphQL::Schema BaseUnion BaseInputObject].freeze
2019-09-30 21:07:59 +05:30
def_node_search :authorize?, <<~PATTERN
(send nil? :authorize ...)
PATTERN
def on_class(node)
2020-07-28 23:09:34 +05:30
return if allowed?(class_constant(node))
return if allowed?(superclass_constant(node))
2019-09-30 21:07:59 +05:30
add_offense(node, location: :expression) unless authorize?(node)
end
private
2020-07-28 23:09:34 +05:30
def allowed?(class_node)
2020-01-01 13:55:28 +05:30
class_const = class_node&.const_name
return false unless class_const
return true if class_const.end_with?('Enum')
2021-04-17 20:07:23 +05:30
return true if class_const.end_with?('InputType')
2019-09-30 21:07:59 +05:30
2021-04-17 20:07:23 +05:30
ALLOWED_TYPES.any? { |allowed| class_const.include?(allowed) }
2019-09-30 21:07:59 +05:30
end
def class_constant(node)
node.descendants.first
end
def superclass_constant(class_node)
2019-12-04 20:38:33 +05:30
# First one is the class name itself, second is its superclass
2019-09-30 21:07:59 +05:30
_class_constant, *others = class_node.descendants
others.find { |node| node.const_type? && node&.const_name != 'Types' }
end
end
end
end
end