<?php
/**
* Created by PhpStorm.
* User: SUSAN MEDINA
* Date: 10/05/2019
* Time: 01:53 PM
*/
namespace App\EventSubscriber\Company;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\KernelEvents;
use Doctrine\ORM\EntityManagerInterface;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Services\VendorService;
use App\Services\UtilsService;
use App\Exception\AccessDeniedException;
use App\Exception\NotFoundException;
use App\Entity\App\company;
use App\Entity\App\User;
use App\Entity\App\Role;
class CompanyPreWriteSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $authorizationChecker;
private $vendorService;
private $entityManager;
private $utilsService;
private $translator;
public function __construct(
TokenStorageInterface $tokenStorage,
AuthorizationCheckerInterface $checker,
VendorService $vendorService,
EntityManagerInterface $entityManager,
UtilsService $utilsService,
TranslatorInterface $translator
){
$this->tokenStorage = $tokenStorage;
$this->authorizationChecker = $checker;
$this->vendorService = $vendorService;
$this->entityManager = $entityManager;
$this->utilsService = $utilsService;
$this->translator = $translator;
}
public function onKernelView(ViewEvent $event)
{
if ($this->utilsService->isAPublicRequest($event)) {
return;
}
$company = $event->getControllerResult();
$request = $event->getRequest();
$method = $request->getMethod();
$userCurrent = $this->tokenStorage->getToken()->getUser();
if (!($company instanceof Company) ||
(Request::METHOD_POST !== $method && Request::METHOD_PUT && Request::METHOD_DELETE !== $method)
)
return;
if ($this->authorizationChecker->isGranted('ROLE_SUPERADMIN'))
return;
if(!$userCurrent instanceof User)
throw new NotFoundException($this->translator->trans('User current not found'));
$controlAccess = [Role::ROLE_ADMIN];
if (!$this->vendorService->isUserRoleInToVendor($company->getVendor(), $userCurrent, $controlAccess)) {
$controlAccessTranslator = [];
foreach ($controlAccess as $roleName) {
$controlAccessTranslator[] = $this->translator->trans($roleName);
}
throw new AccessDeniedException(
$this->translator->trans('access_allowed_only_for') . (implode(', ', $controlAccessTranslator))
);
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::PRE_WRITE]
];
}
}