Class: Reeve::Authorization::Adapters::Plain

Inherits:
Object
  • Object
show all
Defined in:
lib/reeve/authorization/adapters/plain.rb

Overview

Plain policy objects — always available, no dependency on anything.

class InvoicePolicy
def self.authorize(principal, action, record) = ...
def self.scope(principal, relation) = relation.where(owner: principal)
end

Constant Summary collapse

REQUIRED_METHODS =
%i[authorize scope].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.missing_methods(policy) ⇒ Object



19
20
21
# File 'lib/reeve/authorization/adapters/plain.rb', line 19

def self.missing_methods(policy)
  REQUIRED_METHODS.reject { |method| policy.respond_to?(method) }
end

.supports?(policy) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/reeve/authorization/adapters/plain.rb', line 15

def self.supports?(policy)
  REQUIRED_METHODS.all? { |method| policy.respond_to?(method) }
end

Instance Method Details

#authorize(principal:, policy:, action:, record: nil) ⇒ Object



23
24
25
26
27
28
# File 'lib/reeve/authorization/adapters/plain.rb', line 23

def authorize(principal:, policy:, action:, record: nil)
  rule = rule_for(policy, action)
  allowed = policy.authorize(principal, action, record)

  allowed ? Decision.allow(rule: rule) : Decision.deny(rule: rule)
end

#policy_for(record_class) ⇒ Object

A tool may return more than the type its declared policy governs. Rather than denying every mixed result, reeve looks for the conventional <Model>Policy for the other types — and denies when there is not one (unknown_record_type).



46
47
48
49
50
51
52
53
54
# File 'lib/reeve/authorization/adapters/plain.rb', line 46

def policy_for(record_class)
  name = "#{record_class.name}Policy"
  return nil unless Object.const_defined?(name)

  policy = Object.const_get(name)
  self.class.supports?(policy) ? policy : nil
rescue NameError
  nil
end

#scope(principal:, policy:, relation:) ⇒ Object

Raises:



30
31
32
33
34
35
36
37
# File 'lib/reeve/authorization/adapters/plain.rb', line 30

def scope(principal:, policy:, relation:)
  scoped = policy.scope(principal, relation)
  return scoped unless scoped.nil?

  # A nil scope is a policy that did not answer. Answering "everything" would be
  # the dangerous reading, so this is an error rather than a fallback.
  raise Error, "#{rule_for(policy, :scope)} returned nil; a scope must return a relation"
end

#scope_rule(policy) ⇒ Object



39
40
41
# File 'lib/reeve/authorization/adapters/plain.rb', line 39

def scope_rule(policy)
  rule_for(policy, :scope)
end