src/Controller/ResetPasswordController.php line 68

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Constants\GeneralConstants;
  4. use App\Entity\User;
  5. use App\Form\ChangePasswordFormType;
  6. use App\Form\ResetPasswordRequestFormType;
  7. use App\Repository\UserRepository;
  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\Routing\Annotation\Route;
  16. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  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. /**
  22.  * @Route("/reset-password")
  23.  */
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     private $resetPasswordHelper;
  28.     private $translator;
  29.     private $userRepository;
  30.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperUserRepository $userRepositoryTranslatorInterface $translator)
  31.     {
  32.         $this->resetPasswordHelper $resetPasswordHelper;
  33.         $this->userRepository $userRepository;
  34.         $this->translator $translator;
  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 $mailer): 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.             );
  50.         }
  51.         return $this->render('reset_password/request.html.twig', [
  52.             'requestForm' => $form->createView(),
  53.         ]);
  54.     }
  55.     /**
  56.      * Display & process form to request a password reset for agents.
  57.      * @Route("/reset-password-agent", name="app_agent_forgot_password_request")
  58.      */
  59.     public function agentRequest(Request $requestMailerInterface $mailer): Response
  60.     {
  61.         $form $this->createForm(ResetPasswordRequestFormType::class);
  62.         $form->handleRequest($request);
  63.         if ($form->isSubmitted() && $form->isValid()) {
  64.             return $this->processSendingPasswordResetEmail(
  65.                 $form->get('email')->getData(),
  66.                 $mailer,
  67.                 true
  68.             );
  69.         }
  70.         return $this->render('reset_password/request.html.twig', [
  71.             'requestForm' => $form->createView(),
  72.             'agent' => true
  73.         ]);
  74.     }
  75.     /**
  76.      * Confirmation page after a user has requested a password reset.
  77.      *
  78.      * @Route("/check-email", name="app_check_email")
  79.      */
  80.     public function checkEmail(): Response
  81.     {
  82.         // We prevent users from directly accessing this page
  83.         if (!$this->canCheckEmail()) {
  84.             return $this->redirectToRoute('app_forgot_password_request');
  85.         }
  86.         return $this->render('reset_password/check_email.html.twig', [
  87.             'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  88.             'email' => 'recuperare il dato' ]);
  89.     }
  90.     /**
  91.      * Validates and process the reset URL that the user clicked in their email.
  92.      *
  93.      * @Route("/reset/{token}", name="app_reset_password")
  94.      */
  95.     public function reset(Request $requestUserPasswordEncoderInterface $passwordEncoderstring $token null): Response
  96.     {
  97.         if ($token) {
  98.             // We store the token in session and remove it from the URL, to avoid the URL being
  99.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  100.             $this->storeTokenInSession($token);
  101.             return $this->redirectToRoute('app_reset_password');
  102.         }
  103.         $token $this->getTokenFromSession();
  104.         if (null === $token) {
  105.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  106.         }
  107.         try {
  108.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  109.         } catch (ResetPasswordExceptionInterface $e) {
  110.             $this->addFlash('reset_password_error'sprintf(
  111.                 "C'รจ stato un problema di validazione richiesta reset password - %s",
  112.                 $e->getReason()
  113.             ));
  114.             return $this->redirectToRoute('app_forgot_password_request');
  115.         }
  116.         // The token is valid; allow the user to change their password.
  117.         $form $this->createForm(ChangePasswordFormType::class);
  118.         $form->handleRequest($request);
  119.         if ($form->isSubmitted() && $form->isValid()) {
  120.             // A password reset token should be used only once, remove it.
  121.             $this->resetPasswordHelper->removeResetRequest($token);
  122.             // Encode the plain password, and set it.
  123.             $encodedPassword $passwordEncoder->encodePassword(
  124.                 $user,
  125.                 $form->get('plainPassword')->getData()
  126.             );
  127.             $user->setPassword($encodedPassword);
  128.             $this->getDoctrine()->getManager()->flush();
  129.             // The session is cleaned up after the password has been changed.
  130.             $this->cleanSessionAfterReset();
  131.             return $this->render('reset_password/reset_ok.html.twig', [
  132.                 'ok' => $this->translator->trans("frontoffice.reset_password_ok") ]);
  133.             //return $this->redirectToRoute('app_login');
  134.         }
  135.         return $this->render('reset_password/reset.html.twig', [
  136.             'resetForm' => $form->createView(),
  137.         ]);
  138.     }
  139.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer$agent false): RedirectResponse
  140.     {
  141.         $users $this->userRepository->findUserByRole(($agent 'ROLE_AGENT' 'ROLE_CLIENT'), 'LIKE'falsefalse, ['email'=>$emailFormData]);
  142.         $user null;
  143.         if(count($users) >= 1) {
  144.             $user $users[0];
  145.         }
  146.         // Marks that you are allowed to see the app_check_email page.
  147.         $this->setCanCheckEmailInSession();
  148.         // Do not reveal whether a user account was found or not.
  149.         if (!$user) {
  150.             return $this->redirectToRoute('app_check_email');
  151.         }
  152.         try {
  153.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  154.         } catch (ResetPasswordExceptionInterface $e) {
  155.             $this->addFlash('reset_password_error'sprintf(
  156.                 $this->translator->trans("frontoffice.reset_password_error") . " - %s",
  157.                 $e->getReason()
  158.             ));
  159.             return $this->redirectToRoute('app_forgot_password_request');
  160.         }
  161.         $email = (new TemplatedEmail())
  162.             ->from(new Address(GeneralConstants::TDB_DEV_EMAILGeneralConstants::TDB_EXTENDED_COMPANY_NAME))
  163.             ->to($user->getEmail())
  164.             ->subject('Reset Password')
  165.             ->htmlTemplate('reset_password/email.html.twig')
  166.             ->context([
  167.                 'resetToken' => $resetToken,
  168.                 'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  169.             ])
  170.         ;
  171.         $mailer->send($email);
  172.         return $this->redirectToRoute('app_check_email');
  173.     }
  174. }