<?php
/**
* Created by PhpStorm.
* User: SUSAN MEDINA
* Date: 21/05/2019
* Time: 02:15 PM
*/
namespace App\EventSubscriber\Chat;
use App\Services\UtilsService;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\KernelEvents;
use App\Exception\NotFoundException;
use App\Services\ChatService;
use App\Entity\Chat\Chat;
use App\Entity\App\User;
class ChatPreSerializeSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $authorizationChecker;
private $chatService;
private $utilsService;
private $translator;
private $request;
public function __construct(
TokenStorageInterface $tokenStorage,
AuthorizationCheckerInterface $checker,
ChatService $chatService,
UtilsService $utilsService,
TranslatorInterface $translator,
RequestStack $requestStack
) {
$this->tokenStorage = $tokenStorage;
$this->authorizationChecker = $checker;
$this->chatService = $chatService;
$this->utilsService = $utilsService;
$this->translator = $translator;
$this->request = $requestStack->getCurrentRequest();
}
/**
* @param ViewEvent $event
* @return Response|void
* @throws NotFoundException
*/
public function onKernelView(ViewEvent $event)
{
if ($this->utilsService->isAPublicRequest($event)) {
return;
}
$chat = $event->getControllerResult();
$request = $event->getRequest();
$method = $request->getMethod();
if (!($chat instanceof Chat) || (Request::METHOD_GET !== $method)) {
return;
}
$userCurrent = $this->tokenStorage->getToken()->getUser();
if (!($userCurrent instanceof User)) {
$response = new Response();
$response->setContent(json_encode([
'detail' => $this->translator->trans(
'User current not found',
[],
null,
$this->request->getLocale())
]));
$response->setStatusCode(Response::HTTP_NOT_ACCEPTABLE);
return $response;
}
if ($this->authorizationChecker->isGranted('ROLE_SUPERADMIN')) {
return;
}
$authorization = false;
$userChat = $this->chatService->getUsersOfChat($chat);
$search = array_search($userCurrent->getId(), array_column($userChat, 'id'));
if ($search !== false){
$authorization = true;
}
if (!$authorization) {
$response = new Response();
$response->setContent(json_encode([
'detail' => $this->translator->trans(
'You have not permission for write on this chat',
[],
null,
$this->request->getLocale())
]));
$response->setStatusCode(Response::HTTP_NOT_ACCEPTABLE);
return $response;
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::PRE_SERIALIZE]
];
}
}