exAspArk / graphql-guard

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

Can't Using Mutation Type and Query Type Together #33

Closed Christianlauw123 closed 4 years ago

Christianlauw123 commented 4 years ago

I'd like to use mutation type and query type to be used in GraphQL Policy, but what i got, only "QueryType" that always got called even call mutation. Is there an idea why this happen?

Rails 5.2.3 Ruby 2.6.3


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

  use GraphQL::Guard.new(
    policy_object: GraphqlPolicy,
    not_authorized: ->(type, field) { GraphQL::ExecutionError.new("Not authorized to access #{field}") }
  )
end

class GraphqlPolicy
    RULES = {
        Types::QueryType => {
          :user => ->(obj,args,ctx) { ctx[:current_user].is_admin || ctx[:current_ability].can?(:read,User.find(args[:id])) },
          :users => ->(obj,args,ctx) { ctx[:current_user].is_admin },
        },
        Types::MutationType => {
          :create_user => ->(obj,args,ctx) { ctx[:current_user].is_admin },
          :update_user => ->(obj,args,ctx) { ctx[:current_ability].can?(:update, User.find(args[:user_id])) || ctx[:current_user].is_admin }
        },

    }

    def self.guard(type, field)
      RULES.dig(type.metadata[:type_class], field)
    end
end
ghost commented 4 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

exAspArk commented 4 years ago

Hey @Christianlauw123,

Thank you for opening this issue! Have you tried using "camelCase" field names in the policy object like createUser, updateUser? The graphql gem converts "underscore_names" to "camelCase", so I think that should work.

I might need to clarify that in the readme :smile_cat:

UPD. updated the readme https://github.com/exAspArk/graphql-guard/commit/9ed1ab4c606a3d0de1ee414fb67f95c90e59457a

Christianlauw123 commented 4 years ago

@exAspArk Yeah it should be camelCased as you comment before, but i realize it after that. Thanks for the comment and knowledge