<?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\User\UserInterface;
use App\Entity\Notificacion\Notificacion;
use App\Repository\Notificacion\NotificacionAreasRepository;
class NotificacionVoter extends Voter
{
// these strings are just invented: you can use anything
const ACCESS = 'NOTIFICACION_ACCESS';
private $notificacionAreasRepository;
public function __construct(NotificacionAreasRepository $notificacionAreasRepository)
{
$this->notificacionAreasRepository = $notificacionAreasRepository;
}
protected function supports(string $attribute, $subject)
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::ACCESS])
&& $subject instanceof \App\Entity\Notificacion\Notificacion;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
// ... (check conditions and return true to grant permission) ...
switch ($attribute) {
case self::ACCESS:
// logic to determine if the user can ACCESS
return $this->canAccess($subject, $user);
break;
}
return false;
}
private function canAccess(Notificacion $subject, UserInterface $user): bool
{
if($this->notificacionAreasRepository->esUsuarioAdmin($user->getUserIdentifier()))
return true;
return $this->notificacionAreasRepository->mismaArea(
$user->getUserIdentifier(),
$subject->getSsoUsuario()
);
}
}