<?php
namespace App\Security;
use App\Entity\User;
use App\Utils\UserPermissionsHelper;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\KernelEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class UserPermissionsListener
{
/**
* @var SessionInterface
*/
private $session;
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var UserPermissionsHelper
*/
private $userPermissionsHelper;
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
/**
* @var RouterInterface
*/
private $router;
private $userPermissionsRoutes;
public function __construct(
SessionInterface $session,
EntityManagerInterface $em,
UserPermissionsHelper $userPermissionsHelper,
TokenStorageInterface $tokenStorage,
RouterInterface $router,
$userPermissionsRoutes
) {
$this->session = $session;
$this->em = $em;
$this->userPermissionsHelper = $userPermissionsHelper;
$this->tokenStorage = $tokenStorage;
$this->router = $router;
$this->userPermissionsRoutes = $userPermissionsRoutes;
}
public function preExecute(KernelEvent $event)
{
$currentRoute = $event->getRequest()->get('_route');
$protectedRoutes = $this->userPermissionsRoutes;
$permissionNeeded = null;
foreach ($protectedRoutes as $protectedRoute) {
foreach ($protectedRoute as $key => $v) {
if(in_array($currentRoute, $v['urls'])) {
$permissionNeeded = $key;
}
}
}
if (empty($permissionNeeded)) {
return true;
}
/** @var User $user */
$vbxUser = $this->tokenStorage->getToken()->getUser()->getId();
$hasPermission = $this->userPermissionsHelper->userHasPermission($vbxUser, $permissionNeeded);
if (!$hasPermission) {
switch ($event->getRequest()->getRealMethod()) {
case "GET":
$this->session->getFlashBag()->add('danger', "Oops! You don't have the User permissions needed to access this. Please contact your manager to update.");
$event->setController(function () {
return new RedirectResponse($this->router->generate('app_rapoarte_management'));
});
break;
// case "POST":
// $event->setController(function () {
// return new JsonResponse(["error" => true, "message" => "Oops! You are not allowed to perform this action. Please contact your manager to update"]);
// });
// break;
// default:
// $event->setController(function () {
// throw new UnauthorizedHttpException("You are not allowed to access this section.");
// });
// break;
}
}
return true;
}
}