This repository has been archived by the owner on Nov 19, 2019. It is now read-only.
/
authority.rb
68 lines (54 loc) · 1.76 KB
/
authority.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
require 'active_support/concern'
require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/string/inflections'
require 'logger'
module Authority
# NOTE: once this method is called, the library has started meta programming
# and abilities should no longer be modified
# @return [Hash] list of abilities, mapping verbs and adjectives, like :create => 'creatable'
def self.abilities
configuration.abilities.freeze
end
# @return [Array] keys from adjectives method
def self.verbs
abilities.keys
end
# @return [Array] values from adjectives method
def self.adjectives
abilities.values
end
# @param [Symbol] action
# @param [Model] resource instance
# @param [User] user instance
# @raise [SecurityTransgression] if user is not allowed to perform action on resource
# @return [Model] resource instance
def self.enforce(action, resource, user)
action_authorized = user.send("can_#{action}?", resource)
unless action_authorized
message = "#{user} is not authorized to #{action} this resource: #{resource.inspect}"
raise SecurityTransgression.new(message)
end
resource
end
class << self
attr_accessor :configuration
end
def self.configure
self.configuration ||= Configuration.new
yield(configuration) if block_given?
require_authority_internals!
configuration
end
private
def self.require_authority_internals!
require 'authority/abilities'
require 'authority/authorizer'
require 'authority/user_abilities'
end
class SecurityTransgression < StandardError ; end
end
require 'authority/configuration'
require 'authority/controller'
require 'authority/railtie' if defined?(Rails)
require 'authority/version'