|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Component\Security\Http\Authentication; |
| 13 | + |
| 14 | +use Symfony\Component\HttpFoundation\RequestStack; |
| 15 | +use Symfony\Component\Security\Core\Exception\AuthenticationException; |
| 16 | +use Symfony\Component\Security\Core\SecurityContextInterface; |
| 17 | +use Symfony\Component\HttpFoundation\Request; |
| 18 | + |
| 19 | +/** |
| 20 | + * Extracts Security Errors from Request |
| 21 | + * |
| 22 | + * @author Boris Vujicic <boris.vujicic@gmail.com> |
| 23 | + */ |
| 24 | +class AuthenticationUtils |
| 25 | +{ |
| 26 | + /** |
| 27 | + * @var RequestStack |
| 28 | + */ |
| 29 | + private $requestStack; |
| 30 | + |
| 31 | + /** |
| 32 | + * @param RequestStack $requestStack |
| 33 | + */ |
| 34 | + public function __construct(RequestStack $requestStack) |
| 35 | + { |
| 36 | + $this->requestStack = $requestStack; |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * @param bool $clearSession |
| 41 | + * @return null|AuthenticationException |
| 42 | + */ |
| 43 | + public function getLastAuthenticationError($clearSession = true) |
| 44 | + { |
| 45 | + $request = $this->getRequest(); |
| 46 | + $session = $request->getSession(); |
| 47 | + $authenticationException = null; |
| 48 | + |
| 49 | + if ($request->attributes->has(SecurityContextInterface::AUTHENTICATION_ERROR)) { |
| 50 | + $authenticationException = $request->attributes->get(SecurityContextInterface::AUTHENTICATION_ERROR); |
| 51 | + } elseif ($session !== null && $session->has(SecurityContextInterface::AUTHENTICATION_ERROR)) { |
| 52 | + $authenticationException = $session->get(SecurityContextInterface::AUTHENTICATION_ERROR); |
| 53 | + |
| 54 | + if ($clearSession) { |
| 55 | + $session->remove(SecurityContextInterface::AUTHENTICATION_ERROR); |
| 56 | + } |
| 57 | + |
| 58 | + } |
| 59 | + |
| 60 | + return $authenticationException; |
| 61 | + } |
| 62 | + |
| 63 | + /** |
| 64 | + * @return string |
| 65 | + */ |
| 66 | + public function getLastUsername() |
| 67 | + { |
| 68 | + $session = $this->getRequest()->getSession(); |
| 69 | + |
| 70 | + return null === $session ? '' : $session->get(SecurityContextInterface::LAST_USERNAME); |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * @return Request |
| 75 | + * @throws \LogicException |
| 76 | + */ |
| 77 | + private function getRequest() |
| 78 | + { |
| 79 | + $request = $this->requestStack->getCurrentRequest(); |
| 80 | + |
| 81 | + if (null === $request) { |
| 82 | + throw new \LogicException('Request should exist so it can be processed for error.'); |
| 83 | + } |
| 84 | + |
| 85 | + return $request; |
| 86 | + } |
| 87 | +} |
0 commit comments