Security.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Security\Core;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  13. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  14. use Symfony\Component\Security\Core\User\UserInterface;
  15. /**
  16. * Helper class for commonly-needed security tasks.
  17. *
  18. * @final
  19. */
  20. class Security implements AuthorizationCheckerInterface
  21. {
  22. public const ACCESS_DENIED_ERROR = '_security.403_error';
  23. public const AUTHENTICATION_ERROR = '_security.last_error';
  24. public const LAST_USERNAME = '_security.last_username';
  25. public const MAX_USERNAME_LENGTH = 4096;
  26. private $container;
  27. public function __construct(ContainerInterface $container)
  28. {
  29. $this->container = $container;
  30. }
  31. public function getUser(): ?UserInterface
  32. {
  33. if (!$token = $this->getToken()) {
  34. return null;
  35. }
  36. $user = $token->getUser();
  37. if (!\is_object($user)) {
  38. return null;
  39. }
  40. if (!$user instanceof UserInterface) {
  41. return null;
  42. }
  43. return $user;
  44. }
  45. /**
  46. * Checks if the attributes are granted against the current authentication token and optionally supplied subject.
  47. *
  48. * @param mixed $attributes
  49. * @param mixed $subject
  50. */
  51. public function isGranted($attributes, $subject = null): bool
  52. {
  53. return $this->container->get('security.authorization_checker')
  54. ->isGranted($attributes, $subject);
  55. }
  56. public function getToken(): ?TokenInterface
  57. {
  58. return $this->container->get('security.token_storage')->getToken();
  59. }
  60. }