Skip to content

Commit

Permalink
add and test has_any_role_with_hierarchy?
Browse files Browse the repository at this point in the history
Allows passing an array of roles and returning true/executing a block if ANY of the supplied roles are present rather than ALL
  • Loading branch information
tpickett66 authored and stffn committed Mar 28, 2011
1 parent 2a465d3 commit dbbe783
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 2 deletions.
4 changes: 4 additions & 0 deletions lib/declarative_authorization/helper.rb
Expand Up @@ -60,5 +60,9 @@ def has_role_with_hierarchy?(*roles, &block)
def has_any_role?(*roles,&block)
controller.has_any_role?(*roles,&block)
end

def has_any_role_with_hierarchy?(*roles, &block)
controller.has_any_role_with_hierarchy?(*roles, &block)
end
end
end
9 changes: 9 additions & 0 deletions lib/declarative_authorization/in_controller.rb
Expand Up @@ -107,6 +107,15 @@ def has_role_with_hierarchy?(*roles, &block)
result
end

# As has_any_role? except checks all roles included in the role hierarchy
def has_any_role_with_hierarchy?(*roles, &block)
user_roles = authorization_engine.roles_with_hierarchy_for(current_user)
result = roles.any? do |role|
user_roles.include?(role)
end
yield if result and block_given?
result
end

protected
def filter_access_filter # :nodoc:
Expand Down
44 changes: 42 additions & 2 deletions test/helper_test.rb
Expand Up @@ -200,8 +200,48 @@ def test_has_role_with_hierarchy
block_evaled = true
end
assert !block_evaled

end


def test_has_any_role_with_hierarchy
reader = Authorization::Reader::DSLReader.new
reader.parse %{
authorization do
role :test_role do
has_permission_on :mocks, :to => :show
end
role :other_role do
has_permission_on :another_mocks, :to => :show
end
role :root do
includes :test_role
end
end
}

user = MockUser.new(:root)
request!(user, :action, reader)

assert has_any_role_with_hierarchy?(:test_role)
assert !has_any_role_with_hierarchy?(:other_role)
assert has_any_role_with_hierarchy?(:test_role,:other_role)

block_evaled = false
has_any_role_with_hierarchy?(:test_role) do
block_evaled = true
end
assert block_evaled

block_evaled = false
has_any_role_with_hierarchy?(:test_role2) do
block_evaled = true
end
assert !block_evaled

block_evaled = false
has_any_role_with_hierarchy?(:test_role,:test_role2) do
block_evaled = true
end
assert block_evaled
end
end

0 comments on commit dbbe783

Please sign in to comment.