base_mutation.rb 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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::Concerns::HandlesAuthorization
  6. include Gql::Concerns::HasNestedGraphqlName
  7. include Gql::Concerns::HandlesServices
  8. # FIXME: Remove when all mutations are using services which are taking care of this flag.
  9. include Gql::Mutations::Concerns::HandlesCoreWorkflow
  10. argument_class Gql::Types::BaseArgument
  11. field_class Gql::Fields::BaseField
  12. object_class Gql::Types::BaseObject
  13. # input_object_class Gql::Types::BaseInputObject
  14. description 'Base class for all mutations'
  15. field :errors, [Gql::Types::UserErrorType], description: 'Errors encountered during execution of the mutation.'
  16. # Override this for mutations that don't need CSRF verification.
  17. def self.requires_csrf_verification?
  18. true
  19. end
  20. def self.before_authorize(*args)
  21. ctx = args[-1] # This may be called with 2 or 3 params, context is last.
  22. # CSRF - since this is expensive it is only called by mutations.
  23. verify_csrf_token(ctx) if requires_csrf_verification?
  24. end
  25. # Require authentication by default for mutations.
  26. def self.authorize(_obj, ctx)
  27. ctx.current_user
  28. end
  29. def self.verify_csrf_token(ctx)
  30. return true if ctx[:is_graphql_introspection_generator]
  31. # Support :graphql type tests that don't use HTTP.
  32. return true if Rails.env.test? && !ctx[:controller]
  33. # Support developer workflows that need to turn off CSRF.
  34. return true if Rails.env.development? && ctx[:controller].request.headers['SkipAuthenticityTokenCheck'] == 'true'
  35. ctx[:controller].send(:verify_csrf_token) # verify_csrf_token is private :(
  36. end
  37. def self.register_in_schema(schema)
  38. schema.field graphql_field_name, mutation: self
  39. end
  40. def error_response(*errors)
  41. { errors: errors }
  42. end
  43. end
  44. end