src/Controller/SecurityController.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  10. use App\Entity\User;
  11. use App\Form\RegistrationFormType;
  12. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  13. class SecurityController extends AbstractController
  14. {
  15.     /**
  16.      * @Route("/login", name="app_login")
  17.      */
  18.     public function login(AuthenticationUtils $authenticationUtils): Response
  19.     {
  20.         // if ($this->getUser()) {
  21.         //     return $this->redirectToRoute('target_path');
  22.         // }
  23.         // get the login error if there is one
  24.         $error $authenticationUtils->getLastAuthenticationError();
  25.         // last username entered by the user
  26.         $lastUsername $authenticationUtils->getLastUsername();
  27.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  28.     }
  29.     /**
  30.      * @Route("/logout", name="app_logout")
  31.      */
  32.     public function logout(): void
  33.     {
  34.         throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  35.     }
  36.     /**
  37.      * @Route("/forgot-password", name="app_forgot_password")
  38.     */
  39.     public function forgotPassword(): Response
  40.     {
  41.         // Aquí iría la lógica para enviar email de recuperación
  42.         return $this->render('security/forgot_password.html.twig');
  43.     }
  44.     /**
  45.      * @Route("/register", name="app_register")
  46.     */
  47.    
  48.     public function register(
  49.         Request $request,
  50.         UserPasswordHasherInterface $passwordHasher,
  51.         EntityManagerInterface $entityManager
  52.     ): Response {
  53.         $user = new User();
  54.         $form $this->createForm(RegistrationFormType::class, $user);
  55.         $form->handleRequest($request);
  56.         if ($form->isSubmitted() && $form->isValid()) {
  57.             // Rol por defecto para nuevos registros públicos
  58.             $user->setRoles(['ROLE_CLIENT']);
  59.             // Hash de la contraseña
  60.             $hashedPassword $passwordHasher->hashPassword(
  61.                 $user,
  62.                 $user->getPlainPassword()
  63.             );
  64.             $user->setPassword($hashedPassword);
  65.             try {
  66.                 // Buscar al admin por rol
  67.                $admin $entityManager->getRepository(User::class)
  68.                 ->createQueryBuilder('u')
  69.                 ->andWhere('u.roles LIKE :role')
  70.                 ->setParameter('role''%"ROLE_ADMIN"%')
  71.                 ->setMaxResults(1)
  72.                 ->getQuery()
  73.                 ->getOneOrNullResult();
  74.                 if ($admin) {
  75.                     // Relación ManyToMany: asignar el paciente al admin
  76.                     $admin->addPatient($user);
  77.                     $entityManager->persist($admin);
  78.                 }
  79.                 // Guardar usuario
  80.                 $entityManager->persist($user);
  81.                 $entityManager->flush();
  82.                 $this->addFlash('success''Cuenta creada correctamente.');
  83.                 return $this->redirectToRoute('app_login');
  84.             } catch (UniqueConstraintViolationException $e) {
  85.                 $this->addFlash('error''Ya existe una cuenta con este correo electrónico.');
  86.             }
  87.         }
  88.         return $this->render('security/register.html.twig', [
  89.             'registrationForm' => $form->createView(),
  90.         ]);
  91.     }
  92. }