1

I'm using graphql-ruby and trying to protect admin's mutation in schema like that

class MySchema < GraphQL::Schema

  mutation(Types::Admin::MutationType) if context[:current_user].admin?

  mutation(Types::MutationType)
  query(Types::QueryType)

end

but i don't have the context there. Also tried to do the same thing in Types::Admin::MutationType, same result.

Is it possible to check out context anywhere before resolve?

mzsrn
  • 41
  • 4

1 Answers1

0

One of the best if not the best guide that I found is here. It provides extensive documentation and guides. Try using the self.visible?(ctx) method. I also feel like you're fighting the gem instead of working with it. Try to restructure your code as outlined below. It may be easier to work with.

the context object doesn't get attached to the schema until the execute method is called on it. This usually happens in your 'app/controllers/graphql_controller.rb' file. So overall, you won't get to access the `context' object until your application executes your schema. Since QueryType and MutationType get attached to it after you may want to do the following assuming you used the built in code generation tool.


# '/app/graphql/my_schema.rb'

class MySchema < GraphQL::Schema
  mutation(Types::MutationType)
  query(Types::QueryType)
end

# '/app/graphql/types/mutation_type.rb'
class Types::MutationType < Types::BaseObject
  field :some_admin_mutation, mutation: Mutations::Admin::SomeAdminMutation
end


# '/app/graphql/mutations/admin/some_admin_mutation.rb'
class Mutations::Admin::SomeAdminMutation < Mutations::BaseMutation
  ...

   # using this class method, you can choose to hide certain mutations
   def self.visible?(context)
      context[:current_user].admin?
   end
end

test it out using the following graphql query (I use apollo for chrome)

{
  __schema {
    mutationType {
      name
      fields {
        name
      }
    }
  }
}
Ben Hodge
  • 147
  • 1
  • 5