diff --git a/docs/README.md b/docs/README.md index 24e2f82..882982e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -247,6 +247,7 @@ $firewall->login($identity); $firewall->isLoggedIn(); // true $firewall->getIdentity(); // $identity $firewall->getAuthenticationTime(); // Instant +$firewall->hasRole($role); // bool ``` #### Set or remove login expiration diff --git a/src/Authentication/BaseFirewall.php b/src/Authentication/BaseFirewall.php index 288ebd7..7fe09aa 100644 --- a/src/Authentication/BaseFirewall.php +++ b/src/Authentication/BaseFirewall.php @@ -137,6 +137,17 @@ public function getAuthenticationTime(): Instant return $login->getAuthenticationTime(); } + public function hasRole(string $role): bool + { + $identity = $this->fetchIdentity(); + + if ($identity === null) { + return false; + } + + return $identity->hasRole($role); + } + /** * @throws CannotSetExpiration When expiration is set before user is logged in */ diff --git a/src/Authentication/Firewall.php b/src/Authentication/Firewall.php index 0451ccb..145e16e 100644 --- a/src/Authentication/Firewall.php +++ b/src/Authentication/Firewall.php @@ -42,6 +42,8 @@ public function logout(): void; */ public function getIdentity(): Identity; + public function hasRole(string $role): bool; + /** * @throws CannotGetAuthenticationTime When user is not logged id */ diff --git a/tests/Unit/Authentication/BaseFirewallTest.php b/tests/Unit/Authentication/BaseFirewallTest.php index 06e47fe..6ee09d3 100644 --- a/tests/Unit/Authentication/BaseFirewallTest.php +++ b/tests/Unit/Authentication/BaseFirewallTest.php @@ -92,6 +92,20 @@ public function testIdentityClassUpdate(): void self::assertSame($renewedIdentity, $firewall->getLogins()->getCurrentLogin()->getIdentity()); } + public function testHasRole(): void + { + $identity = new IntIdentity(123, ['foo']); + + $storage = new ArrayLoginStorage(); + $firewall = new TestingFirewall($storage, $this->renewer()); + + self::assertFalse($firewall->hasRole('foo')); + + $firewall->login($identity); + self::assertTrue($firewall->hasRole('foo')); + self::assertFalse($firewall->hasRole('bar')); + } + public function testExpiredIdentities(): void { $storage = new ArrayLoginStorage();