src/Controller/homeController.php line 39

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Component\HttpFoundation\Cookie;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpFoundation\RedirectResponse;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
  11. use App\Service\cryptService;
  12. use Symfony\Component\HttpFoundation\Test\Constraint\ResponseIsRedirected;
  13. class homeController extends AbstractController {
  14.     private function cookieDomain(Request $request): ?string {
  15.         // If URL_SITE matches the current host (or its parent domain), set it; otherwise omit Domain
  16.         // so the cookie is scoped to the current host. This avoids "login loops" in dev (IP/localhost).
  17.         $host strtolower((string) $request->getHost());
  18.         $envDomain strtolower((string) ($_ENV['URL_SITE'] ?? ''));
  19.         if ($envDomain === '') {
  20.             return null;
  21.         }
  22.         if ($host === $envDomain) {
  23.             return $envDomain;
  24.         }
  25.         if (str_ends_with($host'.' $envDomain)) {
  26.             return $envDomain;
  27.         }
  28.         return null;
  29.     }
  30.     /**
  31.      * @Route("/", name="index")
  32.      * @param Request $request
  33.      * @return Response
  34.      */
  35.     public function index(Request $requestJWTEncoderInterface $JWTEncodercryptService $crip) {
  36.         $cookie $request->cookies->get("SAPISID");
  37.         if ($cookie !== null) {
  38.             return $this->verificarTokenSession($request$cookie$JWTEncoder$crip);
  39.         }
  40.         
  41.         return $this->render('home.html.twig', [
  42.             'title' => 'Sistema de información de pasantías',
  43.         ]);
  44.     }
  45.     private function verificarTokenSession(Request $request$cookieJWTEncoderInterface $JWTEncodercryptService $crip) {
  46.         try {
  47.             $token $JWTEncoder->decode($cookie);
  48.             $data unserialize($crip->decryptAES($token["data"], $crip->getPassAuto()));
  49.             return $this->redirectToRoute(substrstrtolower($data["roles"][0]),5,strlen($data["roles"][0])));
  50.         } catch (\Exception $exception) {
  51.             $response = new RedirectResponse('/');
  52.             // If the cookie is invalid, clear it for the current host/domain.
  53.             $cookie2 = new Cookie('SAPISID''-'time(), '/'$this->cookieDomain($request), $request->isSecure(), true);
  54.             $response->headers->setCookie($cookie2);
  55.             $response->send();
  56.             return $this->render('home.html.twig', [
  57.                 'title' => 'Sistema de información de pasantías',
  58.             ]);
  59.         }
  60.     }
  61.     /**
  62.      * @Route("/login", name="login")
  63.      * @param Request $request
  64.      * @return Response
  65.      */
  66.     public function login(Request $requestJWTEncoderInterface $jwt cryptService $encrypt){
  67.          /** @var userEntity $data */
  68.          $data $this->getUser();
  69.          $jwtDataserialize([
  70.              'roles' => $data->getRoles(),
  71.              'documento' => $data->getDocumento(),
  72.              'codigo' => $data->getCodigo(),
  73.              'password' => $data->getPassword(),
  74.              'username' => $data->getUsername()
  75.          ]);
  76.          $token $jwt->encode([
  77.              'data' => $encrypt->crypt($encrypt->getPassAuto() ,$jwtData)
  78.          ]);
  79.          $cookie Cookie::create('SAPISID')
  80.          ->withValue($token)
  81.          ->withExpires(time() + 43200)
  82.          ->withDomain($this->cookieDomain($request))
  83.          ->withSecure($request->isSecure())
  84.          ->WithHttpOnly(true);
  85.          $response =  new JsonResponse([
  86.              "data" => "Inicio correctamente" ,
  87.              "user" => $data->getRoles()[0],
  88.              "success" => true
  89.          ]);
  90.          $response->headers->setcookie($cookie);
  91.         return $response;
  92.     }
  93.     
  94.     /**
  95.      * @Route("/salir", name="salir", methods={"GET"})
  96.      */
  97.     public function salir(Request $request) {
  98.         $response = new RedirectResponse('/');
  99.         $cookie2 = new Cookie('SAPISID''-'time(), '/'$this->cookieDomain($request), $request->isSecure(), true);
  100.         $response->headers->setCookie($cookie2);
  101.         $response->send();
  102.         return $this->redirectToRoute('index');
  103.     }
  104. }