src/Security/UserAuthenticator.php line 106

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\SonataUserUser;
  4. use App\Repository\SonataUserUserRepository;
  5. use App\Services\ApiConsumer;
  6. use App\Utils\EAS256CBC;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Doctrine\ORM\Exception\ManagerException;
  9. use Symfony\Component\HttpFoundation\JsonResponse;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  13. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  14. use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
  15. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  16. use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
  17. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  18. use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
  19. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  20. use Symfony\Contracts\HttpClient\HttpClientInterface;
  21. class UserAuthenticator extends AbstractAuthenticator
  22. {
  23.     protected HttpClientInterface      $httpClient;
  24.     protected ApiConsumer              $apiConsumer;
  25.     protected EAS256CBC                $EAS256CBC;
  26.     protected EntityManagerInterface   $entityManager;
  27.     protected SonataUserUserRepository $userRepository;
  28.     public function __construct(HttpClientInterface $httpClientApiConsumer $apiConsumerEAS256CBC $EAS256CBCEntityManagerInterface $entityManagerSonataUserUserRepository $userRepository)
  29.     {
  30.         $this->httpClient     $httpClient;
  31.         $this->apiConsumer    $apiConsumer;
  32.         $this->EAS256CBC      $EAS256CBC;
  33.         $this->entityManager  $entityManager;
  34.         $this->userRepository $userRepository;
  35.     }
  36.     /**
  37.      * Called on every request to decide if this authenticator should be
  38.      * used for the request. Returning `false` will cause this authenticator
  39.      * to be skipped.
  40.      */
  41.     public function supports(Request $request): ?bool
  42.     {
  43.         if ($request->request->get('_username')) {
  44.             return true;
  45.         } else {
  46.             return false;
  47.         }
  48.     }
  49.     public function authenticate(Request $request): SelfValidatingPassport
  50.     {
  51.         $session $request->getSession();
  52.         $password $request->request->get('_password') ?? NULL;
  53.         $username $request->request->get('_username') ?? NULL;
  54.         if (!$username || !$password) {
  55.             throw new AuthenticationException('Usuario y contraseña son requeridos.');
  56.         }
  57.         try {
  58.             $userPasswordHash $this->EAS256CBC->encrypt($username '#' $password$this->apiConsumer::$key);
  59.             $user_data $this->apiConsumer->getClienteValidar($userPasswordHash);
  60.             if ($user_data instanceof Response) {
  61.                 throw new AuthenticationException('No se pudo validar el usuario en este momento. Intente nuevamente más tarde.');
  62.             }
  63.             $isEmptyPayload =
  64.                 $user_data === null ||
  65.                 $user_data === '[]' ||
  66.                 $user_data === '' ||
  67.                 (is_array($user_data) && count($user_data) === 0) ||
  68.                 (is_object($user_data) && count((array)$user_data) === 0);
  69.             if ($isEmptyPayload) {
  70.                 throw new AuthenticationException('Usuario o contraseña son incorrectos.');
  71.             }
  72.             $user $this->userRepository->findOneBy(['username' => $username]);
  73.             if (!$user) {
  74.                 $user = new SonataUserUser();
  75.                 $user->setUsername($username);
  76.                 $user->setUsernameCanonical($username);
  77.                 $user->setEmail($username);
  78.                 $user->setEmailCanonical($username);
  79.                 $user->setEnabled(true);
  80.                 $user->setRoles(['ROLE_USER']);
  81.                 $user->setPassword($userPasswordHash);
  82.                 $user->setUserPassHash($userPasswordHash);
  83.             }else{
  84.                 $user->setUserPassHash($userPasswordHash);
  85.             }
  86.             $this->entityManager->persist($user);
  87.             $this->entityManager->flush();
  88.             $session->set('user_password_hash'$userPasswordHash);
  89.             $session->set('user_module_name'$user_data);
  90.             return new SelfValidatingPassport(
  91.                 new UserBadge($username, function () use ($user) {
  92.                     return $user;
  93.                 })
  94.             );
  95.         } catch (\Exception|ManagerException $e) {
  96.             throw new AuthenticationException($e->getMessage());
  97.         }
  98.     }
  99.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  100.     {
  101.         $data = [
  102.             [
  103.                 "result" => "success",
  104.                 "token"  => $token->getUsername(),
  105.                 "user"   => [
  106.                     "id" => $token->getUser()->getId(),
  107.                 ],
  108.                 "errors" => [
  109.                     "issues" => ""
  110.                 ]
  111.             ]
  112.         ];
  113.         return new JsonResponse($data200, ['json_encode_options' => JSON_UNESCAPED_SLASHES]);
  114.     }
  115.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception): ?Response
  116.     {
  117.         $data = [
  118.             [
  119.                 "result" => "error",
  120.                 "token"  => '',
  121.                 "user"   => [
  122.                     "id" => '',
  123.                 ],
  124.                 "errors" => [
  125.                     "issues" => $exception->getMessage()
  126.                 ]
  127.             ]
  128.         ];
  129.         return new JsonResponse($dataResponse::HTTP_UNAUTHORIZED, ['json_encode_options' => JSON_UNESCAPED_SLASHES]);
  130.     }
  131. }