Authorization on a field in graphql-ruby
Asked Answered
F

3

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?

Fauteuil answered 9/3, 2019 at 8:29 Comment(0)
U
2

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

Unamuno answered 6/7, 2021 at 15:12 Comment(0)
R
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.

Rusty answered 14/3, 2019 at 12:32 Comment(0)
H
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, _|

Hoashis answered 31/7, 2019 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.