6

From this guide I don't understand how we can add authorization on a field in graphql-ruby.

I understand how we can deny access to an entire object but I don't see how we can prevent access to just a field of an object. In my usecase, I want to prevent some queries to access a String field in my UserType.

Is it possible? With the field helper?

Such
  • 910
  • 1
  • 9
  • 20

3 Answers3

1

You could use scoping in the GraphQL-ruby or use gem graphql-guard.

For scoping to work, you should be either using Pundit scope or CanCan accessible_by.

FYI, I haven't used it yet anywhere but seems like both could solve your problem to me.

Abhay Nikam
  • 182
  • 1
  • 1
  • 6
1

I used gem graphql-guard.

GUARD = lambda do |obj, args, ctx|
  ...some logics...
end

field :some_field, String, null: false, guard: GUARD

And when I wanted to use only some of the arguments like lambda do |_, args, _|

Colin Lee
  • 201
  • 2
  • 4
1

Here's an example:

module Types
  class User < Types::BaseObject
    field :private_string, String, null: true do
      def authorized?(object, args, context)
        # Do whatever logic you want and return true if the user is authorized.
        object.id == context[:current_user].id
      end
    end
  end
end

class MySchema < GraphQL::Schema
  # You'll need this in your schema to handle an unauthorized field.
  def self.unauthorized_field(error)
    raise GraphQL::ExecutionError, "The field #{error.field.graphql_name} on an object of type #{error.type.graphql_name} was hidden due to permissions"
  end
end

Jacquen
  • 986
  • 8
  • 18