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 =
:'*'
DEFAULT_NOT_AUTHORIZED =
->(type, field) { raise NotAuthorizedError.new("#{type}.#{field}") }
NotAuthorizedError =
Class.new(StandardError)
VERSION =
"0.3.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(policy_object: nil, not_authorized: DEFAULT_NOT_AUTHORIZED) ⇒ Guard

Returns a new instance of Guard.



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

def initialize(policy_object: nil, not_authorized: DEFAULT_NOT_AUTHORIZED)
  @policy_object = policy_object
  @not_authorized = not_authorized
end

Instance Attribute Details

#not_authorizedObject (readonly)

Returns the value of attribute not_authorized.



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

def not_authorized
  @not_authorized
end

#policy_objectObject (readonly)

Returns the value of attribute policy_object.



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

def policy_object
  @policy_object
end

Instance Method Details

#instrument(type, field) ⇒ Object



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

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

    if authorized
      old_resolve_proc.call(object, arguments, context)
    else
      not_authorized.call(type, field.name.to_sym)
    end
  end

  field.redefine { resolve(new_resolve_proc) }
end

#use(schema_definition) ⇒ Object



23
24
25
# File 'lib/graphql/guard.rb', line 23

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