class Authoraise::Policy

Public Class Methods

new() { |self| ... } click to toggle source
# File lib/authoraise.rb, line 37
def initialize
  @checks = []
  yield(self) if block_given?
end

Public Instance Methods

allow(&procedure) click to toggle source
# File lib/authoraise.rb, line 42
def allow(&procedure)
  @checks <<
    Check.new(procedure.parameters.map(&:last), procedure)
end
authorize(options = {}) click to toggle source
# File lib/authoraise.rb, line 47
def authorize(options = {})
  raise Error, 'Policy is empty' if @checks.empty?
  given_keys = options.keys.to_set
  assert_all_keys_match(given_keys) if Authoraise.strict_mode
  missing_keys = Set.new

  @checks.each do |check|
    if check.required_keys.subset?(given_keys)
      return true if check.(options)
    else
      missing_keys += check.missing_keys(given_keys)
    end
  end

  if missing_keys.empty?
    return false
  else
    raise Error,
      "Inconclusive authorization, missing keys: #{missing_keys.to_a}"
  end
end
freeze() click to toggle source
Calls superclass method
# File lib/authoraise.rb, line 69
def freeze
  @checks.freeze
  super
end

Private Instance Methods

assert_all_keys_match(given_keys) click to toggle source
# File lib/authoraise.rb, line 76
def assert_all_keys_match(given_keys)
  missing_keys = @checks.inject(Set.new) do |set, check|
    set + check.missing_keys(given_keys)
  end.to_a

  if !missing_keys.empty?
    raise Error, "Strict mode found missing keys: #{missing_keys}"
  end
end