src/Controller/SecurityController.php line 38

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  10. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  11. use App\Entity\User;
  12. use App\Form\UserType;
  13. use App\Service\MailService;
  14. class SecurityController extends AbstractController
  15. {
  16.     private $entityManager;
  17.     private $repository;
  18.     private $passwordHasher;
  19.     private $mailService;
  20.     public function __construct(EntityManagerInterface $entityManagerParameterBagInterface $parameterBagUserPasswordHasherInterface $passwordHasherMailService $mailService)
  21.     {
  22.         //Doctrine
  23.         $this->entityManager $entityManager;
  24.         $this->repository $this->entityManager->getRepository(User::class);
  25.         $this->passwordHasher $passwordHasher;
  26.         $this->mailService $mailService;
  27.     }
  28.     /**
  29.      * @Route("/login", name="app_login")
  30.      */
  31.     public function login(AuthenticationUtils $authenticationUtils): Response
  32.     {
  33.         //Si ya estoy logueado, voy a la home
  34.         if ($this->getUser()) {
  35.             return $this->redirectToRoute('index');
  36.         }
  37.         //Obtengo los errores
  38.         $error $authenticationUtils->getLastAuthenticationError();
  39.         //Obtengo el ultimo usuario logueado
  40.         $lastUsername $authenticationUtils->getLastUsername();
  41.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  42.     }
  43.     /**
  44.      * @Route("/logout", name="app_logout")
  45.      */
  46.     public function logout(AuthenticationUtils $authenticationUtils)
  47.     {
  48.         //throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  49.         //Obtengo los errores
  50.         $error $authenticationUtils->getLastAuthenticationError();
  51.         //Obtengo el ultimo usuario logueado
  52.         $lastUsername $authenticationUtils->getLastUsername();
  53.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  54.     }
  55.     /**
  56.      * @Route("/registrarme", name="app_registro")
  57.      */
  58.     public function registro(Request $request): Response
  59.     {
  60.         $session $request->getSession();
  61.         // Generar el valor CAPTCHA solo si el formulario no ha sido enviado
  62.         if (!$request->isMethod('POST')) {
  63.             $captchaValue rand(10009999); // Generar número aleatorio
  64.             $session->set('captcha_value'$captchaValue); // Guardarlo en la sesión
  65.         } else {
  66.             $captchaValue $session->get('captcha_value'); // Usar el valor existente en la sesión
  67.         }
  68.         $user = new User();
  69.         $form $this->createForm(UserType::class, $user);
  70.         $form->handleRequest($request);
  71.         if ($form->isSubmitted() && $form->isValid()) {
  72.             // Validar el CAPTCHA
  73.             $captchaInput $form->get('captcha')->getData();
  74.             if ($captchaInput != $session->get('captcha_value')) {
  75.                 $this->addFlash('error''El CAPTCHA (Codigo de Validacion) ingresado no es válido.');
  76.                 // Regenerar un nuevo CAPTCHA después del error
  77.                 $captchaValue rand(10009999);
  78.                 $session->set('captcha_value'$captchaValue);
  79.                 return $this->redirectToRoute('app_registro');
  80.             }
  81.             // Chequear si ya existe el usuario
  82.             $usuarioExistente $this->repository->findByEmail($user->getMail());
  83.             if ($usuarioExistente === null) {
  84.                 $user->setRoles(['ROLE_USER']);
  85.                 $user->setPassword($this->passwordHasher->hashPassword($user$user->getPassword()));
  86.                 $this->entityManager->persist($user);
  87.                 $this->entityManager->flush();
  88.                 $this->addFlash('exito'"Registro Exitoso! Te enviamos un email a " $user->getMail());
  89.                 // Regenerar un nuevo CAPTCHA para la próxima visita
  90.                 $captchaValue rand(10009999);
  91.                 $session->set('captcha_value'$captchaValue);
  92.                 return $this->redirectToRoute('app_login');
  93.             } else {
  94.                 $this->addFlash('error''Ya existe un usuario registrado con este EMAIL');
  95.                 // Regenerar un nuevo CAPTCHA después del error
  96.                 $captchaValue rand(10009999);
  97.                 $session->set('captcha_value'$captchaValue);
  98.                 return $this->redirectToRoute('app_registro');
  99.             }
  100.         }
  101.         return $this->render('security/registro.html.twig', [
  102.             'form' => $form->createView(),
  103.             'captcha' => $captchaValue// Pasamos el valor CAPTCHA a la vista
  104.         ]);
  105.     }
  106. }