src/Controller/ReposicionController.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 ReposicionController extends AbstractController
  24. {
  25.     use ResetPasswordControllerTrait;
  26.     private $resetPasswordHelper;
  27.     private $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(EntityManagerInterface $entityManagerRequest $requestMailerInterface $mailerTranslatorInterface $translator): Response
  39.     {
  40.         $form $this->createForm(ResetPasswordRequestFormType::class);
  41.         $form->handleRequest($request);
  42.         if ($form->isSubmitted() && $form->isValid()) {
  43.             $u $entityManager->getRepository(Usuario::class)->findOneBy(['correo' => $form->get('correo')->getData()]);
  44.             if (!empty($u)){
  45.                 if ($u->getEstatus() == 'Pendiente' || $u->getEstatus() == 'Rechazado' || $u->getEstatus() == 'Suspendido'){
  46.                     return $this->render('reposicion/request.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('reposicion/request.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('reposicion/request.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", name="app_check_email")
  72.      */
  73.     public function checkEmail(): 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('reposicion/check_email.html.twig', [
  81.             'resetToken' => $resetToken,
  82.         ]);
  83.     }
  84.     /**
  85.      * Validates and process the reset URL that the user clicked in their email.
  86.      *
  87.      * @Route("/reset/{token}", name="app_reset_password")
  88.      */
  89.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  90.     {
  91.         if ($token) {
  92.             // We store the token in session and remove it from the URL, to avoid the URL being
  93.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  94.             $this->storeTokenInSession($token);
  95.             return $this->redirectToRoute('app_reset_password');
  96.         }
  97.         $token $this->getTokenFromSession();
  98.         if (null === $token) {
  99.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  100.         }
  101.         try {
  102.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  103.         } catch (ResetPasswordExceptionInterface $e) {
  104.             $this->addFlash('reset_password_error'sprintf(
  105.                 '%s - %s',
  106.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  107.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  108.             ));
  109.             return $this->redirectToRoute('app_forgot_password_request');
  110.         }
  111.         // The token is valid; allow the user to change their password.
  112.         $form $this->createForm(ChangePasswordFormType::class);
  113.         $form->handleRequest($request);
  114.         if ($form->isSubmitted() && $form->isValid()) {
  115.             // A password reset token should be used only once, remove it.
  116.             $this->resetPasswordHelper->removeResetRequest($token);
  117.             // Encode(hash) the plain password, and set it.
  118.             $encodedPassword $userPasswordHasher->hashPassword(
  119.                 $user,
  120.                 $form->get('plainPassword')->getData()
  121.             );
  122.             $user->setContrasena($encodedPassword);
  123.             $this->entityManager->flush();
  124.             // The session is cleaned up after the password has been changed.
  125.             $this->cleanSessionAfterReset();
  126.             return $this->redirectToRoute('homepage');
  127.         }
  128.         return $this->render('reposicion/reset.html.twig', [
  129.             'resetForm' => $form->createView(),
  130.         ]);
  131.     }
  132.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  133.     {
  134.         $user $this->entityManager->getRepository(Usuario::class)->findOneBy([
  135.             'correo' => $emailFormData,
  136.         ]);
  137.         // Do not reveal whether a user account was found or not.
  138.         if (!$user) {
  139.             return $this->redirectToRoute('app_check_email');
  140.         }
  141.         try {
  142.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  143.         } catch (ResetPasswordExceptionInterface $e) {
  144.             // If you want to tell the user why a reset email was not sent, uncomment
  145.             // the lines below and change the redirect to 'app_forgot_password_request'.
  146.             // Caution: This may reveal if a user is registered or not.
  147.             //
  148.             // $this->addFlash('reset_password_error', sprintf(
  149.             //     '%s - %s',
  150.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  151.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  152.             // ));
  153.             return $this->redirectToRoute('app_check_email');
  154.         }
  155.         $email = (new TemplatedEmail())
  156.             ->from(new Address('no-reply-ti@conalepmex.edu.mx''Recuperación de contraseña'))
  157.             ->to($user->getCorreo())
  158.             ->subject('Recuperación de contraseña')
  159.             ->htmlTemplate('reposicion/email.html.twig')
  160.             ->context([
  161.                 'resetToken' => $resetToken,
  162.             ])
  163.         ;
  164.         $mailer->send($email);
  165.         // Store the token object in session for retrieval in check-email route.
  166.         $this->setTokenObjectInSession($resetToken);
  167.         return $this->redirectToRoute('app_check_email');
  168.     }
  169. }