<?php
namespace App\EventListener;
use App\Entity\Users;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class CheckAdminPathListener implements EventSubscriberInterface
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST =>[
['onKernelRequest', -10],
],
];
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$pathInfo = $request->getPathInfo();
if (substr($pathInfo, 0, 7) === '/admin/') {
$token = $this->security->getToken();
if ($token && $token->getUser() && in_array("ROLE_ADMIN", $token->getUser()->getRoles())) {
$attributes = $token->getAttributes();
if (isset($attributes['custom_roles']) && $attributes['custom_roles'] == Users::ROLE_ADMIN_CLIENT_ACCESS) {
throw new AccessDeniedException('You do not have access to this resource.');
}
}
}
}
}