<?php
namespace AppBundle\Listener;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Topxia\Service\Common\ServiceKernel;
class PermissionKernelControllerListener
{
protected $paths;
/**
* @var ContainerInterface
*/
private $container;
/**
* @var mixed
*/
private $path;
public function __construct(ContainerInterface $container, $path)
{
$this->container = $container;
$this->path = $path;
}
public function onKernelController(ControllerEvent $event)
{
if (HttpKernelInterface::MAIN_REQUEST != $event->getRequestType()) {
return;
}
$request = $event->getRequest();
$currentUser = ServiceKernel::instance()->getCurrentUser();
if (in_array('ROLE_SUPER_ADMIN', $currentUser['roles'])) {
return;
}
$route = $this->container
->get('router')
->getMatcher()
->match($request->getPathInfo());
$permissions = empty($route['_permissions']) ? [] : $route['_permissions'];
if (empty($permissions)) {
return;
}
foreach ($permissions as $permission) {
if ($currentUser->hasPermission($permission)) {
return;
}
}
if ($this->isApiRequest($request)) {
$response = new JsonResponse([
'status' => false,
'message' => $this->container->get('translator')->trans('admin.sensitive_manage.prompt.tips'),
'permissions' => (array) $permissions,
], 403);
} elseif (!preg_match('/^\/admin/', $request->getPathInfo())) {
$response = $this->container->get('twig')->render('role/permission-error.html.twig');
} else {
$response = $this->container->get('twig')->render('admin/role/permission-error.html.twig');
}
$event->setController(function () use ($response) {
return new Response($response, 403);
});
}
private function isApiRequest(Request $request): bool
{
return in_array($request->headers->get('Accept', ''), ['application/json', 'application/vnd.edusoho.v2+json', 'application/vnd.edusoho.v3+json']);
}
}