Last active
April 1, 2020 19:19
-
-
Save msroot/7d48a5603f226a439221d66f4b7efe39 to your computer and use it in GitHub Desktop.
Simple field authorization Ruby GraphQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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