src/EventListener/ControllerListener.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpFoundation\JsonResponse;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use App\Entity\User;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Exception;
  8. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  9. use Symfony\Contracts\Translation\TranslatorInterface;
  10. /**
  11.  * Este evento se distribuye después de que se haya resuelto el controlador a ejecutar, pero antes de ejecutarlo.
  12.  */
  13. class ControllerListener
  14. {
  15.     public EntityManagerInterface $em;
  16.     private TranslatorInterface $translator;
  17.     /**
  18.      * ControllerListener constructor.
  19.      */
  20.     public function __construct(
  21.         EntityManagerInterface $em,
  22.         TranslatorInterface $translator
  23.     ) {
  24.         $this->em $em;
  25.         $this->translator $translator;
  26.     }
  27.     public function onKernelController(
  28.         ControllerEvent $event
  29.     ) {
  30.         $date = new \DateTime('now');
  31.         $date $date->getTimestamp();
  32.         $user $this->getUser($event);
  33.         $email null;
  34.         if ($user['status']) {
  35.             $email $user['data']['email'];
  36.         }
  37.         $user $this->em->getRepository(User::class)->findOneBy(['email' => $email]);
  38.         if ($user) {
  39.             $nameController $this->getController($event);
  40.             if ($nameController === 'Auth'){
  41.                 return true;
  42.             }
  43.             if (($user instanceof User) && !($user->isActiveNow())) {
  44.                 $user->setLastActivity($date);
  45.                 $this->em->persist($user);
  46.                 $this->em->flush();
  47.             }
  48.             $accessURL true;
  49.             // Comprobamos si el usuario tiene permisos para acceder a la plataforma
  50.             if ($user->getIsActive() === false) {
  51.                 $accessURL false;
  52.             }
  53.             // // Comprobamos la fecha del código SMS ha caducado
  54.             // if ($user->getSmsExpirationDate() !== null) {
  55.             //     $smsCodeDate = $user->getSmsExpirationDate();
  56.             //     if ($smsCodeDate < $date) {
  57.             //         $accessURL = false;
  58.             //     }
  59.             // } else if ($user->getSmsExpirationDate() === null) {
  60.             //     $accessURL = false;
  61.             // }
  62.             if (!$accessURL) {
  63.                 $response = new JsonResponse();
  64.                 $response->setStatusCode(403);
  65.                 $response->setData([
  66.                     'status' => false,
  67.                     'msg' => [$this->translator->trans('AUTH.Sorry, you do not have permission to access the platform')],
  68.                     'data' => null,
  69.                 ]);
  70.                 $event->setController(function () use ($response) {
  71.                     return $response;
  72.                 });
  73.             }
  74.         }
  75.     }
  76.     /**
  77.      * Decodificamos el Token que nos llega desde el event y retornamos el usuario.
  78.      */
  79.     private function getUser(ControllerEvent $event): array
  80.     {
  81.         try {
  82.             $token $event->getRequest()->server->get('HTTP_AUTHORIZATION');
  83.             if ($token) {
  84.                 $tokenParts explode('.'$token);
  85.                 $tokenPayload base64_decode($tokenParts[1]);
  86.                 $jwtPayload json_decode($tokenPayload);
  87.                 return [
  88.                     'status' => true,
  89.                     'msg' => [],
  90.                     'data' => [
  91.                         'email' => $jwtPayload->username,
  92.                     ],
  93.                 ];
  94.             }
  95.             return [
  96.                 'status' => false,
  97.                 'mag' => ['Lo sentimos, hubo un problema con la petición. Prueba más tarde o consulta con el administrador.'],
  98.                 'data' => null,
  99.             ];
  100.         } catch (Exception $e) {
  101.             return [
  102.                 'status' => false,
  103.                 'mag' => [$e],
  104.                 'data' => null,
  105.             ];
  106.         }
  107.     }
  108.     /**
  109.      * Obtener el nombre del controlador.
  110.      */
  111.     private function getController(ControllerEvent $event): string
  112.     {
  113.         $controller $event->getController();
  114.         $controller $controller[0];
  115.         $controller get_class($controller);
  116.         $controller explode('\\'$controller);
  117.         $controller $controller[count($controller) - 1];
  118.         return str_replace('Controller'''$controller);
  119.     }
  120. }