src/Controller/CambioContrasenaController.php line 44

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Usuario;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\ResetPasswordRequestFormType;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Mailer\MailerInterface;
  13. use Symfony\Component\Mime\Address;
  14. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  15. use Symfony\Component\Routing\Annotation\Route;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  18. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  20. /**
  21.  * @Route("common/reset-password")
  22.  */
  23. class CambioContrasenaController extends AbstractController
  24. {
  25.     use ResetPasswordControllerTrait;
  26.     private ResetPasswordHelperInterface $resetPasswordHelper;
  27.     private EntityManagerInterface $entityManager;
  28.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManager)
  29.     {
  30.         $this->resetPasswordHelper $resetPasswordHelper;
  31.         $this->entityManager $entityManager;
  32.     }
  33.     /**
  34.      * Display & process form to request a password reset.
  35.      *
  36.      * @Route("", name="app_forgot_password_request")
  37.      */
  38.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  39.     {
  40.         $form $this->createForm(ResetPasswordRequestFormType::class);
  41.         $form->handleRequest($request);
  42.         if ($form->isSubmitted() && $form->isValid()) {
  43.             $u $this->entityManager->getRepository(Usuario::class)->findOneBy(['correo' => $form->get('correo')->getData()]);
  44.             if (!empty($u)){
  45.                 if (in_array($u->getEstatus(), ['Pendiente''Rechazado''Suspendido'])){
  46.                     return $this->render('cambio_contrasena/index.html.twig', [
  47.                         'requestForm' => $form->createView(),
  48.                         'mensaje' => 'Requiere una autorización previa para poder realizar el cambio de contraseña.'
  49.                     ]);
  50.                 } else {;
  51.                     return $this->processSendingPasswordResetEmail(
  52.                         $form->get('correo')->getData(),
  53.                         $mailer,
  54.                         $translator
  55.                     );
  56.                 }
  57.             } else {
  58.                 return $this->render('cambio_contrasena/index.html.twig', [
  59.                     'requestForm' => $form->createView(),
  60.                     'mensaje' => 'No se encontró el usuario, es necesario solicitar acceso al sistema.'
  61.                 ]);
  62.             }
  63.         }
  64.         return $this->render('cambio_contrasena/index.html.twig', [
  65.             'requestForm' => $form->createView(),
  66.         ]);
  67.     }
  68.     /**
  69.      * Confirmation page after a user has requested a password reset.
  70.      *
  71.      * @Route("/check-email/{correo}", name="app_check_email")
  72.      */
  73.     public function checkEmail(Request $request): Response
  74.     {
  75.         // Generate a fake token if the user does not exist or someone hit this page directly.
  76.         // This prevents exposing whether or not a user was found with the given email address or not
  77.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  78.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  79.         }
  80.         return $this->render('cambio_contrasena/check_email.html.twig', [
  81.             'resetToken' => $resetToken,
  82.             'correo' => $request->get('correo')
  83.         ]);
  84.     }
  85.     /**
  86.      * Validates and process the reset URL that the user clicked in their email.
  87.      *
  88.      * @Route("/reset/{token}", name="app_reset_password")
  89.      */
  90.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  91.     {
  92.         if ($token) {
  93.             // We store the token in session and remove it from the URL, to avoid the URL being
  94.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  95.             $this->storeTokenInSession($token);
  96.             return $this->redirectToRoute('app_reset_password');
  97.         }
  98.         $token $this->getTokenFromSession();
  99.         if (null === $token) {
  100.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  101.         }
  102.         try {
  103.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  104.         } catch (ResetPasswordExceptionInterface $e) {
  105.             $this->addFlash('reset_password_error'sprintf(
  106.                 '%s - %s',
  107.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  108.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  109.             ));
  110.             return $this->redirectToRoute('app_forgot_password_request');
  111.         }
  112.         // The token is valid; allow the user to change their password.
  113.         $form $this->createForm(ChangePasswordFormType::class);
  114.         $form->handleRequest($request);
  115.         if ($form->isSubmitted() && $form->isValid()) {
  116.             // A password reset token should be used only once, remove it.
  117.             $this->resetPasswordHelper->removeResetRequest($token);
  118.             // Encode(hash) the plain password, and set it.
  119.             $encodedPassword $userPasswordHasher->hashPassword(
  120.                 $user,
  121.                 $form->get('plainPassword')->getData()
  122.             );
  123.             $user->setContrasena($encodedPassword);
  124.             $this->entityManager->flush();
  125.             // The session is cleaned up after the password has been changed.
  126.             $this->cleanSessionAfterReset();
  127.             return $this->redirectToRoute('homepage');
  128.         }
  129.         return $this->render('cambio_contrasena/reset.html.twig', [
  130.             'resetForm' => $form->createView(),
  131.         ]);
  132.     }
  133.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  134.     {
  135.         $user $this->entityManager->getRepository(Usuario::class)->findOneBy([
  136.             'correo' => $emailFormData,
  137.         ]);
  138.         // Do not reveal whether a user account was found or not.
  139.         if (!$user) {
  140.             return $this->redirectToRoute('app_check_email', ['correo' => $emailFormData]);
  141.         }
  142.         try {
  143.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  144.         } catch (ResetPasswordExceptionInterface $e) {
  145.             // If you want to tell the user why a reset email was not sent, uncomment
  146.             // the lines below and change the redirect to 'app_forgot_password_request'.
  147.             // Caution: This may reveal if a user is registered or not.
  148.             //
  149.             // $this->addFlash('reset_password_error', sprintf(
  150.             //     '%s - %s',
  151.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  152.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  153.             // ));
  154.             return $this->redirectToRoute('app_check_email', ['correo' => $emailFormData]);
  155.         }
  156.         $email = (new TemplatedEmail())
  157.             ->from(new Address('no-reply-ti@conalepmex.edu.mx''Recuperación de contraseña'))
  158.             ->to($user->getCorreo())
  159.             ->subject('Recuperación de contraseña')
  160.             ->htmlTemplate('cambio_contrasena/email.html.twig')
  161.             ->context([
  162.                 'resetToken' => $resetToken
  163.             ])
  164.         ;
  165.         $mailer->send($email);
  166.         // Store the token object in session for retrieval in check-email route.
  167.         $this->setTokenObjectInSession($resetToken);
  168.         return $this->redirectToRoute('app_check_email', ['correo' => $emailFormData]);
  169.     }
  170. }