scoped_field.rb 954 B

123456789101112131415161718192021222324252627282930
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module Gql::Fields
  3. # Represents fields that can be restricted by by Pundit 'FieldScope' results.
  4. class ScopedField < BaseField
  5. def initialize(*args, **kwargs, &)
  6. # Schema verification check: require nullability for scoped fields.
  7. if !kwargs[:null].nil? && !kwargs[:null]
  8. raise "The scoped field #{kwargs[:name]} must be nullable."
  9. end
  10. super
  11. end
  12. # If a field is not authorized, just return 'nil' rather than throwing a GraphQL error.
  13. def resolve(object, args, context)
  14. field_authorized?(object) ? super : nil
  15. end
  16. private
  17. def field_authorized?(object)
  18. pundit_result = object.cached_pundit_authorize
  19. # Check if the pundit result is a 'FieldScope' object.
  20. pundit_result.respond_to?(:field_authorized?) ? pundit_result.field_authorized?(original_name) : !!pundit_result
  21. end
  22. end
  23. end