Skip to content

Instantly share code, notes, and snippets.

@thiago-sydow
Last active December 26, 2017 15:51
Show Gist options
  • Save thiago-sydow/b8f428c150fa5f5bf2292149542f6a8e to your computer and use it in GitHub Desktop.
Save thiago-sydow/b8f428c150fa5f5bf2292149542f6a8e to your computer and use it in GitHub Desktop.
Files used in the Medium post about Field Instrumentation
class FieldAuthorization
def instrument(_type, field)
return field if field.metadata[:access_permission].blank?
resolve_proc = authorization_proc(field)
# Return a copy of `field`, with a new resolve proc
field.redefine do
resolve(resolve_proc)
end
end
private
def authorization_proc(field)
permission = field.metadata[:access_permission]
original_resolve_proc = field.resolve_proc
->(obj, args, ctx) {
resolved = original_resolve_proc.call(obj, args, ctx)
policy = permission[:policy_class].new(ctx[:current_user], resolved)
raise GraphQL::ExecutionError, :forbidden unless policy.send(permission[:action])
resolved
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment