feat: improve user impersonation using dedicated voter
This commit is contained in:
@@ -22,7 +22,7 @@ security:
|
|||||||
custom_authenticators:
|
custom_authenticators:
|
||||||
- App\Security\BpnAuthenticator
|
- App\Security\BpnAuthenticator
|
||||||
switch_user:
|
switch_user:
|
||||||
role: ROLE_ADMIN
|
role: CAN_IMPERSONATE
|
||||||
logout:
|
logout:
|
||||||
path: app_security_logout
|
path: app_security_logout
|
||||||
target: app_security_login
|
target: app_security_login
|
||||||
|
|||||||
@@ -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');
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user