src/Controller/Authentication/ResetPasswordController.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Authentication;
  3. use App\Entity\User\User;
  4. use App\Form\Authentication\ChangePasswordFormType;
  5. use App\Form\Authentication\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. #[Route('/reset-password')]
  21. class ResetPasswordController extends AbstractController
  22. {
  23.     use ResetPasswordControllerTrait;
  24.     private ResetPasswordHelperInterface $resetPasswordHelper;
  25.     private EntityManagerInterface $entityManager;
  26.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManager)
  27.     {
  28.         $this->resetPasswordHelper $resetPasswordHelper;
  29.         $this->entityManager $entityManager;
  30.     }
  31.     /**
  32.      * Display & process form to request a password reset.
  33.      */
  34.     #[Route(''name'app_forgot_password_request')]
  35.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  36.     {
  37.         $form $this->createForm(ResetPasswordRequestFormType::class);
  38.         $form->handleRequest($request);
  39.         if ($form->isSubmitted() && $form->isValid()) {
  40.             return $this->processSendingPasswordResetEmail(
  41.                 $form->get('email')->getData(),
  42.                 $mailer,
  43.                 $translator
  44.             );
  45.         }
  46.         return $this->render('common/authentication/request_reset.html.twig', [
  47.             'requestForm' => $form->createView(),
  48.             'is_show_chat' => 0,
  49.         ]);
  50.     }
  51.     /**
  52.      * Validates and process the reset URL that the user clicked in their email.
  53.      */
  54.     #[Route('/reset/{token}'name'app_reset_password')]
  55.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  56.     {
  57.         if ($token) {
  58.             // We store the token in session and remove it from the URL, to avoid the URL being
  59.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  60.             $this->storeTokenInSession($token);
  61.             return $this->redirectToRoute('app_reset_password');
  62.         }
  63.         $token $this->getTokenFromSession();
  64.         if (null === $token) {
  65.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  66.         }
  67.         try {
  68.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  69.         } catch (ResetPasswordExceptionInterface $e) {
  70.             $this->addFlash('reset_password_error'sprintf(
  71.                 '%s - %s',
  72.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  73.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  74.             ));
  75.             return $this->redirectToRoute('app_forgot_password_request');
  76.         }
  77.         // The token is valid; allow the user to change their password.
  78.         $form $this->createForm(ChangePasswordFormType::class);
  79.         $form->handleRequest($request);
  80.         if ($form->isSubmitted() && $form->isValid()) {
  81.             // A password reset token should be used only once, remove it.
  82.             $this->resetPasswordHelper->removeResetRequest($token);
  83.             // Encode(hash) the plain password, and set it.
  84.             $encodedPassword $userPasswordHasher->hashPassword(
  85.                 $user,
  86.                 $form->get('plainPassword')->getData()
  87.             );
  88.             $user->setPassword($encodedPassword);
  89.             $this->entityManager->flush();
  90.             // The session is cleaned up after the password has been changed.
  91.             $this->cleanSessionAfterReset();
  92.             return $this->redirectToRoute('app_user_dashboard');
  93.         }
  94.         return $this->render('common/authentication/reset.html.twig', [
  95.             'resetForm' => $form->createView(),
  96.             'is_show_chat' => 0,
  97.         ]);
  98.     }
  99.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  100.     {
  101.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  102.             'email' => $emailFormData,
  103.         ]);
  104.         // Do not reveal whether a user account was found or not.
  105.         if (!$user) {
  106.             return $this->redirectToRoute('app_forgot_password_request');
  107.         }
  108.         try {
  109.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  110.         } catch (ResetPasswordExceptionInterface $e) {
  111.             $this->addFlash('reset_password_error'sprintf(
  112.                  '%s - %s',
  113.                  $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE),
  114.                  $translator->trans($e->getReason())
  115.              ));
  116.             return $this->redirectToRoute('app_forgot_password_request');
  117.         }
  118.         $email = (new TemplatedEmail())
  119.             ->from(new Address($this->getParameter('mail.noreply'), 'Platforma Edukacyjna BOT'))
  120.             ->to($user->getEmail())
  121.             ->subject('Potwierdź zmianę hasła')
  122.             ->htmlTemplate('_emails/authentication/reset_password.html.twig')
  123.             ->context([
  124.                 'resetToken' => $resetToken,
  125.             ])
  126.         ;
  127.         $mailer->send($email);
  128.         // Store the token object in session for retrieval in check-email route.
  129.         $this->setTokenObjectInSession($resetToken);
  130.         $this->addFlash('reset_password_info''Wysłano email z linkiem do zmiany hasła. Jeśli nie otrzymałeś wiadomosci, zaczekja kilka minut i/lub sprawdź folder SPAM.');
  131.         return $this->redirectToRoute('login');
  132.     }
  133. }