<?php
namespace App\Security\Voter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
use App\Entity\Student;
use App\Entity\User;
use App\Repository\StudentRepository;
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 StudentVoter extends Voter
{
public const VIEW = 'VIEW_STUDENT';
public const VIEW_SETTINGS = 'VIEW_STUDENT_SETTINGS';
public const VIEW_MOBILITIES = 'VIEW_STUDENT_SETTINGS';
public const EDIT_SETTINGS = 'EDIT_STUDENT_SETTINGS';
private Security $security;
private StudentRepository $studentRepository;
public function __construct(
Security $security,
StudentRepository $studentRepository
) {
$this->security = $security;
$this->studentRepository = $studentRepository;
}
protected function supports(string $attribute, mixed $subject): bool
{
return in_array($attribute, [
self::VIEW,
self::VIEW_SETTINGS,
self::EDIT_SETTINGS,
self::VIEW_MOBILITIES,
])
&& ($subject instanceof Paginator
|| $subject instanceof Student)
;
}
protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
{
/**
* @var User $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;
}
$userStudent = $user->getStudent();
// TODO this should just be temporary until Api Platform allows security check on the owning side
if ($subject instanceof Paginator) {
$query = $subject
->getQuery()
;
$queryParameters = $query->getParameters();
$id = $queryParameters[0]
->getValue()
;
$student = $this->studentRepository->find($id);
} else {
$student = $subject;
}
return match ($attribute) {
self::EDIT_SETTINGS, self::VIEW_SETTINGS, self::VIEW, self::VIEW_MOBILITIES => $userStudent && $userStudent->getId() === $student->getId(),
default => false,
};
}
}