<?php
namespace App\Controller;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use App\Entity\User;
use App\Form\UserType;
use App\Service\MailService;
class SecurityController extends AbstractController
{
private $entityManager;
private $repository;
private $passwordHasher;
private $mailService;
public function __construct(EntityManagerInterface $entityManager, ParameterBagInterface $parameterBag, UserPasswordHasherInterface $passwordHasher, MailService $mailService)
{
//Doctrine
$this->entityManager = $entityManager;
$this->repository = $this->entityManager->getRepository(User::class);
$this->passwordHasher = $passwordHasher;
$this->mailService = $mailService;
}
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
//Si ya estoy logueado, voy a la home
if ($this->getUser()) {
return $this->redirectToRoute('index');
}
//Obtengo los errores
$error = $authenticationUtils->getLastAuthenticationError();
//Obtengo el ultimo usuario logueado
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout(AuthenticationUtils $authenticationUtils)
{
//throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
//Obtengo los errores
$error = $authenticationUtils->getLastAuthenticationError();
//Obtengo el ultimo usuario logueado
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("/registrarme", name="app_registro")
*/
public function registro(Request $request): Response
{
$session = $request->getSession();
// Generar el valor CAPTCHA solo si el formulario no ha sido enviado
if (!$request->isMethod('POST')) {
$captchaValue = rand(1000, 9999); // Generar número aleatorio
$session->set('captcha_value', $captchaValue); // Guardarlo en la sesión
} else {
$captchaValue = $session->get('captcha_value'); // Usar el valor existente en la sesión
}
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Validar el CAPTCHA
$captchaInput = $form->get('captcha')->getData();
if ($captchaInput != $session->get('captcha_value')) {
$this->addFlash('error', 'El CAPTCHA (Codigo de Validacion) ingresado no es válido.');
// Regenerar un nuevo CAPTCHA después del error
$captchaValue = rand(1000, 9999);
$session->set('captcha_value', $captchaValue);
return $this->redirectToRoute('app_registro');
}
// Chequear si ya existe el usuario
$usuarioExistente = $this->repository->findByEmail($user->getMail());
if ($usuarioExistente === null) {
$user->setRoles(['ROLE_USER']);
$user->setPassword($this->passwordHasher->hashPassword($user, $user->getPassword()));
$this->entityManager->persist($user);
$this->entityManager->flush();
$this->addFlash('exito', "Registro Exitoso! Te enviamos un email a " . $user->getMail());
// Regenerar un nuevo CAPTCHA para la próxima visita
$captchaValue = rand(1000, 9999);
$session->set('captcha_value', $captchaValue);
return $this->redirectToRoute('app_login');
} else {
$this->addFlash('error', 'Ya existe un usuario registrado con este EMAIL');
// Regenerar un nuevo CAPTCHA después del error
$captchaValue = rand(1000, 9999);
$session->set('captcha_value', $captchaValue);
return $this->redirectToRoute('app_registro');
}
}
return $this->render('security/registro.html.twig', [
'form' => $form->createView(),
'captcha' => $captchaValue, // Pasamos el valor CAPTCHA a la vista
]);
}
}