Exemple rapide
namespace App\Security\Voter;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
class UserVoter extends Voter
{
public const EDIT = 'USER_EDIT';
public function __construct(private RoleHierarchyInterface $roleHierarchy) {
}
protected function supports(string $attribute, $subject): bool
{
return \in_array($attribute, [self::EDIT, self::TRANSFER, self::DELETE, self::SEE_NDE]) && $subject instanceof User;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/** @var User $user */
$user = $token->getUser();
//
$subjectRoles = $this->roleHierarchy->getReachableRoleNames($subject->getRoles());
$userRoles = $this->roleHierarchy->getReachableRoleNames($user->getRoles());
//je ne peux pas modifier un utilisateur ayant plus de rôles que moi
if(count($subjectRoles) > count($userRoles)) {
return false;
}
return true;
}
}
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
class UserVoter extends Voter
{
public const EDIT = 'USER_EDIT';
public function __construct(private RoleHierarchyInterface $roleHierarchy) {
}
protected function supports(string $attribute, $subject): bool
{
return \in_array($attribute, [self::EDIT, self::TRANSFER, self::DELETE, self::SEE_NDE]) && $subject instanceof User;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/** @var User $user */
$user = $token->getUser();
//
$subjectRoles = $this->roleHierarchy->getReachableRoleNames($subject->getRoles());
$userRoles = $this->roleHierarchy->getReachableRoleNames($user->getRoles());
//je ne peux pas modifier un utilisateur ayant plus de rôles que moi
if(count($subjectRoles) > count($userRoles)) {
return false;
}
return true;
}
}