src/Controller/ResetPasswordController.php line 119

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  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("/reset-password")
  22.  */
  23. class ResetPasswordController extends AbstractController {
  24.     use ResetPasswordControllerTrait;
  25.     private $resetPasswordHelper;
  26.     private $entityManager;
  27.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManager) {
  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.      */
  36.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response {
  37.         $form $this->createForm(ResetPasswordRequestFormType::class);
  38.         $form->handleRequest($request);
  39.         if ($form->isSubmitted() && $form->isValid()) {
  40.             return $this->processSendingPasswordResetEmail(
  41.                             $form->get('emailCompte')->getData(),
  42.                             $mailer,
  43.                             $translator
  44.             );
  45.         }
  46.         return $this->render('reset_password/request.html.twig', [
  47.                     'requestForm' => $form->createView(),
  48.         ]);
  49.     }
  50.     /**
  51.      * Confirmation page after a user has requested a password reset.
  52.      *
  53.      * @Route("/check-email", name="app_check_email")
  54.      */
  55.     public function checkEmail(): Response {
  56.         // Generate a fake token if the user does not exist or someone hit this page directly.
  57.         // This prevents exposing whether or not a user was found with the given email address or not
  58.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  59.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  60.         }
  61.         return $this->render('reset_password/check_email.html.twig', [
  62.                     'resetToken' => $resetToken,
  63.         ]);
  64.     }
  65.     /**
  66.      * Validates and process the reset URL that the user clicked in their email.
  67.      *
  68.      * @Route("/changePassword", name="app_changePassword")
  69.      */
  70.     public function changePassword(Request $requestUserPasswordHasherInterface $userPasswordHasher, \App\Services\AppSevices $service): Response {
  71.         $user $service->getUser();
  72.         // The token is valid; allow the user to change their password.
  73.         $form $this->createForm(ChangePasswordFormType::class);
  74.         $form->handleRequest($request);
  75.         if ($form->isSubmitted() && $form->isValid()) {
  76.             // A password reset token should be used only once, remove it.
  77.            // $this->resetPasswordHelper->removeResetRequest($token);
  78.             // Encode(hash) the plain password, and set it.
  79.             $encodedPassword $userPasswordHasher->hashPassword(
  80.                     $user,
  81.                     $form->get('plainPassword')->getData()
  82.             );
  83.             $user->setVerfier(true);
  84.             $user->setPassword($encodedPassword);
  85.             $this->entityManager->flush();
  86.             // The session is cleaned up after the password has been changed.
  87.             $this->cleanSessionAfterReset();
  88.             return $this->redirectToRoute('app_login');
  89.         }
  90.         return $this->render('reset_password/reset.html.twig', [
  91.                     'resetForm' => $form->createView(),
  92.         ]);
  93.     }
  94.     /**
  95.      * Validates and process the reset URL that the user clicked in their email.
  96.      *
  97.      * @Route("/reset/{token}", name="app_reset_password")
  98.      */
  99.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response {
  100.         if ($token) {
  101.             // We store the token in session and remove it from the URL, to avoid the URL being
  102.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  103.             $this->storeTokenInSession($token);
  104.             return $this->redirectToRoute('app_reset_password');
  105.         }
  106.         $token $this->getTokenFromSession();
  107.         if (null === $token) {
  108.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  109.         }
  110.         try {
  111.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  112.         } catch (ResetPasswordExceptionInterface $e) {
  113.             $this->addFlash('reset_password_error'sprintf(
  114.                             '%s - %s',
  115.                             $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  116.                             $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  117.             ));
  118.             return $this->redirectToRoute('app_forgot_password_request');
  119.         }
  120.         // The token is valid; allow the user to change their password.
  121.         $form $this->createForm(ChangePasswordFormType::class);
  122.         $form->handleRequest($request);
  123.         if ($form->isSubmitted() && $form->isValid()) {
  124.             // A password reset token should be used only once, remove it.
  125.             $this->resetPasswordHelper->removeResetRequest($token);
  126.             // Encode(hash) the plain password, and set it.
  127.             $encodedPassword $userPasswordHasher->hashPassword(
  128.                     $user,
  129.                     $form->get('plainPassword')->getData()
  130.             );
  131.             $user->setVerfier(true);
  132.             $user->setPassword($encodedPassword);
  133.             $this->entityManager->flush();
  134.             // The session is cleaned up after the password has been changed.
  135.             $this->cleanSessionAfterReset();
  136.             return $this->redirectToRoute('app_login');
  137.         }
  138.         return $this->render('reset_password/reset.html.twig', [
  139.                     'resetForm' => $form->createView(),
  140.         ]);
  141.     }
  142.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse {
  143.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  144.             'emailCompte' => $emailFormData,
  145.         ]);
  146.         // Do not reveal whether a user account was found or not.
  147.         if (!$user) {
  148.             return $this->redirectToRoute('app_check_email');
  149.         }
  150.         try {
  151.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  152.         } catch (ResetPasswordExceptionInterface $e) {
  153.             $this->addFlash('reset_password_error'sprintf(
  154.                             '%s - %s',
  155.                             $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  156.                             $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  157.             ));
  158.             return $this->redirectToRoute('app_check_email');
  159.         }
  160.         $email = (new TemplatedEmail())
  161.                 ->from(new Address('amicale.cga@cga.gov.tn''Amicale'))
  162.                 ->to($user->getEmailCompte())
  163.                 ->subject('Your password reset request')
  164.                 ->htmlTemplate('reset_password/email.html.twig')
  165.                 ->context([
  166.             'resetToken' => $resetToken,
  167.                 ])
  168.         ;
  169. //dump($email);die();
  170.         $mailer->send($email);
  171.         // Store the token object in session for retrieval in check-email route.
  172.         $this->setTokenObjectInSession($resetToken);
  173.         return $this->redirectToRoute('app_check_email');
  174.     }
  175. }