FlexAuthorizeTrait.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @package Grav\Framework\Flex
  5. *
  6. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  7. * @license MIT License; see LICENSE file for details.
  8. */
  9. namespace Grav\Framework\Flex\Traits;
  10. use Grav\Common\Grav;
  11. use Grav\Common\User\Interfaces\UserInterface;
  12. use Grav\Framework\Flex\FlexDirectory;
  13. use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
  14. /**
  15. * Implements basic ACL
  16. */
  17. trait FlexAuthorizeTrait
  18. {
  19. private $_authorize = '%s.flex-object.%s';
  20. public function isAuthorized(string $action, string $scope = null, UserInterface $user = null) : bool
  21. {
  22. if (null === $user) {
  23. /** @var UserInterface $user */
  24. $user = Grav::instance()['user'] ?? null;
  25. }
  26. return $user && ($this->isAuthorizedAction($user, $action, $scope) || $this->isAuthorizedSuperAdmin($user));
  27. }
  28. protected function isAuthorizedSuperAdmin(UserInterface $user): bool
  29. {
  30. return $user->authorize('admin.super');
  31. }
  32. protected function isAuthorizedAction(UserInterface $user, string $action, string $scope = null) : bool
  33. {
  34. $scope = $scope ?? isset(Grav::instance()['admin']) ? 'admin' : 'site';
  35. if ($action === 'save' && $this instanceof FlexObjectInterface) {
  36. $action = $this->exists() ? 'update' : 'create';
  37. }
  38. $directory = $this instanceof FlexDirectory ? $this : $this->getFlexDirectory();
  39. $config = $directory->getConfig();
  40. $allowed = $config->get("{$scope}.actions.{$action}") ?? $config->get("actions.{$action}") ?? true;
  41. return $allowed && $user->authorize(sprintf($this->_authorize, $scope, $action));
  42. }
  43. protected function setAuthorizeRule(string $authorize) : void
  44. {
  45. $this->_authorize = $authorize;
  46. }
  47. }