feat: improve user impersonation using dedicated voter

This commit is contained in:
Björn Fromme
2024-04-17 17:59:22 +02:00
parent d42eae0cbc
commit 30218d6f80
2 changed files with 46 additions and 1 deletions
+1 -1
View File
@@ -22,7 +22,7 @@ security:
custom_authenticators:
- App\Security\BpnAuthenticator
switch_user:
role: ROLE_ADMIN
role: CAN_IMPERSONATE
logout:
path: app_security_logout
target: app_security_login
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App\Security\Voter;
use App\Entity\User;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class ImpersonationVoter extends Voter
{
public function __construct(private readonly Security $security)
{
}
protected function supports(string $attribute, mixed $subject): bool
{
return 'CAN_IMPERSONATE' === $attribute && $subject instanceof UserInterface;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$currentUser = $token->getUser();
$targetUser = $subject;
// if the user is anonymous or if the subject is not a user, do not grant access
if (!$currentUser instanceof User || !$targetUser instanceof User) {
return false;
}
// if the current user is trying to impersonate herself, do not grant access
if ($currentUser === $targetUser) {
return false;
}
// if the current user is already impersonating, do not grant access
if ($this->security->isGranted('IS_IMPERSONATOR')) {
return false;
}
// Admin is the only role allowed to impersonate
return $this->security->isGranted('ROLE_ADMIN');
}
}