<?php
namespace App\Security\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class SwitchUserVoter extends Voter
{
/**
* SwitchUserVoter constructor.
*/
public function __construct(
private Security $security
) {
}
protected function supports(string $attribute, mixed $subject): bool
{
return 'CAN_SWITCH_USER' == $attribute && $subject instanceof UserInterface;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof UserInterface || !$subject instanceof UserInterface) {
return false;
}
// you can still check for ROLE_ALLOWED_TO_SWITCH
if ($this->security->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
if (!$this->security->isGranted('ROLE_SUPER_ADMIN') && in_array($subject->getRoles()[0], ['ROLE_ADMIN', 'ROLE_SUPER_ADMIN'])) {
return false;
}
return true;
}
return false;
}
}