handles_authorization.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Copyright (C) 2012-2025 Zammad Foundation, https://zammad-foundation.org/
  2. module Gql::Concerns::HandlesAuthorization
  3. extend ActiveSupport::Concern
  4. included do
  5. #
  6. # Customizable methods
  7. #
  8. # Override this method to implement additional handlers.
  9. def self.before_authorize(...)
  10. true
  11. end
  12. # Override this method if an object requires custom authorization, e.g. based on Pundit.
  13. def self.authorize(...)
  14. true # Authorization is granted by default.
  15. end
  16. # Helper method to check pundit authorization of the current user for a given object.
  17. def pundit_authorize!(record, query = :show?)
  18. Pundit.authorize(context.current_user, record, query)
  19. end
  20. # Helper method to check pundit authorization of the current user for a given object.
  21. def pundit_authorized?(record, query = :show?)
  22. # Invoke policy directly to get back the actual result,
  23. # not the original object as returned by 'authorize'.
  24. Pundit.policy(context.current_user, record).public_send(query)
  25. end
  26. #
  27. # Internal methods
  28. #
  29. # This method is used by GraphQL to perform authorization on the various objects.
  30. def self.authorized?(*)
  31. # ctx = args[-1] # This may be called with 2 or 3 params, context is last.
  32. before_authorize(*)
  33. # Authorize
  34. authorize(*)
  35. rescue Pundit::NotAuthorizedError # Map to 'Forbidden'
  36. raise Exceptions::Forbidden, "Access forbidden by #{name}"
  37. end
  38. end
  39. end