<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Entity\PedometerLog;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
/**
* POST et PATCH /api/pedometer_logs : un relevé de pas appartient toujours à l'utilisateur connecté (#3214).
* Sans propriétaire dans le corps, il le devient ; un autre propriétaire est refusé (403), y compris en PATCH pour
* attribuer son relevé à quelqu'un d'autre. L'admin n'est pas concerné. Le contrôle est posé avant la validation,
* donc avant toute écriture (security_post_denormalize ne s'appliquait pas à cette ressource).
*/
class PedometerLogOwnerSubscriber implements EventSubscriberInterface
{
private Security $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['checkOwner', EventPriorities::PRE_VALIDATE],
];
}
public function checkOwner(ViewEvent $event): void
{
$log = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$log instanceof PedometerLog || !in_array($method, ['POST', 'PATCH', 'PUT'], true) || $this->security->isGranted(User::ROLE_ADMIN)) {
return;
}
$user = $this->security->getUser();
if (!$user instanceof User) {
throw new AccessDeniedHttpException();
}
if (null === $log->getUser()) {
$log->setUser($user);
return;
}
if ($log->getUser()->getId() !== $user->getId()) {
throw new AccessDeniedHttpException('Ce relevé de pas appartient à un autre utilisateur.');
}
}
}