Skip to content
This repository has been archived by the owner on Jan 15, 2021. It is now read-only.

Commit

Permalink
Improved AuthHelper::hasRole().
Browse files Browse the repository at this point in the history
  • Loading branch information
Florian Krämer committed Oct 9, 2015
1 parent 4d2e0e9 commit 61e4cdb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/View/Helper/AuthHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public function user($key = null) {
if ($key === null) {
return $this->_userData;
}
return Hash::get($this->_userData(true), $key);
return Hash::get((array)$this->_userData(true), $key);
}

/**
Expand All @@ -125,17 +125,21 @@ public function user($key = null) {
* @param string String of the role identifier.
* @return boolean|null True if the role is in the set of roles for the active user data.
*/
public function hasRole($role) {
if (!is_string($role)) {
public function hasRole($requestedRole) {
if (!is_string($requestedRole) && !is_array($requestedRole)) {
throw new \InvalidArgumentException('Role must be a string!');
}
$roles = $this->user($this->config('roleField'));
if (is_null($roles)) {
return false;
}
if (is_string($roles)) {
return ($role === $roles);
$roles = [$roles];
}
if (is_array($roles)) {
return (in_array($role, $roles));
if (is_string($requestedRole)) {
$requestedRole = [$requestedRole];
}
$result = array_intersect($roles, $requestedRole);
return (count($result) > 0);
}

}
7 changes: 7 additions & 0 deletions tests/TestCase/View/Helper/AuthHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ public function testHasRole() {
$this->assertTrue($Auth->hasRole('manager'));
$this->assertFalse($Auth->hasRole('doesnotexist'));

$this->View->viewVars['userData']['role'] = array(
'manager', 'user'
);
$Auth = new AuthHelper($this->View);
$this->assertTrue($Auth->hasRole('manager'));
$this->assertFalse($Auth->hasRole('doesnotexist'));

try {
$object = new \stdClass();
$Auth->hasRole($object);
Expand Down

0 comments on commit 61e4cdb

Please sign in to comment.