Skip to content

Instantly share code, notes, and snippets.

@msroot
Last active April 1, 2020 19:19
Show Gist options
  • Save msroot/7d48a5603f226a439221d66f4b7efe39 to your computer and use it in GitHub Desktop.
Save msroot/7d48a5603f226a439221d66f4b7efe39 to your computer and use it in GitHub Desktop.
Simple field authorization Ruby GraphQL
# Add the GarfieldPolicy to GraphQL directory
class GarfieldPolicy
attr_accessor :field
attr_accessor :options
def initialize(field:, options:)
@field = field
@options = options || {}
apply
freeze
end
def apply
end
def after_resolve(object:, arguments:, context:, value:, memo:)
value
end
def resolve(object:, arguments:, context:)
authorized = options[:authorize].call(object, arguments, context)
if authorized
yield(object, arguments, nil)
else
raise GraphQL::ExecutionError, "Not authorized to access: #{@field.name}"
end
end
end
# Field usage:
module Types
class UserType < Types::BaseObject
field :id, ID, null: false, extensions: garfield(->(obj, args, ctx) { ctx[:current_user].admin? })
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment