diff --git a/lib/graphql-pundit/instrumenter.rb b/lib/graphql-pundit/instrumenter.rb index b298df2..6676e77 100644 --- a/lib/graphql-pundit/instrumenter.rb +++ b/lib/graphql-pundit/instrumenter.rb @@ -4,6 +4,7 @@ module GraphQL module Pundit + # The authorization Instrumenter class Instrumenter attr_reader :current_user @@ -12,43 +13,41 @@ def initialize(current_user = :current_user) end def instrument(_type, field) - if field.metadata[:authorize] - old_resolve = field.resolve_proc - resolve_proc = resolve_proc(current_user, - old_resolve, - field.metadata[:authorize]) - field.redefine do - resolve resolve_proc - end - else - # :nocov: - # If no authorization metadata is set, skip and just return the - # original field - field - # :nocov: + return field unless field.metadata[:authorize] + + old_resolve = field.resolve_proc + resolve_proc = resolve_proc(current_user, + old_resolve, + field.metadata[:authorize]) + field.redefine do + resolve resolve_proc end end + private + def resolve_proc(current_user, old_resolve, options) lambda do |obj, args, ctx| begin - result = if options[:proc] - options[:proc].call(obj, args, ctx) - else - query = options[:query].to_s + '?' - record = options[:record] || obj - ::Pundit.authorize(ctx[current_user], record, query) - end + result = authorize(current_user, obj, args, ctx, options) raise ::Pundit::NotAuthorizedError unless result old_resolve.call(obj, args, ctx) rescue ::Pundit::NotAuthorizedError - if options[:raise] - raise GraphQL::ExecutionError, - "You're not authorized to do this" - end + error_message = "You're not authorized to do this" + raise GraphQL::ExecutionError, error_message if options[:raise] end end end + + def authorize(current_user, obj, args, ctx, options) + if options[:proc] + options[:proc].call(obj, args, ctx) + else + ::Pundit.authorize(ctx[current_user], + options[:record] || obj, + options[:query].to_s + '?') + end + end end end end