src/Controller/ResetPasswordController.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Entity\Notification;
  5. use App\Form\ChangePasswordFormType;
  6. use App\Form\ResetPasswordRequestFormType;
  7. use App\Service\NotificationService;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Psr\Log\LoggerInterface;
  10. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Mailer\MailerInterface;
  16. use Symfony\Component\Mime\Address;
  17. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  20. use Symfony\Contracts\Translation\TranslatorInterface;
  21. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  22. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  23. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  24. use Symfony\Component\Translation\TranslatableMessage;
  25. #[Route('/reset-password')]
  26. class ResetPasswordController extends AbstractController
  27. {
  28.     use ResetPasswordControllerTrait;
  29.     
  30.     public function __construct(
  31.         private ResetPasswordHelperInterface $resetPasswordHelper,
  32.         private EntityManagerInterface $entityManager,
  33.         private NotificationService $notificationService,
  34.         private LoggerInterface $loggerInterface
  35.     ) {
  36.         //$this->loggerInterface = $loggerInterface;
  37.     }
  38.     /**
  39.      * Display & process form to request a password reset.
  40.      */
  41.     #[Route(''name'app_forgot_password_request')]
  42.     public function request(Request $requestTranslatorInterface $translator): Response
  43.     {
  44.         $this->loggerInterface->debug(__METHOD__);
  45.         $form $this->createForm(ResetPasswordRequestFormType::class);
  46.         $form->handleRequest($request);
  47.         if ($form->isSubmitted() && $form->isValid()) {
  48.             return $this->processSendingPasswordResetEmail(
  49.                 $form->get('email')->getData(),
  50.                 $translator
  51.             );
  52.         }
  53.         return $this->render('reset_password/request.html.twig', [
  54.             'requestForm' => $form->createView(),
  55.         ]);
  56.     }
  57.     /**
  58.      * Confirmation page after a user has requested a password reset.
  59.      */
  60.     #[Route('/check-email'name'app_check_email')]
  61.     public function checkEmail(): Response
  62.     {
  63.         $this->loggerInterface->debug(__METHOD__);
  64.         // Generate a fake token if the user does not exist or someone hit this page directly.
  65.         // This prevents exposing whether or not a user was found with the given email address or not
  66.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  67.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  68.         }
  69.         return $this->render('reset_password/check_email.html.twig', [
  70.             'resetToken' => $resetToken,
  71.         ]);
  72.     }
  73.     /**
  74.      * Validates and process the reset URL that the user clicked in their email.
  75.      */
  76.     #[Route('/reset/{token}'name'app_reset_password')]
  77.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherTranslatorInterface $translatorstring $token null): Response
  78.     {
  79.         $this->loggerInterface->debug(__METHOD__);
  80.         if ($token) {
  81.             // We store the token in session and remove it from the URL, to avoid the URL being
  82.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  83.             $this->storeTokenInSession($token);
  84.             return $this->redirectToRoute('app_reset_password');
  85.         }
  86.         $token $this->getTokenFromSession();
  87.         if (null === $token) {
  88.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  89.         }
  90.         try {
  91.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  92.         } catch (ResetPasswordExceptionInterface $e) {
  93.             $this->addFlash('reset_password_error'sprintf(
  94.                 '%s - %s',
  95.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  96.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  97.             ));
  98.             return $this->redirectToRoute('app_forgot_password_request');
  99.         }
  100.         // The token is valid; allow the user to change their password.
  101.         $form $this->createForm(ChangePasswordFormType::class);
  102.         $form->handleRequest($request);
  103.         if ($form->isSubmitted() && $form->isValid()) {
  104.             // A password reset token should be used only once, remove it.
  105.             $this->resetPasswordHelper->removeResetRequest($token);
  106.             // Encode(hash) the plain password, and set it.
  107.             $encodedPassword $passwordHasher->hashPassword(
  108.                 $user,
  109.                 $form->get('plainPassword')->getData()
  110.             );
  111.             $user->setPassword($encodedPassword);
  112.             $this->entityManager->flush();
  113.             // The session is cleaned up after the password has been changed.
  114.             $this->cleanSessionAfterReset();
  115.             return $this->redirectToRoute('app_login');
  116.         }
  117.         return $this->render('reset_password/reset.html.twig', [
  118.             'resetForm' => $form->createView(),
  119.         ]);
  120.     }
  121.     private function processSendingPasswordResetEmail(string $emailFormDataTranslatorInterface $translator): RedirectResponse
  122.     {
  123.         $this->loggerInterface->debug(__METHOD__, [
  124.             "emailFormData" => $emailFormData
  125.         ]);
  126.         $user $this->entityManager->getRepository(User::class)->loadUserByIdentifier($emailFormData,true);
  127.         // Do not reveal whether a user account was found or not.
  128.         if (!$user) {
  129.             $this->loggerInterface->warning("User not found");
  130.             return $this->redirectToRoute('app_check_email');
  131.         }
  132.         try {
  133.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  134.         } catch (ResetPasswordExceptionInterface $e) {
  135.             $this->loggerInterface->critical($e);
  136.             // If you want to tell the user why a reset email was not sent, uncomment
  137.             // the lines below and change the redirect to 'app_forgot_password_request'.
  138.             // Caution: This may reveal if a user is registered or not.
  139.             //
  140.             // $this->addFlash('reset_password_error', sprintf(
  141.             //     '%s - %s',
  142.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  143.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  144.             // ));
  145.             return $this->redirectToRoute('app_check_email');
  146.         }
  147.         /*
  148.         $email = (new TemplatedEmail())
  149.             ->from(new Address('triwuu@triwuu.com', 'Triwuu'))
  150.             ->to($user->getEmail())
  151.             ->subject($translator->trans('general.reset_password.email_subject'))
  152.             ->htmlTemplate('reset_password/email.html.twig')
  153.             ->context([
  154.                 'resetToken' => $resetToken,
  155.                 'fullname' => $user->getName() . ' ' . $user->getSurname(),
  156.             ]);
  157.             $mailer->send($email);
  158.         */
  159.         $locale 'es';
  160.         if(!is_null($user) && !is_null($user->getLanguage()) && !is_null($user->getLanguage()->getKey())){
  161.             $locale $user->getLanguage()->getKey();
  162.         }
  163.         $this->loggerInterface->debug("Sending email for reset Password", ["locale" => $locale]);
  164.         $this->notificationService->sendNotification(Notification::ON_RESET_PASSWORD$user->getId(), [
  165.             '%fullname%' => $user->getName() . ' ' $user->getSurname(),
  166.             '%url%' => $this->generateUrl('app_reset_password', ['token' => $resetToken->getToken()], UrlGeneratorInterface::ABSOLUTE_URL),
  167.             '%expireString%' => $translator->trans(
  168.                 "general.reset_password.link_will_expire_in"
  169.                 [
  170.                     '%expiresAt%' => $resetToken->getExpiresAt()->format('H:i')
  171.                 ], 
  172.                 'messages'
  173.                 $locale
  174.             )
  175.         ], []);
  176.         // Store the token object in session for retrieval in check-email route.
  177.         $this->setTokenObjectInSession($resetToken);
  178.         return $this->redirectToRoute('app_check_email');
  179.     }
  180. }