src/Controller/Login/ResetPasswordController.php line 47

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Login;
  3. use App\Entity\User;
  4. use Symfony\Component\Mime\Address;
  5. use App\Form\ChangePasswordFormType;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use App\Form\ResetPasswordRequestFormType;
  8. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\Mailer\MailerInterface;
  11. use Symfony\Component\Security\Core\Security;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Component\HttpFoundation\RedirectResponse;
  15. use Symfony\Contracts\Translation\TranslatorInterface;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  18. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  20. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  21. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  22. // https://symfony.com/doc/5.4/security/passwords.html#reset-password
  23. /**
  24.  * @Route("/reset-password")
  25.  */
  26. class ResetPasswordController extends AbstractController
  27. {
  28.     use ResetPasswordControllerTrait;
  29.     private ResetPasswordHelperInterface $resetPasswordHelper;
  30.     private EntityManagerInterface $entityManager;
  31.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManager)
  32.     {
  33.         $this->resetPasswordHelper $resetPasswordHelper;
  34.         $this->entityManager $entityManager;
  35.     }
  36.     /**
  37.      * Display & process form to request a password reset.
  38.      *
  39.      * @Route("", name="app_forgot_password_request")
  40.      */
  41.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  42.     {
  43.         $form $this->createForm(ResetPasswordRequestFormType::class);
  44.         $form->handleRequest($request);
  45.         if ($form->isSubmitted() && $form->isValid()) {
  46.             return $this->processSendingPasswordResetEmail(
  47.                 $form->get('email')->getData(),
  48.                 $mailer,
  49.                 $translator
  50.             );
  51.         }
  52.         return $this->render('login/reset_password/request.html.twig', [
  53.             'requestForm' => $form->createView(),
  54.         ]);
  55.     }
  56.     /**
  57.      * Confirmation page after a user has requested a password reset.
  58.      *
  59.      * @Route("/check-email", name="app_check_email")
  60.      */
  61.     public function checkEmail(): Response
  62.     {
  63.         // Generate a fake token if the user does not exist or someone hit this page directly.
  64.         // This prevents exposing whether or not a user was found with the given email address or not
  65.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  66.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  67.         }
  68.         return $this->render('login/reset_password/check_email.html.twig', [
  69.             'resetToken' => $resetToken,
  70.         ]);
  71.     }
  72.     /**
  73.      * Validates and process the reset URL that the user clicked in their email.
  74.      *
  75.      * @Route("/reset/{token}", name="app_reset_password")
  76.      */
  77.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  78.     {
  79.         if ($token) {
  80.             // We store the token in session and remove it from the URL, to avoid the URL being
  81.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  82.             $this->storeTokenInSession($token);
  83.             return $this->redirectToRoute('app_reset_password');
  84.         }
  85.         $token $this->getTokenFromSession();
  86.         if (null === $token) {
  87.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  88.         }
  89.         try {
  90.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  91.         } catch (ResetPasswordExceptionInterface $e) {
  92.             $this->addFlash('reset_password_error'sprintf(
  93.                 '%s - %s',
  94.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  95.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  96.             ));
  97.             return $this->redirectToRoute('app_forgot_password_request');
  98.         }
  99.         // The token is valid; allow the user to change their password.
  100.         $form $this->createForm(ChangePasswordFormType::class, null, [
  101.             'isLogged' => false,
  102.         ]);
  103.         $form->handleRequest($request);
  104.         if ($form->isSubmitted() && $form->isValid()) {
  105.             // A password reset token should be used only once, remove it.
  106.             $this->resetPasswordHelper->removeResetRequest($token);
  107.             // Encode(hash) the plain password, and set it.
  108.             $encodedPassword $userPasswordHasher->hashPassword(
  109.                 $user,
  110.                 $form->get('plainPassword')->getData()
  111.             );
  112.             $user->setPassword($encodedPassword);
  113.             $this->entityManager->flush();
  114.             // The session is cleaned up after the password has been changed.
  115.             $this->cleanSessionAfterReset();
  116.             $msg $translator->trans('reset_password.flash.success', [], 'security');
  117.             $this->addFlash('info'$msg);
  118.             return $this->redirectToRoute('app_home');
  119.         }
  120.         return $this->render('login/reset_password/reset.html.twig', [
  121.             'resetForm' => $form->createView(),
  122.         ]);
  123.     }
  124.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  125.     {
  126.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  127.             'email' => $emailFormData,
  128.         ]);
  129.         // Do not reveal whether a user account was found or not.
  130.         if (!$user) {
  131.             return $this->redirectToRoute('app_check_email');
  132.         }
  133.         try {
  134.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  135.         } catch (ResetPasswordExceptionInterface $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.         $email = (new TemplatedEmail())
  148.             ->from(new Address($this->getParameter('app.mail_from_email'), $this->getParameter('app.mail_from_name')))
  149.             ->to($user->getEmail())
  150.             ->subject('Your password reset request')
  151.             ->htmlTemplate('login/reset_password/email.html.twig')
  152.             ->context([
  153.                 'resetToken' => $resetToken,
  154.             ])
  155.         ;
  156.         $mailer->send($email);
  157.         // Store the token object in session for retrieval in check-email route.
  158.         $this->setTokenObjectInSession($resetToken);
  159.         return $this->redirectToRoute('app_check_email');
  160.     }
  161.     /**
  162.      * @IsGranted("ROLE_USER")
  163.      * @Route("/update", name="app_update_password")
  164.      */
  165.     public function udpatePassword(Request $requestUserPasswordHasherInterface $userPasswordHasherSecurity $securityTranslatorInterface $translator): response
  166.     {
  167.    
  168.         $user $security->getUser(); // 
  169.         if (!$user || !$user instanceof User) {
  170.             throw $this->createAccessDeniedException('You are not logged!!');
  171.         }
  172.         $form $this->createForm(ChangePasswordFormType::class, null, [
  173.             'isLogged' => true,
  174.         ]);
  175.         $form->handleRequest($request);
  176.         if ($form->isSubmitted() && $form->isValid()) {
  177.             // Encode(hash) the plain password, and set it.
  178.             $encodedPassword $userPasswordHasher->hashPassword(
  179.                 $user,
  180.                 $form->get('plainPassword')->getData()
  181.             );
  182.             $user->setPassword($encodedPassword);
  183.             $this->entityManager->flush();
  184.             // The session is cleaned up after the password has been changed.
  185.             //$this->cleanSessionAfterReset();
  186.             $msg $translator->trans('reset_password.flash.success', [], 'security');
  187.             $this->addFlash('info'$msg);
  188.             //return $this->guardHandler->authenticateUserAndHandleSuccess($user, $request, $this->authenticator, 'main');
  189.             return $this->redirectToRoute('app_home');
  190.         }
  191.         return $this->render('login/reset_password/reset.html.twig', [
  192.             'resetForm' => $form->createView(),
  193.         ]);
  194.     }
  195. }