<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Este evento se distribuye después de que se haya resuelto el controlador a ejecutar, pero antes de ejecutarlo.
*/
class ControllerListener
{
public EntityManagerInterface $em;
private TranslatorInterface $translator;
/**
* ControllerListener constructor.
*/
public function __construct(
EntityManagerInterface $em,
TranslatorInterface $translator
) {
$this->em = $em;
$this->translator = $translator;
}
public function onKernelController(
ControllerEvent $event
) {
$date = new \DateTime('now');
$date = $date->getTimestamp();
$user = $this->getUser($event);
$email = null;
if ($user['status']) {
$email = $user['data']['email'];
}
$user = $this->em->getRepository(User::class)->findOneBy(['email' => $email]);
if ($user) {
$nameController = $this->getController($event);
if ($nameController === 'Auth'){
return true;
}
if (($user instanceof User) && !($user->isActiveNow())) {
$user->setLastActivity($date);
$this->em->persist($user);
$this->em->flush();
}
$accessURL = true;
// Comprobamos si el usuario tiene permisos para acceder a la plataforma
if ($user->getIsActive() === false) {
$accessURL = false;
}
// // Comprobamos la fecha del código SMS ha caducado
// if ($user->getSmsExpirationDate() !== null) {
// $smsCodeDate = $user->getSmsExpirationDate();
// if ($smsCodeDate < $date) {
// $accessURL = false;
// }
// } else if ($user->getSmsExpirationDate() === null) {
// $accessURL = false;
// }
if (!$accessURL) {
$response = new JsonResponse();
$response->setStatusCode(403);
$response->setData([
'status' => false,
'msg' => [$this->translator->trans('AUTH.Sorry, you do not have permission to access the platform')],
'data' => null,
]);
$event->setController(function () use ($response) {
return $response;
});
}
}
}
/**
* Decodificamos el Token que nos llega desde el event y retornamos el usuario.
*/
private function getUser(ControllerEvent $event): array
{
try {
$token = $event->getRequest()->server->get('HTTP_AUTHORIZATION');
if ($token) {
$tokenParts = explode('.', $token);
$tokenPayload = base64_decode($tokenParts[1]);
$jwtPayload = json_decode($tokenPayload);
return [
'status' => true,
'msg' => [],
'data' => [
'email' => $jwtPayload->username,
],
];
}
return [
'status' => false,
'mag' => ['Lo sentimos, hubo un problema con la petición. Prueba más tarde o consulta con el administrador.'],
'data' => null,
];
} catch (Exception $e) {
return [
'status' => false,
'mag' => [$e],
'data' => null,
];
}
}
/**
* Obtener el nombre del controlador.
*/
private function getController(ControllerEvent $event): string
{
$controller = $event->getController();
$controller = $controller[0];
$controller = get_class($controller);
$controller = explode('\\', $controller);
$controller = $controller[count($controller) - 1];
return str_replace('Controller', '', $controller);
}
}