From 78e3ea50c7ee8ddf2e238bbb673ed7e8479a0524 Mon Sep 17 00:00:00 2001 From: Vincent Langlet Date: Fri, 2 Jul 2021 13:21:45 +0200 Subject: [PATCH] Support custom role --- src/Security/Handler/RoleSecurityHandler.php | 10 ++++++++-- tests/Security/Handler/RoleSecurityHandlerTest.php | 6 ++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/Security/Handler/RoleSecurityHandler.php b/src/Security/Handler/RoleSecurityHandler.php index 6960c05021..6363bce3d3 100644 --- a/src/Security/Handler/RoleSecurityHandler.php +++ b/src/Security/Handler/RoleSecurityHandler.php @@ -57,8 +57,14 @@ public function isGranted(AdminInterface $admin, $attributes, $object = null) $attributes = [$attributes]; } + $useAll = false; foreach ($attributes as $pos => $attribute) { - $attributes[$pos] = sprintf($this->getBaseRole($admin), $attribute); + // If the attribute is not already a ROLE_ we generate the related role. + if (0 !== strpos($attribute, 'ROLE_')) { + $attributes[$pos] = sprintf($this->getBaseRole($admin), $attribute); + // All the admin related role are available when you have the `_ALL` role. + $useAll = true; + } } $allRole = sprintf($this->getBaseRole($admin), 'ALL'); @@ -66,7 +72,7 @@ public function isGranted(AdminInterface $admin, $attributes, $object = null) try { return $this->isAnyGranted($this->superAdminRoles) || $this->isAnyGranted($attributes, $object) - || $this->isAnyGranted([$allRole], $object); + || $useAll && $this->isAnyGranted([$allRole], $object); } catch (AuthenticationCredentialsNotFoundException $e) { return false; } diff --git a/tests/Security/Handler/RoleSecurityHandlerTest.php b/tests/Security/Handler/RoleSecurityHandlerTest.php index 7fd8dc8d51..20aae8df0a 100644 --- a/tests/Security/Handler/RoleSecurityHandlerTest.php +++ b/tests/Security/Handler/RoleSecurityHandlerTest.php @@ -85,6 +85,7 @@ public function testIsGranted(bool $expected, array $superAdminRoles, string $ad case 'ROLE_IRONMAN': case 'ROLE_FOO_BAR_ABC': case 'ROLE_FOO_BAR_BAZ_ALL': + case 'ROLE_CUSTOM': return true; case 'ROLE_AUTH_EXCEPTION': throw new AuthenticationCredentialsNotFoundException(); @@ -162,6 +163,11 @@ public function getIsGrantedTests(): array [false, [], 'foo.bar.baz.xyz', ['BAZ'], new \stdClass()], [false, ['ROLE_AUTH_EXCEPTION'], 'foo.bar.baz.xyz', ['BAZ'], new \stdClass()], + //role + [false, [], 'foo.bar', ['CUSTOM']], + [true, [], 'foo.bar', ['ROLE_CUSTOM']], + [false, [], 'foo.bar', ['ROLE_ANOTHER_CUSTOM']], + // ALL role [true, [], 'foo.bar.baz', 'LIST'], [true, [], 'foo.bar.baz', ['LIST', 'EDIT']],