<?php
namespace PaperKite\Common\Security\Voter;
use PaperKite\Common\Service\DossierReaderService;
use PaperKite\EmployeeApi\Entity\EmployeeInterface;
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 DossierVoter extends Voter
{
public const EDIT = 'DOSSIER_EDIT';
public const VIEW = 'DOSSIER_VIEW';
public function __construct(
private Security $security,
private DossierReaderService $dossierReaderService,
) {
}
protected function supports(string $attribute, $subject): bool
{
// https://symfony.com/doc/current/security/voters.html
return in_array($attribute, [self::EDIT, self::VIEW]);
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
/** @var EmployeeInterface $user */
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof UserInterface) {
return false;
}
if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
return true;
}
$dossier = $this->dossierReaderService->getById($subject);
return self::EDIT === $attribute && $dossier->getAssignedEmployee() === $user->getUserIdentifier();
}
}