src/Twig/Runtime/AclRuntime.php line 101

Open in your IDE?
  1. <?php
  2. /** @noinspection ALL */
  3. namespace App\Twig\Runtime;
  4. use App\Constants\ACL;
  5. use App\Entity\Parameter;
  6. use App\Entity\SliderItem;
  7. use App\Entity\User;
  8. use App\Model\Product;
  9. use App\Services\Back\ParameterService;
  10. use App\Services\Common\AclServiceV2;
  11. use App\Services\UtilsService;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Psr\Cache\InvalidArgumentException;
  14. use Symfony\Component\HttpFoundation\RequestStack;
  15. use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
  16. use Symfony\Component\Security\Core\Security;
  17. use Symfony\Component\Security\Core\User\UserInterface;
  18. use Twig\Extension\RuntimeExtensionInterface;
  19. use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
  20. /**
  21. * Rassemble toute les fonction disponible dans twig qui touchent aux ACL et à l'affichage des données via les règles acl ou les systèmes paralèlles (roles, jobs sur les entités comme pour les slider ou les documents)
  22. */
  23. class AclRuntime implements RuntimeExtensionInterface
  24. {
  25. private AclServiceV2 $aclService;
  26. private RequestStack $requestStack;
  27. private ParameterService $parameterService;
  28. private Security $security;
  29. private RoleHierarchyInterface $roleHierarchy;
  30. private EntityManagerInterface $em;
  31. private array $userIsGrantedCache = [];
  32. private array $componentVisibilityCache = [];
  33. private array $displayConfigCache = [];
  34. private ?string $currentRouteCache = null;
  35. private mixed $currentRouteParamsCache = null;
  36. private bool $currentRequestResolved = false;
  37. private User|UserInterface|null $currentUserCache = null;
  38. private bool $currentUserResolved = false;
  39. private UtilsService $utilsService;
  40. public function __construct(
  41. AclServiceV2 $aclService,
  42. RequestStack $requestStack,
  43. ParameterService $parameterService,
  44. Security $security,
  45. RoleHierarchyInterface $roleHierarchy,
  46. EntityManagerInterface $em,
  47. UtilsService $utilsService
  48. ) {
  49. $this->aclService = $aclService;
  50. $this->requestStack = $requestStack;
  51. $this->parameterService = $parameterService;
  52. $this->security = $security;
  53. $this->roleHierarchy = $roleHierarchy;
  54. $this->em = $em;
  55. $this->utilsService = $utilsService;
  56. }
  57. /**
  58. * Permet de savoir si le user a le droit d'accéder à la route
  59. * @param User|null $user
  60. * @param string $route
  61. * @param array $params
  62. * @param string $env
  63. * @return bool
  64. */
  65. public function userIsGrantedRoute(
  66. ?User $user,
  67. string $route,
  68. array $params = [],
  69. string $env = ACL::FRONT_ENV,
  70. bool $debug = false
  71. ) {
  72. $config = [
  73. 'route' => $route,
  74. 'params' => $params,
  75. 'component' => ACL::ACL_NO_COMPONENT,
  76. 'slug' => ACL::ACL_NO_SLUG,
  77. 'action' => ACL::READ,
  78. 'env' => $env,
  79. ];
  80. return $this->aclService->userIsGranted($user, $config, $debug);
  81. }
  82. /**
  83. * Permet de savoir si un user peut faire une action en fonction de son rôle ou de son job
  84. *
  85. * @param User|null $user
  86. * @param string $slug
  87. * @param string $action
  88. * @param string $env
  89. *
  90. * @return bool
  91. *
  92. * @throws InvalidArgumentException
  93. */
  94. public function userIsGranted(
  95. ?User $user,
  96. string $component,
  97. string $slug = ACL::ACL_NO_SLUG,
  98. string $action = ACL::READ,
  99. string $env = ACL::FRONT_ENV,
  100. string $route = null,
  101. string $params = null,
  102. bool $debug = false
  103. ): bool {
  104. [$resolvedRoute, $resolvedParams] = $this->getCurrentRouteContext();
  105. $currentRoute = $route ?? $resolvedRoute;
  106. $currentParams = $params ?? $resolvedParams;
  107. if ($currentRoute === null) {
  108. return $this->checkWhenRouteIsNull();
  109. }
  110. $config = [
  111. 'route' => $currentRoute,
  112. 'params' => $this->aclService->getRouteParamsForAcl($currentRoute, $currentParams),
  113. 'component' => $component,
  114. 'slug' => $slug,
  115. 'action' => $action,
  116. 'env' => $env,
  117. ];
  118. $cacheKey = implode('|', [
  119. $user instanceof User ? $user->getId() : 'anonymous',
  120. $currentRoute,
  121. $config['params'],
  122. $component,
  123. $slug,
  124. $action,
  125. $env,
  126. ]);
  127. if (array_key_exists($cacheKey, $this->userIsGrantedCache)) {
  128. return $this->userIsGrantedCache[$cacheKey];
  129. }
  130. return $this->userIsGrantedCache[$cacheKey] = $this->aclService->userIsGranted($user, $config, $debug);
  131. }
  132. /**
  133. * Logique pour éviter des erreurs 500 si jamais une route est évaluée à NULL
  134. * Si on est dans le cas d'une exception on autorise la visualition
  135. * @return true
  136. * @throws \Exception
  137. */
  138. private function checkWhenRouteIsNull()
  139. {
  140. $request = $this->requestStack->getCurrentRequest();
  141. $exeption = $request->attributes->get('exception');
  142. if ($exeption !== null) {
  143. return true;
  144. }
  145. throw new \Exception('Une erreur est survenue, la route ne peut pas être null et ne pas être une exception');
  146. }
  147. /**
  148. * Permet de savoir si le current user à le droit de voir le catalogue par son slug
  149. * @param $catalogue
  150. * @return bool
  151. * @throws InvalidArgumentException
  152. */
  153. public function userIsGrantedCatalogue($catalogue)
  154. {
  155. $currentUser = $this->security->getUser();
  156. return $this->aclService->userIsGrantedCatalogue($currentUser, $catalogue);
  157. }
  158. /**
  159. * Permet de savoir si le current user à le droit de voir le produit
  160. * @param Product $product
  161. *
  162. * @return bool
  163. * @throws \JsonException
  164. */
  165. public function userIsGrantedProduct(Product $product)
  166. {
  167. $currentUser = $this->security->getUser();
  168. return $this->aclService->userIsGrantedProduct($currentUser, $product);
  169. }
  170. /**
  171. * Retourne le slug du premier catalogue qui contient le produit et qui est accèssible au user courant
  172. * @param Product $product
  173. *
  174. * @return mixed|null
  175. * @throws \JsonException
  176. */
  177. public function getUserFirstGrantedCatalogSlugForProduct(Product $product)
  178. {
  179. $currentUser = $this->security->getUser();
  180. return $this->aclService->getUserFirstGrantedCatalogSlugForProduct($currentUser, $product);
  181. }
  182. /**
  183. * Défini si l'utilisateur à le droit de voir le document
  184. *
  185. * @param User|null $user
  186. * @param Parameter $document
  187. *
  188. * @return bool
  189. *
  190. * @throws \JsonException
  191. */
  192. public function canDisplayDocument(?User $user, Parameter $document): bool
  193. {
  194. return $this->aclService->userIsGrantedOnDocument($user, $document);
  195. }
  196. public function filterVisibleDocuments(
  197. ?User $user,
  198. array $documents,
  199. bool $onlyPublicOnSecurityRoute = false
  200. ): array {
  201. [$currentRoute] = $this->getCurrentRouteContext();
  202. $isSecurityRoute = $currentRoute !== null && in_array($currentRoute, ACL::ACL_SECURITY_ROUTES, true);
  203. return array_values(
  204. array_filter(
  205. $documents,
  206. function (Parameter $document) use ($user, $onlyPublicOnSecurityRoute, $isSecurityRoute) {
  207. if (!$this->canDisplayDocument($user, $document)) {
  208. return false;
  209. }
  210. if ($onlyPublicOnSecurityRoute && $isSecurityRoute && !$document->isPublic()) {
  211. return false;
  212. }
  213. return true;
  214. }
  215. )
  216. );
  217. }
  218. /**
  219. * Lors des documents personnalisé, permet de savoit si le user peut voir le document
  220. *
  221. * @param User|null $user
  222. * @param $id
  223. *
  224. * @return bool
  225. *
  226. * @throws \JsonException
  227. */
  228. public function isDocumentSelectedForUser(?User $user, $id): bool
  229. {
  230. return $this->parameterService->isDocumentSelectedForUser($user, $id);
  231. }
  232. /**
  233. * Permet de savoir si on component est visible par le user courant
  234. *
  235. * Ne doit être utilisé que pour l'affichage twig des components en front
  236. *
  237. * @param array|null $componentOptions
  238. * @param bool $debug
  239. * @return bool
  240. * @throws InvalidArgumentException
  241. */
  242. public function canDisplayComponentByAcl(?array $componentOptions, bool $debug = false)
  243. {
  244. if ($componentOptions === null || $componentOptions === []) {
  245. return true;
  246. }
  247. [$currentRoute] = $this->getCurrentRouteContext();
  248. $currentUser = $this->getCurrentUser();
  249. $item = $componentOptions['item'] ?? $componentOptions;
  250. $display = $item['display'] ?? [];
  251. $univers = $item['univers'] ?? [];
  252. $componentAcl = $item['data']['data-component-acl'] ?? ACL::ACL_NO_COMPONENT;
  253. $cacheKey = implode('|', [
  254. $currentRoute ?? 'no-route',
  255. $currentUser instanceof User ? $currentUser->getId() : 'anonymous',
  256. $componentAcl,
  257. (int)($item['enabled'] ?? true),
  258. md5(json_encode($display)),
  259. md5(json_encode($univers)),
  260. ]);
  261. if (array_key_exists($cacheKey, $this->componentVisibilityCache)) {
  262. return $this->componentVisibilityCache[$cacheKey];
  263. }
  264. // Le component est actif sur la page ?
  265. $canDisplay = (bool)$item['enabled'] ?? true;
  266. if (!$canDisplay) {
  267. return $this->componentVisibilityCache[$cacheKey] = false;
  268. }
  269. // on regarde s'il peut s'afficher sur la page via la clef display
  270. $canDisplay = $this->canDisplayOnPageByConfig($display, $debug);
  271. if (!$canDisplay) {
  272. return $this->componentVisibilityCache[$cacheKey] = false;
  273. }
  274. // on recherche l'acl si on peut récupérer son slug data-component-acl
  275. if (isset($item['data']['data-component-acl'])) {
  276. $canDisplay = $this->userIsGranted($currentUser instanceof User ? $currentUser : null, $componentAcl);
  277. }
  278. if (!$canDisplay) {
  279. return $this->componentVisibilityCache[$cacheKey] = false;
  280. }
  281. // on regarde s'il y a des univers... on verifie le currentUser car le component peut être utilisé en partie security
  282. if ($currentUser instanceof User && $univers !== []) {
  283. if ($canDisplay && !$currentUser->isDeveloper() && !$currentUser->isSuperAdmin()) {
  284. $canDisplay = $this->aclService->canDisplayByUniverses($currentUser, $univers);
  285. }
  286. }
  287. return $this->componentVisibilityCache[$cacheKey] = $canDisplay;
  288. }
  289. /**
  290. * Défini si un component s'affiche via la clef display
  291. *
  292. * Elle contient 2 enfants:
  293. * enabled_on : array (tableau de route)|null
  294. * disabled_on : array (tableau de route)|null
  295. * Si disabled_on est a autre chose que null, alors c'est lui qui prend l'ascendant
  296. * Afficher partout => enabled_on: null + disabled_on: [] ou null
  297. *
  298. * @param array $display
  299. *
  300. * @return bool
  301. */
  302. private function canDisplayOnPageByConfig(array $display, bool $debug = false)
  303. {
  304. [$currentRoute] = $this->getCurrentRouteContext();
  305. if ($currentRoute === null) {
  306. return $this->checkWhenRouteIsNull();
  307. }
  308. $cacheKey = md5(json_encode([$currentRoute, $display]));
  309. if (array_key_exists($cacheKey, $this->displayConfigCache)) {
  310. return $this->displayConfigCache[$cacheKey];
  311. }
  312. $canDisplay = true; // par défaut on affiche
  313. // On prend la config du disabled_on si elle n'est pas nulle
  314. $displayByDisabled = false;
  315. if (isset($display['disabled_on']) && $display['disabled_on'] !== null) {
  316. $displayByDisabled = true;
  317. }
  318. // On prend la config enbaled_on
  319. if (isset($display['enabled_on']) && !$displayByDisabled) {
  320. $arrayRoute = $display['enabled_on'];
  321. if (gettype($display['enabled_on']) === "string") {
  322. $arrayRoute = json_decode($display['enabled_on'], true);
  323. }
  324. switch (true) {
  325. // tableau vide, ce n'est pas visible
  326. case $arrayRoute === []:
  327. $canDisplay = false;
  328. break;
  329. // NULL ou valeur qui n'est pas un tableau, on considère que c'est visible
  330. // ainsi si enabled_on et disabled_on sont NULL, on affiche
  331. case $arrayRoute === null:
  332. case !is_array($arrayRoute):
  333. $canDisplay = true;
  334. break;
  335. // on regarde si la route actuelle est dans le tableau pour l'afficher
  336. default:
  337. $canDisplay = in_array($currentRoute, $arrayRoute, true);
  338. break;
  339. }
  340. }
  341. // on prend la config disabled_on
  342. if (isset($display['disabled_on']) && $displayByDisabled) {
  343. $arrayRoute = $display['disabled_on'];
  344. if (gettype($display['disabled_on']) === "string") {
  345. $arrayRoute = json_decode($display['disabled_on'], true);
  346. }
  347. switch (true) {
  348. // tableau vide, c'est visible partout
  349. case $arrayRoute === []:
  350. $canDisplay = true;
  351. break;
  352. // NULL ou valeur qui n'est pas un tableau, on refuse l'affichage
  353. // Normalement on ne tombe pas dans cette configuration puisque $displayByDisabled est FALSE
  354. case $arrayRoute === null:
  355. case !is_array($arrayRoute):
  356. $canDisplay = false;
  357. break;
  358. // on regarde si la route actuelle est dans le tableau pour refuser l'affichage
  359. default:
  360. $canDisplay = !in_array($currentRoute, $arrayRoute, true);
  361. break;
  362. }
  363. }
  364. return $this->displayConfigCache[$cacheKey] = $canDisplay;
  365. }
  366. private function getCurrentRouteContext(): array
  367. {
  368. if ($this->currentRequestResolved) {
  369. return [$this->currentRouteCache, $this->currentRouteParamsCache];
  370. }
  371. $request = $this->requestStack->getCurrentRequest();
  372. $this->currentRouteCache = $request?->get('_route');
  373. $this->currentRouteParamsCache = $request?->get('_route_params');
  374. $this->currentRequestResolved = true;
  375. return [$this->currentRouteCache, $this->currentRouteParamsCache];
  376. }
  377. private function getCurrentUser(): User|UserInterface|null
  378. {
  379. if ($this->currentUserResolved) {
  380. return $this->currentUserCache;
  381. }
  382. $this->currentUserCache = $this->security->getUser();
  383. $this->currentUserResolved = true;
  384. return $this->currentUserCache;
  385. }
  386. /**
  387. * Permet de savoir si le user peut voir le slider
  388. *
  389. * Les acl du slider sont intégré à l'édition de l'entité
  390. *
  391. * @param User $user
  392. * @param SliderItem $item
  393. *
  394. * @return bool
  395. */
  396. public function canDisplaySliderItem(?User $user, SliderItem $item): bool
  397. {
  398. if (!$user) {
  399. return false;
  400. }
  401. $jobs = $item->getDisplayJob() ?? [];
  402. $universes = $item->getDisplayUniverses();
  403. // Le superadmin et dev doivent pouvoir tout voir...
  404. if ($user->isDeveloper() || $user->isSuperAdmin()) {
  405. return true;
  406. }
  407. // Par défaut, tout s'affiche
  408. $canDisplay = true;
  409. // SI config par job on regarde si ça match
  410. if (!$this->utilsService->array_jobs_intersect($user->getJobs(), $jobs)) {
  411. $canDisplay = false;
  412. }
  413. // Si config par univers on regarde si ça match
  414. if ($universes !== null) {
  415. foreach ($user->getUniverses() as $userUnivers) {
  416. if (in_array($userUnivers->getSlug(), $universes, true)) {
  417. $canDisplay = true;
  418. break;
  419. }
  420. $canDisplay = false;
  421. }
  422. }
  423. return $canDisplay;
  424. }
  425. /**
  426. * Normalise la transformation de l'array qui contient les params d'une route pour la transformer en string
  427. * @param array $params
  428. *
  429. * @return false|string
  430. * @throws \JsonException
  431. */
  432. public function formatParamsToString(array $params)
  433. {
  434. return $this->aclService->formatArrayParamsToString($params);
  435. }
  436. /**
  437. * Retourne un tableau avec la liste de roles et les jobs relatif à ces roles
  438. *
  439. * @return array[]
  440. */
  441. public function getDefaultRolesAndJobs()
  442. {
  443. return $this->aclService->getDefaultRoleAndJob();
  444. }
  445. /**
  446. * @return UserInterface|null
  447. */
  448. public function getOriginalUser(): ?UserInterface
  449. {
  450. $token = $this->security->getToken();
  451. if ($token instanceof SwitchUserToken) {
  452. $user = $token->getOriginalToken()->getUser();
  453. $user = $this->em->getRepository(User::class)->findOneBy(['email' => $user->getEmail()]);
  454. return $user;
  455. }
  456. return $this->security->getUser();
  457. }
  458. /**
  459. * @param User $user
  460. * @param string $role
  461. *
  462. * @return bool
  463. */
  464. public function hasRole(User $user, string $role): bool
  465. {
  466. $reachableRoles = $this->roleHierarchy->getReachableRoleNames($user->getRoles());
  467. return in_array($role, $reachableRoles);
  468. }
  469. }