src/Controller/ResetPasswordController.php line 40

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 App\Repository\UserRepository;
  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\PasswordHasher\Hasher\UserPasswordHasherInterface;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  19. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  21. #[Route('/reset-password')]
  22. class ResetPasswordController extends AbstractController
  23. {
  24.     use ResetPasswordControllerTrait;
  25.     public function __construct(
  26.         private ResetPasswordHelperInterface $resetPasswordHelper,
  27.         private EntityManagerInterface $entityManager,
  28.         private UserRepository $userRepository
  29.     ) {
  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.             $theUser $this->userRepository->findOneBy(['email' => $form->get('email')->getData()]);
  41.             if ($theUser) {
  42.                 if (in_array('ROLE_ADMIN'$theUser->getRoles()) || in_array('ROLE_STAFF'$theUser->getRoles())) {
  43.                     return $this->redirectToRoute('admin_app_forgot_password_request');
  44.                 }
  45.             }
  46.             return $this->processSendingPasswordResetEmail(
  47.                 $request,
  48.                 $form->get('email')->getData(),
  49.                 $mailer,
  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.         // 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('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.     public function reset(Request $requestUserPasswordHasherInterface $passwordHasherTranslatorInterface $translatorstring $token null): Response
  77.     {
  78.         if ($token) {
  79.             // We store the token in session and remove it from the URL, to avoid the URL being
  80.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  81.             $this->storeTokenInSession($token);
  82.             return $this->redirectToRoute('app_reset_password');
  83.         }
  84.         $token $this->getTokenFromSession();
  85.         if (null === $token) {
  86.             return $this->redirectToRoute('app_login');
  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);
  101.         $form->handleRequest($request);
  102.         if ($form->isSubmitted() && $form->isValid()) {
  103.             // Prevent a list of passwords patterns
  104.             $preventedPasswords array_merge(RegistrationController::PREVENTED_PASSWORDSrange(19002050));
  105.             foreach ($preventedPasswords as $pattern) {
  106.                 if (str_contains($form->get('password')->getData(), $pattern)) {
  107.                     $this->addFlash(
  108.                         'password_error_for_reset''Your password contains unsecure characteristics (dates, patterns, or popular phrases), please choose another password.'
  109.                     );
  110.                     return $this->redirectToRoute('app_reset_password');
  111.                 }
  112.             }
  113.             // A password reset token should be used only once, remove it.
  114.             $this->resetPasswordHelper->removeResetRequest($token);
  115.             // Encode(hash) the plain password, and set it.
  116.             $encodedPassword $passwordHasher->hashPassword(
  117.                 $user,
  118.                 $form->get('password')->getData()
  119.             );
  120.             $user->setPassword($encodedPassword);
  121.             $this->entityManager->flush();
  122.             // The session is cleaned up after the password has been changed.
  123.             $this->cleanSessionAfterReset();
  124.             return $this->render('reset_password/reset_password_confirmation.html.twig');
  125.             /* return $this->redirectToRoute('app_login'); */
  126.         }
  127.         return $this->render('reset_password/reset.html.twig', [
  128.             'resetForm' => $form->createView(),
  129.         ]);
  130.     }
  131.     private function processSendingPasswordResetEmail(Request $requeststring $emailFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  132.     {
  133.         $user $this->entityManager->getRepository(User::class)->findOneBy([
  134.             'email' => $emailFormData,
  135.         ]);
  136.         $logoUrl $request->getScheme().'://'.$request->getHttpHost().$request->getBasePath().'/assets/img/Consort/Consort1-email.png';
  137.         // Do not reveal whether a user account was found or not.
  138.         if (!$user) {
  139.             return $this->redirectToRoute('app_check_email');
  140.         }
  141.         try {
  142.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  143.         } catch (ResetPasswordExceptionInterface) {
  144.             // If you want to tell the user why a reset email was not sent, uncomment
  145.             // the lines below and change the redirect to 'app_forgot_password_request'.
  146.             // Caution: This may reveal if a user is registered or not.
  147.             //
  148.             // $this->addFlash('reset_password_error', sprintf(
  149.             //     '%s - %s',
  150.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  151.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  152.             // ));
  153.             return $this->redirectToRoute('app_check_email');
  154.         }
  155.         $email = (new TemplatedEmail())
  156.             ->from(new Address('trading@sdsrepo.io''Consort1 - SDSrepo.io'))
  157.             ->to($user->getEmail())
  158.             ->subject('Your password reset request')
  159.             ->htmlTemplate('reset_password/email.html.twig')
  160.             ->context([
  161.                 'resetToken' => $resetToken,
  162.                 'imgUrl' => $logoUrl,
  163.             ])
  164.         ;
  165.         $mailer->send($email);
  166.         // Store the token object in session for retrieval in check-email route.
  167.         $this->setTokenObjectInSession($resetToken);
  168.         return $this->redirectToRoute('app_check_email');
  169.     }
  170. }