base_mutation.rb 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. module Gql::Mutations
  3. # class BaseMutation < GraphQL::Schema::RelayClassicMutation
  4. class BaseMutation < GraphQL::Schema::Mutation
  5. include Gql::Concern::HandlesAuthorization
  6. argument_class Gql::Types::BaseArgument
  7. field_class Gql::Types::BaseField
  8. object_class Gql::Types::BaseObject
  9. # input_object_class Gql::Types::BaseInputObject
  10. field :errors, [Gql::Types::UserErrorType], description: 'Errors encountered during execution of the mutation.'
  11. # Override this for mutations that don't need CSRF verification.
  12. def self.requires_csrf_verification?
  13. true
  14. end
  15. def self.before_authorize(*args)
  16. ctx = args[-1] # This may be called with 2 or 3 params, context is last.
  17. # CSRF - since this is expensive it is only called by mutations.
  18. verify_csrf_token(ctx) if requires_csrf_verification?
  19. end
  20. # Require authentication by default for mutations.
  21. def self.authorize(_obj, ctx)
  22. ctx.current_user
  23. end
  24. def self.verify_csrf_token(ctx)
  25. return true if ctx[:is_graphql_introspection_generator]
  26. # Support :graphql type tests that don't use HTTP.
  27. return true if Rails.env.test? && !ctx[:controller]
  28. # Support developer workflows that need to turn off CSRF.
  29. return true if Rails.env.development? && ctx[:controller].request.headers['SkipAuthenticityTokenCheck'] == 'true'
  30. ctx[:controller].send(:verify_csrf_token) # verify_csrf_token is private :(
  31. end
  32. def self.register_in_schema(schema)
  33. field_name = name.sub('Gql::Mutations::', '').gsub('::', '').camelize(:lower).to_sym
  34. schema.field field_name, mutation: self
  35. end
  36. def error_response(*errors)
  37. { errors: errors }
  38. end
  39. end
  40. end