2018-11-09 13:39:43 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-07-10 10:19:45 -04:00
|
|
|
module Gitlab
|
|
|
|
module Graphql
|
|
|
|
module Authorize
|
|
|
|
module AuthorizeResource
|
|
|
|
extend ActiveSupport::Concern
|
2021-03-18 02:11:52 -04:00
|
|
|
ConfigurationError = Class.new(StandardError)
|
2018-07-10 10:19:45 -04:00
|
|
|
|
2021-03-18 02:11:52 -04:00
|
|
|
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-12-13 04:08:01 -05:00
|
|
|
|
2019-02-17 20:19:49 -05:00
|
|
|
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
|
2021-03-18 02:11:52 -04:00
|
|
|
# on its superclass.
|
|
|
|
@required_permissions ||= if respond_to?(:superclass) && superclass.respond_to?(:required_permissions)
|
2019-02-17 20:19:49 -05:00
|
|
|
superclass.required_permissions.dup
|
|
|
|
else
|
|
|
|
[]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def authorize(*permissions)
|
|
|
|
required_permissions.concat(permissions)
|
|
|
|
end
|
2021-03-18 02:11:52 -04:00
|
|
|
|
|
|
|
def authorizes_object?
|
|
|
|
defined?(@authorizes_object) ? @authorizes_object : false
|
|
|
|
end
|
|
|
|
|
|
|
|
def authorizes_object!
|
|
|
|
@authorizes_object = true
|
|
|
|
end
|
|
|
|
|
|
|
|
def raise_resource_not_available_error!(msg = RESOURCE_ACCESS_ERROR)
|
|
|
|
raise ::Gitlab::Graphql::Errors::ResourceNotAvailable, msg
|
|
|
|
end
|
2018-07-10 10:19:45 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def find_object(*args)
|
|
|
|
raise NotImplementedError, "Implement #find_object in #{self.class.name}"
|
|
|
|
end
|
|
|
|
|
2020-10-11 23:08:20 -04:00
|
|
|
def authorized_find!(*args, **kwargs)
|
|
|
|
object = Graphql::Lazy.force(find_object(*args, **kwargs))
|
2019-09-04 13:42:48 -04:00
|
|
|
|
2018-07-10 10:19:45 -04:00
|
|
|
authorize!(object)
|
|
|
|
|
|
|
|
object
|
|
|
|
end
|
|
|
|
|
|
|
|
def authorize!(object)
|
2021-03-18 02:11:52 -04:00
|
|
|
raise_resource_not_available_error! unless authorized_resource?(object)
|
2018-07-10 10:19:45 -04:00
|
|
|
end
|
|
|
|
|
2019-09-04 13:42:48 -04:00
|
|
|
def authorized_resource?(object)
|
2021-03-18 02:11:52 -04:00
|
|
|
raise ConfigurationError, "#{self.class.name} has no authorizations" if self.class.authorization.none?
|
2019-06-21 01:09:02 -04:00
|
|
|
|
2021-03-18 02:11:52 -04:00
|
|
|
self.class.authorization.ok?(object, current_user)
|
2018-07-10 10:19:45 -04:00
|
|
|
end
|
2019-12-13 04:08:01 -05:00
|
|
|
|
2021-03-18 02:11:52 -04:00
|
|
|
def raise_resource_not_available_error!(*args)
|
|
|
|
self.class.raise_resource_not_available_error!(*args)
|
2019-12-13 04:08:01 -05:00
|
|
|
end
|
2018-07-10 10:19:45 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|