summaryrefslogtreecommitdiff
path: root/lib/gitlab/graphql/authorize/authorize_resource.rb
blob: 38a8067d1e5c94a5849a80163ba6ddebadcb9533 (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
# frozen_string_literal: true

module Gitlab
  module Graphql
    module Authorize
      module AuthorizeResource
        extend ActiveSupport::Concern

        included do
          extend Gitlab::Graphql::Authorize
        end

        def find_object(*args)
          raise NotImplementedError, "Implement #find_object in #{self.class.name}"
        end

        def authorized_find(*args)
          object = find_object(*args)

          object if authorized?(object)
        end

        def authorized_find!(*args)
          object = find_object(*args)
          authorize!(object)

          object
        end

        def authorize!(object)
          unless authorized?(object)
            raise Gitlab::Graphql::Errors::ResourceNotAvailable,
                  _("The resource that you are attempting to access does not exist or you don't have permission to perform this action")
          end
        end

        def authorized?(object)
          self.class.required_permissions.all? do |ability|
            # The actions could be performed across multiple objects. In which
            # case the current user is common, and we could benefit from the
            # caching in `DeclarativePolicy`.
            Ability.allowed?(current_user, ability, object, scope: :user)
          end
        end
      end
    end
  end
end