debian-mirror-gitlab/lib/gitlab/graphql/authorize/authorize_resource.rb

72 lines
2.5 KiB
Ruby
Raw Normal View History

2019-02-15 15:39:39 +05:30
# frozen_string_literal: true
2018-11-18 11:00:15 +05:30
module Gitlab
module Graphql
module Authorize
module AuthorizeResource
extend ActiveSupport::Concern
2020-01-01 13:55:28 +05:30
RESOURCE_ACCESS_ERROR = "The resource that you are attempting to access does not exist or you don't have permission to perform this action"
2019-07-07 11:18:12 +05:30
class_methods do
def required_permissions
# If the `#authorize` call is used on multiple classes, we add the
# permissions specified on a subclass, to the ones that were specified
# on it's superclass.
@required_permissions ||= if self.respond_to?(:superclass) && superclass.respond_to?(:required_permissions)
superclass.required_permissions.dup
else
[]
end
end
def authorize(*permissions)
required_permissions.concat(permissions)
end
2018-11-18 11:00:15 +05:30
end
def find_object(*args)
raise NotImplementedError, "Implement #find_object in #{self.class.name}"
end
def authorized_find!(*args)
2020-07-28 23:09:34 +05:30
object = Graphql::Lazy.force(find_object(*args))
2019-12-04 20:38:33 +05:30
2018-11-18 11:00:15 +05:30
authorize!(object)
object
end
def authorize!(object)
2019-12-04 20:38:33 +05:30
unless authorized_resource?(object)
2020-03-09 13:42:32 +05:30
raise_resource_not_available_error!
2018-11-18 11:00:15 +05:30
end
end
2019-12-04 20:38:33 +05:30
# this was named `#authorized?`, however it conflicts with the native
# graphql gem version
# TODO consider adopting the gem's built in authorization system
# https://gitlab.com/gitlab-org/gitlab/issues/13984
def authorized_resource?(object)
2019-09-30 21:07:59 +05:30
# Sanity check. We don't want to accidentally allow a developer to authorize
# without first adding permissions to authorize against
if self.class.required_permissions.empty?
raise Gitlab::Graphql::Errors::ArgumentError, "#{self.class.name} has no authorizations"
end
2018-11-18 11:00:15 +05:30
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
2020-01-01 13:55:28 +05:30
2020-03-09 13:42:32 +05:30
def raise_resource_not_available_error!
2020-01-01 13:55:28 +05:30
raise Gitlab::Graphql::Errors::ResourceNotAvailable, RESOURCE_ACCESS_ERROR
end
2018-11-18 11:00:15 +05:30
end
end
end
end