Class: Authoreyes::Authorization::Engine

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/authoreyes/authorization/engine.rb

Overview

Authorization::Engine implements the reference monitor. It may be used for querying the permission and retrieving obligations under which a certain privilege is granted for the current user.

Defined Under Namespace

Classes: AttributeValidator

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Engine

If reader is not given, a new one is created with the default authorization configuration of AUTH_DSL_FILES. If given, may be either a Reader object or a path to a configuration file.



17
18
19
20
21
22
23
# File 'lib/authoreyes/authorization/engine.rb', line 17

def initialize(options)
  options = {
    reader: nil
  }.merge(options)
  #@auth_rules = AuthorizationRuleSet.new reader.auth_rules_reader.auth_rules
  @reader = ::Authoreyes::Parser::DSLParser.factory(options[:reader] || AUTH_DSL_FILES)
end

Instance Attribute Details

#readerObject (readonly)

Returns the value of attribute reader.



8
9
10
# File 'lib/authoreyes/authorization/engine.rb', line 8

def reader
  @reader
end

Class Method Details

.development_reload?Boolean

Returns:

  • (Boolean)


219
220
221
222
223
224
225
226
227
228
# File 'lib/authoreyes/authorization/engine.rb', line 219

def self.development_reload?
  if Rails.env.development?
    mod_time = AUTH_DSL_FILES.map { |m| File.mtime(m) rescue Time.at(0) }.flatten.max
    @@auth_dsl_last_modified ||= mod_time
    if mod_time > @@auth_dsl_last_modified
      @@auth_dsl_last_modified = mod_time
      return true
    end
  end
end

.instance(dsl_file = nil) ⇒ Object

Returns an instance of Engine, which is created if there isn’t one yet. If dsl_file is given, it is passed on to Engine.new and a new instance is always created.



233
234
235
236
237
238
239
# File 'lib/authoreyes/authorization/engine.rb', line 233

def self.instance (dsl_file = nil)
  if dsl_file or development_reload?
    @@instance = new(dsl_file)
  else
    @@instance ||= new
  end
end

Instance Method Details

#description_for(role) ⇒ Object

Returns the description for the given role. The description may be specified with the authorization rules. Returns nil if none was given.



185
186
187
# File 'lib/authoreyes/authorization/engine.rb', line 185

def description_for (role)
  role_descriptions[role]
end

#initialize_copy(from) ⇒ Object

:nodoc:



25
26
27
# File 'lib/authoreyes/authorization/engine.rb', line 25

def initialize_copy(from) # :nodoc:
  @reader = from.reader.clone
end

#obligations(privilege, options = {}) ⇒ Object

Returns the obligations to be met by the current user for the given privilege as an array of obligation hashes in form of

[{:object_attribute => obligation_value, ...}, ...]

where obligation_value is either (recursively) another obligation hash or a value spec, such as

[operator, literal_value]

The obligation hashes in the array should be OR’ed, conditions inside the hashes AND’ed.

Example

{:branch => {:company => [:is, 24]}, :active => [:is, true]}

Options

:context

See permit!

:user

See permit!



168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/authoreyes/authorization/engine.rb', line 168

def obligations (privilege, options = {})
  options = {:context => nil}.merge(options)
  user, roles, privileges = user_roles_privleges_from_options(privilege, options)

  permit!(privilege, :skip_attribute_test => true, :user => user, :context => options[:context])

  return [] if roles.is_a?(Array) and not (roles & omnipotent_roles).empty?

  attr_validator = AttributeValidator.new(self, user, nil, privilege, options[:context])
  matching_auth_rules(roles, privileges, options[:context]).collect do |rule|
    rule.obligations(attr_validator)
  end.flatten
end

#permit!(privilege, options = {}) ⇒ Object

Returns true if privilege is met by the current user. Raises AuthorizationError otherwise. privilege may be given with or without context. In the latter case, the :context option is required.

Options:

:context

The context part of the privilege. Defaults either to the tableized class_name of the given :object, if given. That is, :users for :object of type User. Raises AuthorizationUsageError if context is missing and not to be inferred.

:object

An context object to test attribute checks against.

:skip_attribute_test

Skips those attribute checks in the authorization rules. Defaults to false.

:user

The user to check the authorization for. Defaults to Authorization#current_user.

:bang

Should NotAuthorized exceptions be raised Defaults to true.



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/authoreyes/authorization/engine.rb', line 78

