Module: AccessGranted::Policy

Included in:
AccessPolicy
Defined in:
lib/access-granted/policy.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#cacheObject

Returns the value of attribute cache.



3
4
5
# File 'lib/access-granted/policy.rb', line 3

def cache
  @cache
end

#rolesObject

Returns the value of attribute roles.



3
4
5
# File 'lib/access-granted/policy.rb', line 3

def roles
  @roles
end

#userObject (readonly)

Returns the value of attribute user.



4
5
6
# File 'lib/access-granted/policy.rb', line 4

def user
  @user
end

Instance Method Details

#applicable_rolesObject



66
67
68
69
70
# File 'lib/access-granted/policy.rb', line 66

def applicable_roles
  @applicable_roles ||= roles.select do |role|
    role.applies_to?(user)
  end
end

#authorize!(action, subject, message = 'Access Denied') ⇒ Object



59
60
61
62
63
64
# File 'lib/access-granted/policy.rb', line 59

def authorize!(action, subject, message = 'Access Denied')
  if cannot?(action, subject)
    raise AccessDenied.new(action, subject, message)
  end
  subject
end

#can?(action, subject = nil) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/access-granted/policy.rb', line 30

def can?(action, subject = nil)
  cache[action] ||= {}

  if cache[action][subject]
    cache[action][subject]
  else
    granted, actions = check_permission(action, subject)
    actions.each do |a|
      cache[a] ||= {}
      cache[a][subject] ||= granted
    end

    granted
  end
end

#cannot?(*args) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/access-granted/policy.rb', line 55

def cannot?(*args)
  !can?(*args)
end

#check_permission(action, subject) ⇒ Object



46
47
48
49
50
51
52
53
# File 'lib/access-granted/policy.rb', line 46

def check_permission(action, subject)
  applicable_roles.each do |role|
    permission = role.find_permission(action, subject)
    return [permission.granted, permission.actions] if permission
  end

  [false, []]
end

#configureObject



13
14
# File 'lib/access-granted/policy.rb', line 13

def configure
end

#initialize(user, cache_enabled = true) ⇒ Object



6
7
8
9
10
11
# File 'lib/access-granted/policy.rb', line 6

def initialize(user, cache_enabled = true)
  @user          = user
  @roles         = []
  @cache         = {}
  configure
end

#role(name, conditions_or_klass = nil, conditions = nil, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/access-granted/policy.rb', line 16

def role(name, conditions_or_klass = nil, conditions = nil, &block)
  name = name.to_sym
  if roles.select {|r| r.name == name }.any?
    raise DuplicateRole, "Role '#{name}' already defined"
  end
  r = if conditions_or_klass.is_a?(Class) && conditions_or_klass <= AccessGranted::Role
    conditions_or_klass.new(name, conditions, user, block)
  else
    Role.new(name, conditions_or_klass, user, block)
  end
  roles << r
  r
end