Class: GraphQL::Guard

Inherits:
Object
  • Object
show all
Defined in:
lib/graphql/guard.rb,
lib/graphql/guard/version.rb

Constant Summary collapse

ANY_FIELD_NAME =
:'*'
NotAuthorizedError =
Class.new(StandardError)
VERSION =
"0.2.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(policy_object: nil) ⇒ Guard

Returns a new instance of Guard.



17
18
19
# File 'lib/graphql/guard.rb', line 17

def initialize(policy_object: nil)
  @policy_object = policy_object
end

Instance Attribute Details

#policy_objectObject (readonly)

Returns the value of attribute policy_object.



15
16
17
# File 'lib/graphql/guard.rb', line 15

def policy_object
  @policy_object
end

Instance Method Details

#instrument(type, field) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/graphql/guard.rb', line 25

def instrument(type, field)
  field_guard_proc = inline_field_guard(field) || policy_object_guard(type, field.name.to_sym)
  type_guard_proc = inline_type_guard(type) || policy_object_guard(type, ANY_FIELD_NAME)
  return field if !field_guard_proc && !type_guard_proc

  old_resolve_proc = field.resolve_proc
  new_resolve_proc = ->(object, arguments, context) do
    authorized =
      if field_guard_proc
        field_guard_proc.call(object, arguments, context)
      elsif type_guard_proc
        type_guard_proc.call(object, context)
      end
    raise NotAuthorizedError.new("#{type}.#{field.name}") unless authorized

    old_resolve_proc.call(object, arguments, context)
  end

  field.redefine { resolve(new_resolve_proc) }
end

#use(schema_definition) ⇒ Object



21
22
23
# File 'lib/graphql/guard.rb', line 21

def use(schema_definition)
  schema_definition.instrument(:field, self)
end