def permit! (privilege, options = {})
  return true if Authorization.ignore_access_control
  options = {
    :object => nil,
    :skip_attribute_test => false,
    :context => nil,
    :bang => true
  }.merge(options)

  # Make sure we're handling all privileges as symbols.
  privilege = privilege.is_a?( Array ) ?
              privilege.flatten.collect { |priv| priv.to_sym } :
              privilege.to_sym

  # Convert context to symbol as well
  unless options[:context].nil?
    options[:context] = options[:context].to_sym
  end

  #
  # If the object responds to :proxy_reflection, we're probably working with
  # an association proxy.  Use 'new' to leverage ActiveRecord's builder
  # functionality to obtain an object against which we can check permissions.
  #
  # Example: permit!( :edit, :object => user.posts )
  #
  if Authorization.is_a_association_proxy?(options[:object]) && options[:object].respond_to?(:new)
    options[:object] = (Rails.version < "3.0" ? options[:object] : options[:object].where(nil)).new
  end

  options[:context] ||= options[:object] && (
    options[:object].class.respond_to?(:decl_auth_context) ?
        options[:object].class.decl_auth_context :
        options[:object].class.name.tableize.to_sym
  ) rescue NoMethodError

  user, roles, privileges = user_roles_privleges_from_options(privilege, options)

  return true if roles.is_a?(Array) and not (roles & omnipotent_roles).empty?

  # find a authorization rule that matches for at least one of the roles and
  # at least one of the given privileges
  attr_validator = AttributeValidator.new(self, user, options[:object], privilege, options[:context])
  rules = matching_auth_rules(roles, privileges, options[:context])

  # Test each rule in turn to see whether any one of them is satisfied.
  rules.each do |rule|
    return true if rule.validate?(attr_validator, options[:skip_attribute_test])
  end

  if options[:bang]
    if rules.empty?
      raise NotAuthorized, "No matching rules found for #{privilege} for #{user.inspect} " +
        "(roles #{roles.inspect}, privileges #{privileges.inspect}, " +
        "context #{options[:context].inspect})."
    else
      raise AttributeAuthorizationError, "#{privilege} not allowed for #{user.inspect} on #{(options[:object] || options[:context]).inspect}."
    end
  else
    false
  end
end

#permit?(privilege, options = {}) ⇒ Boolean

Calls permit! but doesn’t raise authorization errors. If no exception is raised, permit? returns true and yields to the optional block.

Returns:

  • (Boolean)


143
144
145
146
147
148
149
150
# File 'lib/authoreyes/authorization/engine.rb', line 143

def permit? (privilege, options = {}) # :yields:
  if permit!(privilege, options.merge(:bang=> false))
    yield if block_given?
    true
  else
    false
  end
end

#rev_priv_hierarchyObject

ctx] => [priv, …]



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/authoreyes/authorization/engine.rb', line 30

def rev_priv_hierarchy
  if @rev_priv_hierarchy.nil?
    @rev_priv_hierarchy = {}
    privilege_hierarchy.each do |key, value|
      value.each do |val|
        @rev_priv_hierarchy[val] ||= []
        @rev_priv_hierarchy[val] << key
      end
    end
  end
  @rev_priv_hierarchy
end

#rev_role_hierarchyObject

ctx] => [priv, …]



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/authoreyes/authorization/engine.rb', line 44

def rev_role_hierarchy
  if @rev_role_hierarchy.nil?
    @rev_role_hierarchy = {}
    role_hierarchy.each do |higher_role, lower_roles|
      lower_roles.each do |role|
        (@rev_role_hierarchy[role] ||= []) << higher_role
      end
    end
  end
  @rev_role_hierarchy
end

#roles_for(user) ⇒ Object

Returns the role symbols of the given user.



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/authoreyes/authorization/engine.rb', line 197

def roles_for (user)
  user ||= Authorization.current_user
  raise AuthorizationUsageError, "User object doesn't respond to roles (#{user.inspect})" \
    if !user.respond_to?(:role_symbols) and !user.respond_to?(:roles)

  Rails.logger.info("The use of user.roles is deprecated.  Please add a method " +
      "role_symbols to your User model.") if defined?(Rails) and Rails.respond_to?(:logger) and !user.respond_to?(:role_symbols)

  roles = user.respond_to?(:role_symbols) ? user.role_symbols : user.roles

  raise AuthorizationUsageError, "User.#{user.respond_to?(:role_symbols) ? 'role_symbols' : 'roles'} " +
    "doesn't return an Array of Symbols (#{roles.inspect})" \
        if !roles.is_a?(Array) or (!roles.empty? and !roles[0].is_a?(Symbol))

  (roles.empty? ? [Authorization.default_role] : roles)
end

#roles_with_hierarchy_for(user) ⇒ Object

Returns the role symbols and inherritted role symbols for the given user



215
216
217
# File 'lib/authoreyes/authorization/engine.rb', line 215

def roles_with_hierarchy_for(user)
  flatten_roles(roles_for(user))
end

#title_for(role) ⇒ Object

Returns the title for the given role. The title may be specified with the authorization rules. Returns nil if none was given.



192
193
194
# File 'lib/authoreyes/authorization/engine.rb', line 192

def title_for (role)
  role_titles[role]
end