src/EventSubscriber/EasyAdmin/EasyAdminSubscriber.php line 51

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\EasyAdmin;
  3. use App\Security\RoleInterface;
  4. use EasyCorp\Bundle\EasyAdminBundle\Configuration\ConfigManager;
  5. use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\EventDispatcher\GenericEvent;
  8. use Symfony\Component\HttpFoundation\RequestStack;
  9. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  10. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  11. class EasyAdminSubscriber implements EventSubscriberInterface
  12. {
  13.     protected $authorization;
  14.     protected $requestStack;
  15.     protected $config;
  16.     /**
  17.      * EasyAdminSubscriber constructor.
  18.      */
  19.     public function __construct(AuthorizationCheckerInterface $authorizationRequestStack $requestStackConfigManager $config)
  20.     {
  21.         $this->authorization $authorization;
  22.         $this->requestStack $requestStack;
  23.         $this->config $config;
  24.     }
  25.     /**
  26.      * @return array
  27.      */
  28.     public static function getSubscribedEvents()
  29.     {
  30.         return [
  31.             EasyAdminEvents::PRE_NEW    => 'checkUserRights',
  32.             EasyAdminEvents::PRE_LIST   => 'checkUserRights',
  33.             EasyAdminEvents::PRE_EDIT   => 'checkUserRights',
  34.             EasyAdminEvents::PRE_SHOW   => 'checkUserRights',
  35.             EasyAdminEvents::PRE_DELETE => 'checkUserRights',
  36.         ];
  37.     }
  38.     /**
  39.      * show an error if user is not superadmin and tries to manage restricted stuff.
  40.      *
  41.      * @param GenericEvent $event event
  42.      *
  43.      * @throws AccessDeniedException
  44.      */
  45.     public function checkUserRights(GenericEvent $event)
  46.     {
  47.         $request $this->requestStack->getCurrentRequest()->query;
  48.         if ($this->authorization->isGranted(RoleInterface::ROLE_ADMIN)) {
  49.             return;
  50.         }
  51.         $entity $request->get('entity');
  52.         $action $request->get('action');
  53.         $backEndConfig $this->config->getBackendConfig();
  54.         foreach ($backEndConfig['entities'] as $key => $entityType) {
  55.             if (
  56.                 $entity == $key
  57.                 && isset($entityType[$action]['role'])
  58.                 && !$this->authorization->isGranted($entityType[$action]['role'])
  59.             ) {
  60.                 throw new AccessDeniedException();
  61.             }
  62.         }
  63.     }
  64. }