Module: Reeve::Authorization::Adapter

Defined in:
lib/reeve/authorization/adapter.rb

Overview

Chooses the adapter a policy speaks through, and refuses declarations no adapter can serve — at declaration time, so the developer learns immediately rather than on the first denial in production (Constitution VI).

Constant Summary collapse

BUILT_IN =
{ plain: Adapters::Plain, pundit: Adapters::Pundit }.freeze

Class Method Summary collapse

Class Method Details

.auto_resolve(policy) ⇒ Object



44
45
46
# File 'lib/reeve/authorization/adapter.rb', line 44

def auto_resolve(policy)
  Adapters::Pundit.supports?(policy) ? Adapters::Pundit.new : Adapters::Plain.new
end

.resolve(policy, setting = Reeve.config.policy_adapter) ⇒ Object



13
14
15
16
17
18
19
20
# File 'lib/reeve/authorization/adapter.rb', line 13

def resolve(policy, setting = Reeve.config.policy_adapter)
  case setting
  when :plain  then Adapters::Plain.new
  when :pundit then Adapters::Pundit.new
  when :auto   then auto_resolve(policy)
  else setting # a host-supplied adapter object; Configuration validated its protocol
  end
end

.resolve_name(policy, setting = Reeve.config.policy_adapter) ⇒ Object



22
23
24
25
26
# File 'lib/reeve/authorization/adapter.rb', line 22

def resolve_name(policy, setting = Reeve.config.policy_adapter)
  return setting unless setting == :auto

  Adapters::Pundit.supports?(policy) ? :pundit : :plain
end

.supported?(policy, setting = Reeve.config.policy_adapter) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
38
39
40
41
42
# File 'lib/reeve/authorization/adapter.rb', line 35

def supported?(policy, setting = Reeve.config.policy_adapter)
  case setting
  when :plain  then Adapters::Plain.supports?(policy)
  when :pundit then Adapters::Pundit.supports?(policy)
  when :auto   then Adapters::Pundit.supports?(policy) || Adapters::Plain.supports?(policy)
  else true # a custom adapter is trusted to know its own policies
  end
end

.unsupported_message(policy, setting) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/reeve/authorization/adapter.rb', line 48

def unsupported_message(policy, setting)
  described = policy.respond_to?(:name) && policy.name ? policy.name : policy.inspect
  missing = Adapters::Plain.missing_methods(policy).map do |method|
    "##{method}"
  end.join(" and ")

  "#{described} cannot be used as a reeve policy (policy_adapter is #{setting.inspect}). " \
    "A plain policy must respond to #{missing.empty? ? '#authorize and #scope' : missing}; " \
    "a Pundit policy must define a query method and a Scope class."
end

.validate!(policy, setting = Reeve.config.policy_adapter) ⇒ Object

Raises unless some adapter can serve this policy. Called from guard_with.

Raises:



29
30
31
32
33
# File 'lib/reeve/authorization/adapter.rb', line 29

def validate!(policy, setting = Reeve.config.policy_adapter)
  return true if supported?(policy, setting)

  raise ConfigurationError, unsupported_message(policy, setting)
end