<?php
namespace App\EventSubscriber\EasyAdmin;
use App\Security\RoleInterface;
use EasyCorp\Bundle\EasyAdminBundle\Configuration\ConfigManager;
use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class EasyAdminSubscriber implements EventSubscriberInterface
{
protected $authorization;
protected $requestStack;
protected $config;
/**
* EasyAdminSubscriber constructor.
*/
public function __construct(AuthorizationCheckerInterface $authorization, RequestStack $requestStack, ConfigManager $config)
{
$this->authorization = $authorization;
$this->requestStack = $requestStack;
$this->config = $config;
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
EasyAdminEvents::PRE_NEW => 'checkUserRights',
EasyAdminEvents::PRE_LIST => 'checkUserRights',
EasyAdminEvents::PRE_EDIT => 'checkUserRights',
EasyAdminEvents::PRE_SHOW => 'checkUserRights',
EasyAdminEvents::PRE_DELETE => 'checkUserRights',
];
}
/**
* show an error if user is not superadmin and tries to manage restricted stuff.
*
* @param GenericEvent $event event
*
* @throws AccessDeniedException
*/
public function checkUserRights(GenericEvent $event)
{
$request = $this->requestStack->getCurrentRequest()->query;
if ($this->authorization->isGranted(RoleInterface::ROLE_ADMIN)) {
return;
}
$entity = $request->get('entity');
$action = $request->get('action');
$backEndConfig = $this->config->getBackendConfig();
foreach ($backEndConfig['entities'] as $key => $entityType) {
if (
$entity == $key
&& isset($entityType[$action]['role'])
&& !$this->authorization->isGranted($entityType[$action]['role'])
) {
throw new AccessDeniedException();
}
}
}
}