src/Listener/AccessListener.php line 34

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Novo SGA project.
  4.  *
  5.  * (c) Rogerio Lino <rogeriolino@gmail.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace App\Listener;
  11. use App\Repository\ORM\UsuarioRepository;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpKernel\Event\RequestEvent;
  14. use Symfony\Component\HttpKernel\HttpKernelInterface;
  15. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  16. /**
  17.  * AccessListener
  18.  *
  19.  * @author Rogerio Lino <rogeriolino@gmail.com>
  20.  */
  21. class AccessListener extends AppListener
  22. {
  23.     private $authChecker;
  24.     
  25.     public function __construct(AuthorizationCheckerInterface $authChecker)
  26.     {
  27.         $this->authChecker $authChecker;
  28.     }
  29.     
  30.     public function onKernelRequest(RequestEvent $event)
  31.     {
  32.         if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
  33.             return;
  34.         }
  35.         
  36.         $request  $event->getRequest();
  37.         $isApi    $this->isApiRequest($request);
  38.         $isAdmin  $this->isAdminRequest($request);
  39.         $isModule $this->isModuleRequest($request);
  40.         
  41.         
  42.         if ($isApi) {
  43.             return;
  44.         }
  45.         if ($isAdmin) {
  46.             $isUserAdmin $this->authChecker->isGranted('ROLE_ADMIN');
  47.             if (!$isUserAdmin) {
  48.                 $response = new RedirectResponse("/");
  49.                 $event->setResponse($response);
  50.                 return;
  51.             }
  52.         }
  53.         if ($isModule !== false) {
  54.             $role UsuarioRepository::roleName($isModule);
  55.             $isUserModule $this->authChecker->isGranted($role);
  56.             $isUserAdmin $this->authChecker->isGranted('ROLE_ADMIN');
  57.             if (!$isUserAdmin && !$isUserModule) {
  58.                 $response = new RedirectResponse("/");
  59.                 $event->setResponse($response);
  60.             }
  61.         }
  62.     }
  63. }