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("Not authorized to access: #{type}.#{field}") }
NotAuthorizedError =
Class.new(StandardError)
VERSION =
"1.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.



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

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.



13
14
15
# File 'lib/graphql/guard.rb', line 13

def not_authorized
  @not_authorized
end

#policy_objectObject (readonly)

Returns the value of attribute policy_object.



13
14
15
# File 'lib/graphql/guard.rb', line 13

def policy_object
  @policy_object
end

Instance Method Details

#guard_proc(type, field) ⇒ Object



49
50
51
52
53
54
# File 'lib/graphql/guard.rb', line 49

def guard_proc(type, field)
  inline_field_guard(field) ||
    policy_object_guard(type, field.name.to_sym) ||
    inline_type_guard(type) ||
    policy_object_guard(type, ANY_FIELD_NAME)
end

#instrument(type, field) ⇒ Object



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

def instrument(type, field)
  guard_proc = guard_proc(type, field)
  return field unless guard_proc

  old_resolve_proc = field.resolve_proc
  new_resolve_proc = ->(object, arguments, context) do
    authorized = guard_proc.call(object, arguments, context)

    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



20
21
22
23
24
25
26
27
28
29
# File 'lib/graphql/guard.rb', line 20

def use(schema_definition)
  schema_definition.instrument(:field, self)
  schema_definition.target.instance_eval do
    def default_filter
      GraphQL::Filter.new(except: default_mask).merge(only: ->(schema_member, ctx) {
        schema_member.[:mask] ? schema_member.[:mask].call(ctx) : true
      })
    end
  end
end