vendor/symfony/security-http/Authentication/AuthenticationUtils.php line 43

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