<?php
declare(strict_types=1);
/*
* Copyright (C) Office National de Publication et de Communication - All Rights Reserved
*
* Unauthorized copying of this file, via any medium is strictly prohibited by law
* This file is proprietary and confidential
*/
namespace App\Security\Voter;
use App\Entity\Utilisateur;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
final class UtilisateurVoter extends Voter
{
public const IMPERSONATE = 'impersonate';
/**
* @var Security
*/
private $security;
/**
* @var EntityManagerInterface
*/
private $entityManager;
public function __construct(Security $security, EntityManagerInterface $entityManager)
{
$this->security = $security;
$this->entityManager = $entityManager;
}
protected function supports($attribute, $subject): bool
{
return
self::IMPERSONATE === $attribute &&
$subject instanceof Utilisateur;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
if (self::IMPERSONATE !== $attribute) {
return false;
}
// D'abbord, il faut avoir le role ROLE_ALLOWED_TO_SWITCH
if (!$this->security->isGranted('ROLE_ALLOWED_TO_SWITCH')) {
return false;
}
// Admin peut se passe pour n'importe qui
// if ($this->security->isGranted(['ROLE_ADMIN', 'ROLE_REDACTEUR'])) {
if ($this->security->isGranted('ROLE_ADMIN') || $this->security->isGranted('ROLE_REDACTEUR')) {
return true;
}
// Délégue peut se passer par ses établissements
if ($this->security->isGranted('ROLE_DELEGUE') && $subject->hasRole('ROLE_RESPONSABLE_ETABLISSEMENT')) {
$repository = $this->entityManager->getRepository(Utilisateur::class);
$user = $token->getUser();
$etabs = $subject->getEtablissementsResponsable();
foreach ($etabs as $etab) {
if ($repository->isDelegueOf($user, $etab)) {
return true;
}
}
}
return false;
}
}