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

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\LegacyEventDispatcherProxy;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\Event\RequestEvent;
  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. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  31. use Webkul\UVDesk\CoreFrameworkBundle\Entity\User;
  32. use Webkul\UVDesk\CoreFrameworkBundle\Entity\UserInstance;
  33. use Webkul\UVDesk\CoreFrameworkBundle\Entity\SupportGroup;
  34. use Mysqli;
  35. /**
  36.  * The AbstractAuthenticationListener is the preferred base class for all
  37.  * browser-/HTTP-based authentication requests.
  38.  *
  39.  * Subclasses likely have to implement the following:
  40.  * - an TokenInterface to hold authentication related data
  41.  * - an AuthenticationProvider to perform the actual authentication of the
  42.  *   token, retrieve the UserInterface implementation from a database, and
  43.  *   perform the specific account checks using the UserChecker
  44.  *
  45.  * By default, this listener only is active for a specific path, e.g.
  46.  * /login_check. If you want to change this behavior, you can overwrite the
  47.  * requiresAuthentication() method.
  48.  *
  49.  * @author Fabien Potencier <fabien@symfony.com>
  50.  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  51.  */
  52. abstract class AbstractAuthenticationListener implements ListenerInterface
  53. {
  54.     use LegacyListenerTrait;
  55.     protected $options;
  56.     protected $logger;
  57.     protected $authenticationManager;
  58.     protected $providerKey;
  59.     protected $httpUtils;
  60.     private $tokenStorage;
  61.     private $sessionStrategy;
  62.     private $dispatcher;
  63.     private $successHandler;
  64.     private $failureHandler;
  65.     private $rememberMeServices;
  66.     /**
  67.      * @throws \InvalidArgumentException
  68.      */
  69.     public function __construct(TokenStorageInterface $tokenStorageAuthenticationManagerInterface $authenticationManagerSessionAuthenticationStrategyInterface $sessionStrategyHttpUtils $httpUtilsstring $providerKeyAuthenticationSuccessHandlerInterface $successHandlerAuthenticationFailureHandlerInterface $failureHandler, array $options = [], LoggerInterface $logger nullEventDispatcherInterface $dispatcher null)
  70.     {
  71.         if (empty($providerKey)) {
  72.             throw new \InvalidArgumentException('$providerKey must not be empty.');
  73.         }
  74.         $this->tokenStorage $tokenStorage;
  75.         $this->authenticationManager $authenticationManager;
  76.         $this->sessionStrategy $sessionStrategy;
  77.         $this->providerKey $providerKey;
  78.         $this->successHandler $successHandler;
  79.         $this->failureHandler $failureHandler;
  80.         $this->options array_merge([
  81.             'check_path' => '/login_check',
  82.             'login_path' => '/login',
  83.             'always_use_default_target_path' => false,
  84.             'default_target_path' => '/',
  85.             'target_path_parameter' => '_target_path',
  86.             'use_referer' => false,
  87.             'failure_path' => null,
  88.             'failure_forward' => false,
  89.             'require_previous_session' => true,
  90.         ], $options);
  91.         $this->logger $logger;
  92.         $this->dispatcher LegacyEventDispatcherProxy::decorate($dispatcher);
  93.         $this->httpUtils $httpUtils;
  94.     }
  95.     /**
  96.      * Sets the RememberMeServices implementation to use.
  97.      */
  98.     public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices)
  99.     {
  100.         $this->rememberMeServices $rememberMeServices;
  101.     }
  102.     public function conectionTKT(){
  103.         $mysqli = new mysqli("database-plesk.cfcc6wi065dc.us-east-1.rds.amazonaws.com""ticketera""Qn0is837Zo102""admin_tkt2");
  104.         //$mysqli = new mysqli("localhost", "root", "root", "ticketerasg");
  105.         /* comprobar la conexión */
  106.         if ($mysqli->connect_errno) {
  107.             printf("Falló la conexión: %s\n"$mysqli->connect_error);
  108.             exit();
  109.         }
  110.         return $mysqli;
  111.     }
  112.     
  113.     /**
  114.      * Handles form based authentication.
  115.      *
  116.      * @throws \RuntimeException
  117.      * @throws SessionUnavailableException
  118.      */
  119.     public function __invoke(RequestEvent $event)
  120.     {
  121.         $request $event->getRequest();
  122.         if (!$this->requiresAuthentication($request)) {
  123.             return;
  124.         }
  125.         if (!$request->hasSession()) {
  126.             throw new \RuntimeException('This authentication method requires a session.');
  127.         }
  128.         try {
  129.             if ($this->options['require_previous_session'] && !$request->hasPreviousSession()) {
  130.                 throw new SessionUnavailableException('Your session has timed out, or you have disabled cookies.');
  131.             }
  132. /* 
  133.             if (null === $returnValue = $this->attemptAuthentication($request)) {
  134.                 return;
  135.             } */
  136.             
  137.              $email $request->request->get('_username');
  138.             $password $request->request->get('_password');
  139.   
  140.             if ($this->isHashAuthentication($password)) {
  141.                 
  142.                 $mysqli $this->conectionTKT();
  143.         
  144.                 // Preparar la consulta para obtener el usuario por email
  145.                 $consulta $mysqli->prepare("SELECT * FROM uv_user WHERE email = ?");
  146.                 $consulta->bind_param("s"$email);  // "s" indica que estamos pasando un string (el email)
  147.                 $consulta->execute();
  148.                 $resultado $consulta->get_result();
  149.                
  150.                             
  151.                             if ($resultado->num_rows 0) {
  152.                                 // Obtener el primer usuario
  153.                                 $userData $resultado->fetch_assoc();  // Obtiene los datos del usuario en un array asociativo
  154.                         
  155.                                 if($password === $userData['password']){
  156.                     
  157.                                 // Crear una nueva instancia del objeto User
  158.                                 $user = new User();
  159.                                 // Asignar los valores básicos obligatorios
  160.                                 $user->setEmail($userData['email']);  // Establecer el correo del usuario
  161.                                 $user->setRoles(['ROLE_CUSTOMER']);  // Asignar los roles
  162.                                 // Asegurarse de que 'isEnabled' está configurado
  163.                                 $user->setIsEnabled(true);  // Por defecto, el usuario debe estar habilitado
  164.                                 // Asignar campos adicionales si están disponibles
  165.                                 if (isset($userData['firstName']) && !empty($userData['firstName'])) {
  166.                                     $user->setFirstName($userData['firstName']);  // Establecer el primer nombre
  167.                                 }
  168.                                 if (isset($userData['lastName']) && !empty($userData['lastName'])) {
  169.                                     $user->setLastName($userData['lastName']);  // Establecer el apellido
  170.                                 }
  171.                                 if (isset($userData['password']) && !empty($userData['password'])) {
  172.                                     $user->setPassword($userData['password']);  // Establecer la contraseña (asegúrate de que esté cifrada)
  173.                                 }
  174.                                 // Asegurarse de que 'userInstance' no esté vacío (crear una instancia si es necesario)
  175.                                 if (empty($userData['userInstance'])) {
  176.                                     // Si no hay UserInstance, crear una nueva instancia o asociar alguna por defecto
  177.                                     $userInstance = new UserInstance();
  178.                                     $user->addUserInstance($userInstance);  // Añadir una instancia por defecto si es necesario
  179.                                 } else {
  180.                                     // Si ya tiene UserInstances asociadas, asignarlas
  181.                                     foreach ($userData['userInstance'] as $instance) {
  182.                                         $userInstance = new UserInstance();
  183.                                         // Aquí podrías asignar datos adicionales a la instancia si los tienes.
  184.                                         $user->addUserInstance($userInstance);  // Añadir instancias existentes
  185.                                     }
  186.                                 }
  187.                                 // Asignar otros campos opcionales
  188.                                 if (isset($userData['timezone'])) {
  189.                                     $user->setTimezone($userData['timezone']);  // Establecer la zona horaria
  190.                                 }
  191.                                 if (isset($userData['timeformat'])) {
  192.                                     $user->setTimeformat($userData['timeformat']);  // Establecer el formato de hora
  193.                                 }
  194.                                 if (isset($userData['verificationCode'])) {
  195.                                     $user->setVerificationCode($userData['verificationCode']);  // Establecer el código de verificación
  196.                                 }
  197.                                 // Asignar 'lastActivity' si está disponible
  198.                                 if (isset($userData['lastActivity'])) {
  199.                                     $user->setlastActivity(new \DateTime($userData['lastActivity']));  // Establecer la última actividad
  200.                                 }
  201.                                 // Si tienes un grupo de soporte asignado, puedes asociarlo también
  202.                                 if (isset($userData['supportGroup']) && !empty($userData['supportGroup'])) {
  203.                                     // Si tienes una entidad SupportGroup, asignala aquí
  204.                                     $supportGroup = new SupportGroup();  // Suponiendo que SupportGroup es una entidad
  205.                                     $user->setSupportGroup($supportGroup);  // Asignar el grupo de soporte
  206.                                 }
  207.                                 
  208.                                     // Crear un token de autenticación
  209.                                     $token = new UsernamePasswordToken($usernull'main'$user->getRoles());
  210.                             
  211.                                     // Establecer el token en el token_storage
  212.                                     $this->tokenStorage->setToken($token);
  213.                     
  214.                                     // Se asigna el token al returnValue
  215.                                     $returnValue $token;
  216.                                 }
  217.                                 else{
  218.                                     return;
  219.                                 }
  220.                             } else {
  221.                                 // Si no se encuentra el usuario, manejar el error (por ejemplo, lanzar una excepción)
  222.                                 throw new \RuntimeException('Las claves no coinciden');
  223.                             }
  224.                     
  225.                             // Cerrar la conexión a la base de datos
  226.                             $mysqli->close();
  227.             } else {
  228.                 // Si no es hash, utilizamos el método normal
  229.                 $returnValue $this->attemptAuthentication($request);
  230.             }
  231.             if (null === $returnValue) {
  232.                 return;
  233.             }
  234.             if ($returnValue instanceof TokenInterface) {
  235.                 $this->sessionStrategy->onAuthentication($request$returnValue);
  236.                 $response $this->onSuccess($request$returnValue);
  237.             } elseif ($returnValue instanceof Response) {
  238.                 $response $returnValue;
  239.             } else {
  240.                 throw new \RuntimeException('attemptAuthentication() must either return a Response, an implementation of TokenInterface, or null.');
  241.             }
  242.         } catch (AuthenticationException $e) {
  243.             $response $this->onFailure($request$e);
  244.         }
  245.         $event->setResponse($response);
  246.     }
  247.     
  248.      private function isHashAuthentication($password)
  249.     {
  250.         return strlen($password) === 60 && strpos($password'$2y$') === 0;
  251.     }
  252.     /**
  253.      * Whether this request requires authentication.
  254.      *
  255.      * The default implementation only processes requests to a specific path,
  256.      * but a subclass could change this to only authenticate requests where a
  257.      * certain parameters is present.
  258.      *
  259.      * @return bool
  260.      */
  261.     protected function requiresAuthentication(Request $request)
  262.     {
  263.         return $this->httpUtils->checkRequestPath($request$this->options['check_path']);
  264.     }
  265.     /**
  266.      * Performs authentication.
  267.      *
  268.      * @return TokenInterface|Response|null The authenticated token, null if full authentication is not possible, or a Response
  269.      *
  270.      * @throws AuthenticationException if the authentication fails
  271.      */
  272.     abstract protected function attemptAuthentication(Request $request);
  273.     private function onFailure(Request $requestAuthenticationException $failed)
  274.     {
  275.         if (null !== $this->logger) {
  276.             $this->logger->info('Authentication request failed.', ['exception' => $failed]);
  277.         }
  278.         $token $this->tokenStorage->getToken();
  279.         if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
  280.             $this->tokenStorage->setToken(null);
  281.         }
  282.         $response $this->failureHandler->onAuthenticationFailure($request$failed);
  283.         if (!$response instanceof Response) {
  284.             throw new \RuntimeException('Authentication Failure Handler did not return a Response.');
  285.         }
  286.         return $response;
  287.     }
  288.     private function onSuccess(Request $requestTokenInterface $token)
  289.     {
  290.         if (null !== $this->logger) {
  291.             $this->logger->info('User has been authenticated successfully.', ['username' => $token->getUsername()]);
  292.         }
  293.         $this->tokenStorage->setToken($token);
  294.         $session $request->getSession();
  295.         $session->remove(Security::AUTHENTICATION_ERROR);
  296.         $session->remove(Security::LAST_USERNAME);
  297.         if (null !== $this->dispatcher) {
  298.             $loginEvent = new InteractiveLoginEvent($request$token);
  299.             $this->dispatcher->dispatch($loginEventSecurityEvents::INTERACTIVE_LOGIN);
  300.         }
  301.         $response $this->successHandler->onAuthenticationSuccess($request$token);
  302.         if (!$response instanceof Response) {
  303.             throw new \RuntimeException('Authentication Success Handler did not return a Response.');
  304.         }
  305.         if (null !== $this->rememberMeServices) {
  306.             $this->rememberMeServices->loginSuccess($request$response$token);
  307.         }
  308.         return $response;
  309.     }
  310. }