src/Controller/App/ResetPasswordController.php line 48

Open in your IDE?
  1. <?php
  2. namespace App\Controller\App;
  3. use App\Entity\User;
  4. use App\Form\ChangePasswordFormType;
  5. use App\Form\ResetPasswordRequestFormType;
  6. use App\Service\Notification\MailService;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\RedirectResponse;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Mailer\MailerInterface;
  14. use Symfony\Component\Mime\Address;
  15. use Symfony\Component\Mime\Email;
  16. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Contracts\Translation\TranslatorInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  20. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  21. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  22. /**
  23.  * @Route("/reset-password")
  24.  */
  25. class ResetPasswordController extends AbstractController
  26. {
  27.     use ResetPasswordControllerTrait;
  28.     private $resetPasswordHelper;
  29.     private $entityManager;
  30.     private $mailService;
  31.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerMailService $mailService)
  32.     {
  33.         $this->resetPasswordHelper $resetPasswordHelper;
  34.         $this->entityManager $entityManager;
  35.         $this->mailService $mailService;
  36.     }
  37.     /**
  38.      * Display & process form to request a password reset.
  39.      *
  40.      * @Route("", name="app_forgot_password_request")
  41.      */
  42.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  43.     {
  44.         $form $this->createForm(ResetPasswordRequestFormType::class);
  45.         $form->handleRequest($request);
  46.         if ($form->isSubmitted() && $form->isValid()) {
  47.             return $this->processSendingPasswordResetEmail(
  48.                 $form->get('email')->getData(),
  49.                 $mailer,
  50.                 $translator
  51.             );
  52.         }
  53.         return $this->render('app/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.      */
  62.     public function checkEmail(): Response
  63.     {
  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('app/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.      */
  78.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  79.     {
  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 $userPasswordHasher->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('login');
  116.         }
  117.         return $this->render('app/reset_password/reset.html.twig', [
  118.             'resetForm' => $form->createView(),
  119.         ]);
  120.     }
  121.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  122.     {
  123.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  124.             'email' => $emailFormData,
  125.         ]);
  126.         // Do not reveal whether a user account was found or not.
  127.        /* if (!$user) {
  128.             return $this->redirectToRoute('app_check_email');
  129.         }*/
  130.         try {
  131.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  132.         } catch (ResetPasswordExceptionInterface $e) {
  133.             // If you want to tell the user why a reset email was not sent, uncomment
  134.             // the lines below and change the redirect to 'app_forgot_password_request'.
  135.             // Caution: This may reveal if a user is registered or not.
  136.             //
  137.             // $this->addFlash('reset_password_error', sprintf(
  138.             //     '%s - %s',
  139.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  140.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  141.             // ));
  142.             return $this->redirectToRoute('app_check_email');
  143.         }
  144.         $this->mailService->send('resetPassword', array('resetToken' => $resetToken), $user->getEmail(),'Your password reset request');
  145.         // Store the token object in session for retrieval in check-email route.
  146.         $this->setTokenObjectInSession($resetToken);
  147.         return $this->redirectToRoute('app_check_email');
  148.     }
  149. }