src/EventSubscriber/AccessSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\RequestEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  9. use Symfony\Component\Security\Core\Security;
  10. class AccessSubscriber implements EventSubscriberInterface
  11. {
  12.     private Security $security;
  13.     private UrlGeneratorInterface $urlGenerator;
  14.     private const ACCESS_DENIED_ROUTE 'app_403_page';
  15.     private const RESTRICTED_ROUTE_ARRAY = [
  16.         'dh_auditor_list_audits',
  17.         'dh_auditor_show_transaction',
  18.         'dh_auditor_show_entity_history'
  19.     ];
  20.     public function __construct(Security $securityUrlGeneratorInterface $urlGenerator){
  21.         $this->security $security;
  22.         $this->urlGenerator $urlGenerator;
  23.     }
  24.     public function onKernelRequest(RequestEvent $event)
  25.     {
  26.         $routeName $event->getRequest()->attributes->get('_route');
  27.         $user $this->security->getUser();
  28.         // Implement your logic to check user's userType and allowed routes
  29.         if ($user && $user->getUserType() !== 777 && in_array($routeNameself::RESTRICTED_ROUTE_ARRAYtrue)) {
  30.             $event->setResponse(new RedirectResponse($this->urlGenerator->generate(self::ACCESS_DENIED_ROUTE)));
  31.         }
  32.     }
  33.     public static function getSubscribedEvents() : array
  34.     {
  35.         return [
  36.             KernelEvents::REQUEST => 'onKernelRequest',
  37.         ];
  38.     }
  39. }