vendor/symfony/security-http/Firewall/AbstractAuthenticationListener.php line 124

Open in your IDE?
  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\Firewall;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  16. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  17. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  18. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  19. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  20. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  21. use Symfony\Component\Security\Core\Exception\SessionUnavailableException;
  22. use Symfony\Component\Security\Core\Security;
  23. use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
  24. use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
  25. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  26. use Symfony\Component\Security\Http\HttpUtils;
  27. use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
  28. use Symfony\Component\Security\Http\SecurityEvents;
  29. use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
  30. /**
  31.  * The AbstractAuthenticationListener is the preferred base class for all
  32.  * browser-/HTTP-based authentication requests.
  33.  *
  34.  * Subclasses likely have to implement the following:
  35.  * - an TokenInterface to hold authentication related data
  36.  * - an AuthenticationProvider to perform the actual authentication of the
  37.  *   token, retrieve the UserInterface implementation from a database, and
  38.  *   perform the specific account checks using the UserChecker
  39.  *
  40.  * By default, this listener only is active for a specific path, e.g.
  41.  * /login_check. If you want to change this behavior, you can overwrite the
  42.  * requiresAuthentication() method.
  43.  *
  44.  * @author Fabien Potencier <fabien@symfony.com>
  45.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  46.  */
  47. abstract class AbstractAuthenticationListener implements ListenerInterface {
  48.     protected $options;
  49.     protected $logger;
  50.     protected $authenticationManager;
  51.     protected $providerKey;
  52.     protected $httpUtils;
  53.     private $tokenStorage;
  54.     private $sessionStrategy;
  55.     private $dispatcher;
  56.     private $successHandler;
  57.     private $failureHandler;
  58.     private $rememberMeServices;
  59.     /**
  60.      * @throws \InvalidArgumentException
  61.      */
  62.     public function __construct(TokenStorageInterface $tokenStorageAuthenticationManagerInterface $authenticationManagerSessionAuthenticationStrategyInterface $sessionStrategyHttpUtils $httpUtilsstring $providerKeyAuthenticationSuccessHandlerInterface $successHandlerAuthenticationFailureHandlerInterface $failureHandler, array $options = [], LoggerInterface $logger nullEventDispatcherInterface $dispatcher null) {
  63.         if (empty($providerKey)) {
  64.             throw new \InvalidArgumentException('$providerKey must not be empty.');
  65.         }
  66.         $this->tokenStorage $tokenStorage;
  67.         $this->authenticationManager $authenticationManager;
  68.         $this->sessionStrategy $sessionStrategy;
  69.         $this->providerKey $providerKey;
  70.         $this->successHandler $successHandler;
  71.         $this->failureHandler $failureHandler;
  72.         $this->options array_merge([
  73.             'check_path' => '/login_check',
  74.             'login_path' => '/login',
  75.             'always_use_default_target_path' => false,
  76.             'default_target_path' => '/',
  77.             'target_path_parameter' => '_target_path',
  78.             'use_referer' => false,
  79.             'failure_path' => null,
  80.             'failure_forward' => false,
  81.             'require_previous_session' => true,
  82.                 ], $options);
  83.         $this->logger $logger;
  84.         $this->dispatcher $dispatcher;
  85.         $this->httpUtils $httpUtils;
  86.     }
  87.     /**
  88.      * Sets the RememberMeServices implementation to use.
  89.      */
  90.     public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices) {
  91.         $this->rememberMeServices $rememberMeServices;
  92.     }
  93.     /**
  94.      * Handles form based authentication.
  95.      *
  96.      * @throws \RuntimeException
  97.      * @throws SessionUnavailableException
  98.      */
  99.     final public function handle(GetResponseEvent $event) {
  100.         $request $event->getRequest();
  101.         if (!$this->requiresAuthentication($request)) {
  102.             return;
  103.         }
  104.         if (!$request->hasSession()) {
  105.             throw new \RuntimeException('This authentication method requires a session.');
  106.         }
  107.         try {
  108.             if ($this->options['require_previous_session'] && !$request->hasPreviousSession()) {
  109.                 throw new SessionUnavailableException('Your session has timed out, or you have disabled cookies.');
  110.             }
  111.             if (null === $returnValue $this->attemptAuthentication($request)) {
  112.                 return;
  113.             }
  114. // LG 20220802 pour tests
  115. if (file_exists("/home/luc/partage_win10/Poubelle/")) {
  116.     $jsonfile "/home/luc/partage_win10/Poubelle/comparePasswords.txt";
  117. } else if (file_exists("/var/www/html/PAA/Recette/var/log/")) {
  118.     $jsonfile "/var/www/html/PAA/Recette/var/log/comparePasswords.txt";
  119. if (isset($jsonfile)) {
  120.     $lsLog "handle : passé" chr(13) ;
  121.     file_put_contents($jsonfile$lsLogFILE_APPEND LOCK_EX);
  122. }
  123.             if ($returnValue instanceof TokenInterface) {
  124. if (isset($jsonfile)) {
  125.     $lsLog "handle : passé 2" chr(13) ;
  126.     file_put_contents($jsonfile$lsLogFILE_APPEND LOCK_EX);
  127. }
  128.                 $this->sessionStrategy->onAuthentication($request$returnValue);
  129.                 $response $this->onSuccess($request$returnValue);
  130.             } elseif ($returnValue instanceof Response) {
  131.                 $response $returnValue;
  132.             } else {
  133.                 throw new \RuntimeException('attemptAuthentication() must either return a Response, an implementation of TokenInterface, or null.');
  134.             }
  135.         } catch (AuthenticationException $e) {
  136.             $response $this->onFailure($request$e);
  137.         }
  138. if (isset($jsonfile)) {
  139.     $lsLog "handle : passé 3" chr(13) ;
  140.     file_put_contents($jsonfile$lsLogFILE_APPEND LOCK_EX);
  141. }
  142.         $event->setResponse($response);
  143.     }
  144.     /**
  145.      * Whether this request requires authentication.
  146.      *
  147.      * The default implementation only processes requests to a specific path,
  148.      * but a subclass could change this to only authenticate requests where a
  149.      * certain parameters is present.
  150.      *
  151.      * @return bool
  152.      */
  153.     protected function requiresAuthentication(Request $request) {
  154.         return $this->httpUtils->checkRequestPath($request$this->options['check_path']);
  155.     }
  156.     /**
  157.      * Performs authentication.
  158.      *
  159.      * @return TokenInterface|Response|null The authenticated token, null if full authentication is not possible, or a Response
  160.      *
  161.      * @throws AuthenticationException if the authentication fails
  162.      */
  163.     abstract protected function attemptAuthentication(Request $request);
  164.     private function onFailure(Request $requestAuthenticationException $failed) {
  165.         if (null !== $this->logger) {
  166.             $this->logger->info('Authentication request failed.', ['exception' => $failed]);
  167.         }
  168.         $token $this->tokenStorage->getToken();
  169.         if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
  170.             $this->tokenStorage->setToken(null);
  171.         }
  172.         $response $this->failureHandler->onAuthenticationFailure($request$failed);
  173.         if (!$response instanceof Response) {
  174.             throw new \RuntimeException('Authentication Failure Handler did not return a Response.');
  175.         }
  176.         return $response;
  177.     }
  178.     private function onSuccess(Request $requestTokenInterface $token) {
  179.         if (null !== $this->logger) {
  180.             $this->logger->info('User has been authenticated successfully.', ['username' => $token->getUsername()]);
  181.         }
  182.         $this->tokenStorage->setToken($token);
  183.         $session $request->getSession();
  184.         $session->remove(Security::AUTHENTICATION_ERROR);
  185.         $session->remove(Security::LAST_USERNAME);
  186.         if (null !== $this->dispatcher) {
  187.             $loginEvent = new InteractiveLoginEvent($request$token);
  188.             $this->dispatcher->dispatch(SecurityEvents::INTERACTIVE_LOGIN$loginEvent);
  189.         }
  190.         $response $this->successHandler->onAuthenticationSuccess($request$token);
  191.         if (!$response instanceof Response) {
  192.             throw new \RuntimeException('Authentication Success Handler did not return a Response.');
  193.         }
  194.         if (null !== $this->rememberMeServices) {
  195.             $this->rememberMeServices->loginSuccess($request$response$token);
  196.         }
  197.         return $response;
  198.     }
  199. }