Introduce `User::can()' for checking whether a user has a given permission

The authentication manager already has the `hasPermission()' method but it lacks wildcard support
and uses stupid looping. Implementing this method on the user further saves a call to `User::getPermissions()'.
This commit is contained in:
Eric Lippmann 2014-09-18 14:37:18 +02:00
parent 18aad562dd
commit af58732545
2 changed files with 51 additions and 5 deletions

View File

@ -187,9 +187,9 @@ class User
}
/**
* Return permission information for this user
* Get the user's permissions
*
* @return array
* @return array
*/
public function getPermissions()
{
@ -197,13 +197,17 @@ class User
}
/**
* Setter for permissions
* Set the user's permissions
*
* @param array $permissions
* @param array $permissions
*
* @return $this
*/
public function setPermissions(array $permissions)
{
$this->permissions = $permissions;
natcasesort($permissions);
$this->permissions = array_combine($permissions, $permissions);
return $this;
}
/**
@ -444,4 +448,31 @@ class User
{
return (count($this->remoteUserInformation)) ? true : false;
}
/**
* Whether the user has a given permission
*
* @param string $permission
*
* @return bool
*/
public function can($permission)
{
if (isset($this->permissions['*']) || isset($this->permissions[$permission])) {
return true;
}
foreach ($this->permissions as $permitted) {
$wildcard = strpos($permitted, '*');
if ($wildcard !== false) {
if (substr($permission, 0, $wildcard) === substr($permitted, 0, $wildcard)) {
return true;
} else {
if ($permission === $permitted) {
return true;
}
}
}
}
return false;
}
}

View File

@ -60,4 +60,19 @@ class UserTest extends BaseTestCase
$user = new User('unittest');
$user->setEmail('mySampleEmail at someDomain dot org');
}
public function testPermissions()
{
$user = new User('test');
$user->setPermissions(array(
'test',
'test/some/specific',
'test/more/*'
));
$this->assertTrue($user->can('test'));
$this->assertTrue($user->can('test/some/specific'));
$this->assertTrue($user->can('test/more/everything'));
$this->assertFalse($user->can('not/test'));
$this->assertFalse($user->can('test/some/not/so/specific'));
}
}