src/EventSubscriber/PedometerLogOwnerSubscriber.php line 38

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use ApiPlatform\Symfony\EventListener\EventPriorities;
  5. use App\Entity\PedometerLog;
  6. use App\Entity\User;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Event\ViewEvent;
  9. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. use Symfony\Component\Security\Core\Security;
  12. /**
  13.  * POST et PATCH /api/pedometer_logs : un relevé de pas appartient toujours à l'utilisateur connecté (#3214).
  14.  * Sans propriétaire dans le corps, il le devient ; un autre propriétaire est refusé (403), y compris en PATCH pour
  15.  * attribuer son relevé à quelqu'un d'autre. L'admin n'est pas concerné. Le contrôle est posé avant la validation,
  16.  * donc avant toute écriture (security_post_denormalize ne s'appliquait pas à cette ressource).
  17.  */
  18. class PedometerLogOwnerSubscriber implements EventSubscriberInterface
  19. {
  20.     private Security $security;
  21.     public function __construct(Security $security)
  22.     {
  23.         $this->security = $security;
  24.     }
  25.     public static function getSubscribedEvents(): array
  26.     {
  27.         return [
  28.             KernelEvents::VIEW => ['checkOwner', EventPriorities::PRE_VALIDATE],
  29.         ];
  30.     }
  31.     public function checkOwner(ViewEvent $event): void
  32.     {
  33.         $log = $event->getControllerResult();
  34.         $method = $event->getRequest()->getMethod();
  35.         if (!$log instanceof PedometerLog || !in_array($method, ['POST', 'PATCH', 'PUT'], true) || $this->security->isGranted(User::ROLE_ADMIN)) {
  36.             return;
  37.         }
  38.         $user = $this->security->getUser();
  39.         if (!$user instanceof User) {
  40.             throw new AccessDeniedHttpException();
  41.         }
  42.         if (null === $log->getUser()) {
  43.             $log->setUser($user);
  44.             return;
  45.         }
  46.         if ($log->getUser()->getId() !== $user->getId()) {
  47.             throw new AccessDeniedHttpException('Ce relevé de pas appartient à un autre utilisateur.');
  48.         }
  49.     }
  50. }