Welcome to mirror list, hosted at ThFree Co, Russian Federation.

authorize_types.rb « graphql « cop « rubocop - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 180a1a27a858c57c87a8df28477047a6341e288e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 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
        ALLOWED_TYPES = %w[BaseEnum BaseScalar BasePermissionType MutationType SubscriptionType
                           QueryType GraphQL::Schema BaseUnion BaseInputObject].freeze

        def_node_search :authorize?, <<~PATTERN
          (send nil? :authorize ...)
        PATTERN

        def on_class(node)
          return if allowed?(class_constant(node))
          return if allowed?(superclass_constant(node))

          add_offense(node, location: :expression) unless authorize?(node)
        end

        private

        def allowed?(class_node)
          class_const = class_node&.const_name

          return false unless class_const
          return true if class_const.end_with?('Enum')
          return true if class_const.end_with?('InputType')

          ALLOWED_TYPES.any? { |allowed| class_const.include?(allowed) }
        end

        def class_constant(node)
          node.descendants.first
        end

        def superclass_constant(class_node)
          # First one is the class name itself, second is its superclass
          _class_constant, *others = class_node.descendants

          others.find { |node| node.const_type? && node&.const_name != 'Types' }
        end
      end
    end
  end
end