<?php
namespace App\Security\Voter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
class UserVoter extends Voter
{
public const VIEW_NOTIFICATIONS = 'VIEW_NOTIFICATIONS';
protected function supports(string $attribute, mixed $subject): bool
{
return in_array($attribute, [
self::VIEW_NOTIFICATIONS,
])
&& ($subject instanceof Paginator
|| $subject instanceof User)
;
}
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 (self::VIEW_NOTIFICATIONS === $attribute) {
// 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();
$email = $queryParameters[0]
->getValue()
;
} else {
$email = $subject->getEmail();
}
return $user->getEmail() === $email;
}
return false;
}
}