exAspArk / graphql-guard

Simple authorization gem for GraphQL :lock:
MIT License
472 stars 36 forks source link

Is guard proc works on Mutations? #3

Closed bricesanchez closed 7 years ago

bricesanchez commented 7 years ago

As i see in: https://github.com/exAspArk/graphql-guard/blob/master/lib/graphql/guard.rb#L6-L7

It looks like there is no mentions of mutations.

Is it an oversight or it needs a lot of work ?

exAspArk commented 7 years ago

Hey @bricesanchez!

Yes, it should work if you define mutation as GraphQL::ObjectType. For example:

Schema = GraphQL::Schema.define do
  mutation Mutation
end

Mutation = GraphQL::ObjectType.define do
  name "Mutation"
  field :doSomething, field: Mutations::DoSomething.field do
    description "Do something"

    guard: ->(_, _, _) { true } 

    # Works with policy object as well:
    # RULES = {
    #   Graph::Types::Mutation => {
    #     doSomething: ->(_, _, _) { true }
    #   }
    # }
  end
end

Mutations::DoSomething = GraphQL::Relay::Mutation.define do
  name "DoSomething"

  input_field :id, !types.ID
  return_field :something, Something

  resolve ->(object, inputs, context) do
    something = ...
    {something: something}
  end
end

Please let me know whether it works for you.

bricesanchez commented 7 years ago

Hi @exAspArk!

I just come to the same result of you!

Thanks for your quick support!

bricesanchez commented 7 years ago

My solution now stands in a GraphqlPolicy Class

class GraphqlPolicy
  RULES = {
    Types::MutationType => {
      'create_category': ->(obj, inputs, ctx) { ctx[:current_ability].can?(:create, Store::Category) },
      'update_category': ->(obj, inputs, ctx) { ctx[:current_ability].can?(:update, Store::Category) }
    }
  }

[...]

end
exAspArk commented 7 years ago

@bricesanchez awesome! We do the same with policy object :)

Thank you for sharing! 💛