AuthenticationUtils.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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\Http\Authentication;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\RequestStack;
  13. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  14. use Symfony\Component\Security\Core\Security;
  15. /**
  16. * Extracts Security Errors from Request.
  17. *
  18. * @author Boris Vujicic <boris.vujicic@gmail.com>
  19. */
  20. class AuthenticationUtils
  21. {
  22. private $requestStack;
  23. public function __construct(RequestStack $requestStack)
  24. {
  25. $this->requestStack = $requestStack;
  26. }
  27. /**
  28. * @param bool $clearSession
  29. *
  30. * @return AuthenticationException|null
  31. */
  32. public function getLastAuthenticationError($clearSession = true)
  33. {
  34. $request = $this->getRequest();
  35. $session = $request->getSession();
  36. $authenticationException = null;
  37. if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
  38. $authenticationException = $request->attributes->get(Security::AUTHENTICATION_ERROR);
  39. } elseif (null !== $session && $session->has(Security::AUTHENTICATION_ERROR)) {
  40. $authenticationException = $session->get(Security::AUTHENTICATION_ERROR);
  41. if ($clearSession) {
  42. $session->remove(Security::AUTHENTICATION_ERROR);
  43. }
  44. }
  45. return $authenticationException;
  46. }
  47. /**
  48. * @return string
  49. */
  50. public function getLastUsername()
  51. {
  52. $request = $this->getRequest();
  53. if ($request->attributes->has(Security::LAST_USERNAME)) {
  54. return $request->attributes->get(Security::LAST_USERNAME);
  55. }
  56. $session = $request->getSession();
  57. return null === $session ? '' : $session->get(Security::LAST_USERNAME);
  58. }
  59. /**
  60. * @return Request
  61. *
  62. * @throws \LogicException
  63. */
  64. private function getRequest()
  65. {
  66. $request = $this->requestStack->getCurrentRequest();
  67. if (null === $request) {
  68. throw new \LogicException('Request should exist so it can be processed for error.');
  69. }
  70. return $request;
  71. }
  72. }