From af5873254501846a8860cd0765ec7aa8d1f644e9 Mon Sep 17 00:00:00 2001 From: Eric Lippmann Date: Thu, 18 Sep 2014 14:37:18 +0200 Subject: [PATCH] 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()'. --- library/Icinga/User.php | 41 ++++++++++++++++++++++++---- test/php/library/Icinga/UserTest.php | 15 ++++++++++ 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/library/Icinga/User.php b/library/Icinga/User.php index 13f62881a..da894151f 100644 --- a/library/Icinga/User.php +++ b/library/Icinga/User.php @@ -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; + } } diff --git a/test/php/library/Icinga/UserTest.php b/test/php/library/Icinga/UserTest.php index ebb39293e..d12666b04 100644 --- a/test/php/library/Icinga/UserTest.php +++ b/test/php/library/Icinga/UserTest.php @@ -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')); + } }