<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
use App\Service\cryptService;
use Symfony\Component\HttpFoundation\Test\Constraint\ResponseIsRedirected;
class homeController extends AbstractController {
private function cookieDomain(Request $request): ?string {
// If URL_SITE matches the current host (or its parent domain), set it; otherwise omit Domain
// so the cookie is scoped to the current host. This avoids "login loops" in dev (IP/localhost).
$host = strtolower((string) $request->getHost());
$envDomain = strtolower((string) ($_ENV['URL_SITE'] ?? ''));
if ($envDomain === '') {
return null;
}
if ($host === $envDomain) {
return $envDomain;
}
if (str_ends_with($host, '.' . $envDomain)) {
return $envDomain;
}
return null;
}
/**
* @Route("/", name="index")
* @param Request $request
* @return Response
*/
public function index(Request $request, JWTEncoderInterface $JWTEncoder, cryptService $crip) {
$cookie = $request->cookies->get("SAPISID");
if ($cookie !== null) {
return $this->verificarTokenSession($request, $cookie, $JWTEncoder, $crip);
}
return $this->render('home.html.twig', [
'title' => 'Sistema de información de pasantías',
]);
}
private function verificarTokenSession(Request $request, $cookie, JWTEncoderInterface $JWTEncoder, cryptService $crip) {
try {
$token = $JWTEncoder->decode($cookie);
$data = unserialize($crip->decryptAES($token["data"], $crip->getPassAuto()));
return $this->redirectToRoute(substr( strtolower($data["roles"][0]),5,strlen($data["roles"][0])));
} catch (\Exception $exception) {
$response = new RedirectResponse('/');
// If the cookie is invalid, clear it for the current host/domain.
$cookie2 = new Cookie('SAPISID', '-', time(), '/', $this->cookieDomain($request), $request->isSecure(), true);
$response->headers->setCookie($cookie2);
$response->send();
return $this->render('home.html.twig', [
'title' => 'Sistema de información de pasantías',
]);
}
}
/**
* @Route("/login", name="login")
* @param Request $request
* @return Response
*/
public function login(Request $request, JWTEncoderInterface $jwt , cryptService $encrypt){
/** @var userEntity $data */
$data = $this->getUser();
$jwtData= serialize([
'roles' => $data->getRoles(),
'documento' => $data->getDocumento(),
'codigo' => $data->getCodigo(),
'password' => $data->getPassword(),
'username' => $data->getUsername()
]);
$token = $jwt->encode([
'data' => $encrypt->crypt($encrypt->getPassAuto() ,$jwtData)
]);
$cookie = Cookie::create('SAPISID')
->withValue($token)
->withExpires(time() + 43200)
->withDomain($this->cookieDomain($request))
->withSecure($request->isSecure())
->WithHttpOnly(true);
$response = new JsonResponse([
"data" => "Inicio correctamente" ,
"user" => $data->getRoles()[0],
"success" => true
]);
$response->headers->setcookie($cookie);
return $response;
}
/**
* @Route("/salir", name="salir", methods={"GET"})
*/
public function salir(Request $request) {
$response = new RedirectResponse('/');
$cookie2 = new Cookie('SAPISID', '-', time(), '/', $this->cookieDomain($request), $request->isSecure(), true);
$response->headers->setCookie($cookie2);
$response->send();
return $this->redirectToRoute('index');
}
}