src/Controller/ResetPasswordController.php line 42

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\MailjetApiRepository;
  7. use App\Services\CustomMailer;
  8. use App\Services\MailjetApiEncryptionService;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Mailer\Mailer;
  17. use Symfony\Component\Mime\Address;
  18. use Symfony\Component\Mime\Email;
  19. use Symfony\Component\Mime\Message;
  20. use Symfony\Component\Routing\Annotation\Route;
  21. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  22. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  23. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  24. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  25. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  26. use Twig\Environment;
  27. #[Route(path'/reset-password')]
  28. class ResetPasswordController extends AbstractController
  29. {
  30.     use ResetPasswordControllerTrait;
  31.     private ResetPasswordHelperInterface $resetPasswordHelper;
  32.     private TokenStorageInterface $tokenStorage;
  33.     private string $notAnswerMail;
  34.     private Mailer $mailer;
  35.     private Environment $twig;
  36.     private MailjetApiEncryptionService $mailjetApiEncryptionService;
  37.     public function __construct(Environment $twigCustomMailer $mailerResetPasswordHelperInterface $resetPasswordHelperTokenStorageInterface $tokenStorageParameterBagInterface $parameterBagMailjetApiEncryptionService $mailjetApiEncryptionServiceMailjetApiRepository $mailjetApiRepository)
  38.     {
  39.         $this->resetPasswordHelper $resetPasswordHelper;
  40.         $this->tokenStorage $tokenStorage;
  41.         $this->twig $twig;
  42.         $this->notAnswerMail $parameterBag->get('not_answer_mail');
  43.         $this->mailjetApiEncryptionService $mailjetApiEncryptionService;
  44.         $mailjetApi $this->mailjetApiEncryptionService->decryptMailjetApi($mailjetApiRepository->findOneBy(['id' => '2']));
  45.         $this->mailer $mailer->getMailer($mailjetApi->getUsername(), $mailjetApi->getPassword());
  46.     }
  47.     /**
  48.      * Display & process form to request a password reset.
  49.      *
  50.      */
  51.     #[Route(path''name'app_forgot_password_request')]
  52.     public function request(Request $request): Response
  53.     {
  54.         if ($email $request->get('email')) {
  55.             $this->destroySession($request);
  56.         }
  57.         $form $this->createForm(ResetPasswordRequestFormType::class);
  58.         $form->handleRequest($request);
  59.         if ($form->isSubmitted() && ($form->isValid() || $form->get('email')->getData()) && $request->getMethod() == 'POST') {
  60.             return $this->processSendingPasswordResetEmail($form->get('email')->getData());
  61.         }
  62.         return $this->render('reset_password/request.html.twig', [
  63.             'requestForm' => $form->createView(),
  64.             'email' => $email,
  65.         ]);
  66.     }
  67.     /**
  68.      * Confirmation page after a user has requested a password reset.
  69.      *
  70.      */
  71.     #[Route(path'/check-email'name'app_check_email')]
  72.     public function checkEmail(Request $request): Response
  73.     {
  74.         $this->destroySession($request);
  75.         // Generate a fake token if the user does not exist or someone hit this page directly.
  76.         // This prevents exposing whether or not a user was found with the given email address or not
  77.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  78.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  79.         }
  80.         return $this->render('reset_password/check_email.html.twig', [
  81.             'resetToken' => $resetToken,
  82.         ]);
  83.     }
  84.     /**
  85.      * Validates and process the reset URL that the user clicked in their email.
  86.      *
  87.      */
  88.     #[Route(path'/reset/{token}'name'app_reset_password')]
  89.     public function reset(Request $requestUserPasswordEncoderInterface $passwordEncoderstring $token null): Response
  90.     {
  91.         if ($token) {
  92.             // We store the token in session and remove it from the URL, to avoid the URL being
  93.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  94.             $this->storeTokenInSession($token);
  95.             return $this->redirectToRoute('app_reset_password');
  96.         }
  97.         $token $this->getTokenFromSession();
  98.         if (null === $token) {
  99.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  100.         }
  101.         try {
  102.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  103.         } catch (ResetPasswordExceptionInterface $e) {
  104.             $this->addFlash('reset_password_error'sprintf(
  105.                 'Un problème est survenu lors de la validation de votre demande de réinitialisation - %s',
  106.                 $e->getReason()
  107.             ));
  108.             return $this->redirectToRoute('app_forgot_password_request');
  109.         }
  110.         // The token is valid; allow the user to change their password.
  111.         $form $this->createForm(ChangePasswordFormType::class);
  112.         $form->handleRequest($request);
  113.         if ($form->isSubmitted() && $form->isValid()) {
  114.             // A password reset token should be used only once, remove it.
  115.             $this->resetPasswordHelper->removeResetRequest($token);
  116.             // Encode the plain password, and set it.
  117.             $encodedPassword $passwordEncoder->encodePassword(
  118.                 $user,
  119.                 $form->get('plainPassword')->getData()
  120.             );
  121.             $user->setPassword($encodedPassword);
  122.             $this->getDoctrine()->getManager()->flush();
  123.             // The session is cleaned up after the password has been changed.
  124.             $this->cleanSessionAfterReset();
  125.             if ($this->getUser()) {
  126.                 return $this->redirectToRoute('app_logout');
  127.             }
  128.             return $this->redirectToRoute('app_home');
  129.         }
  130.         return $this->render('reset_password/reset.html.twig', [
  131.             'resetForm' => $form->createView(),
  132.         ]);
  133.     }
  134.     private function processSendingPasswordResetEmail(string $emailFormData): RedirectResponse
  135.     {
  136.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  137.             'email' => $emailFormData,
  138.         ]);
  139.         // Do not reveal whether a user account was found or not.
  140.         if (!$user) {
  141.             return $this->redirectToRoute('app_check_email');
  142.         }
  143.         try {
  144.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  145.         } catch (ResetPasswordExceptionInterface $e) {
  146.             // If you want to tell the user why a reset email was not sent, uncomment
  147.             // the lines below and change the redirect to 'app_forgot_password_request'.
  148.             // Caution: This may reveal if a user is registered or not.
  149.             //
  150.             // $this->addFlash('reset_password_error', sprintf(
  151.             //     'There was a problem handling your password reset request - %s',
  152.             //     $e->getReason()
  153.             // ));
  154.             return $this->redirectToRoute('app_check_email');
  155.         }
  156.         $template $this->twig->render('reset_password/email.html.twig', [
  157.             'resetToken' => $resetToken,
  158.         ]);
  159.         $email = (new Email())
  160.             ->from(new Address($this->notAnswerMail'L\'agence expert'))
  161.             ->to($user->getEmail())
  162.             ->subject('Réinitialisation du mot de passe de votre espace web l’agence expert.')
  163.             ->html($template)
  164.         ;
  165.         $this->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.     private function destroySession(Request $request)
  171.     {
  172.         if ($this->getUser()) {
  173.             $this->tokenStorage->setToken(null);
  174.             $request->getSession()->invalidate();
  175.         }
  176.     }
  177.     #[Route(path'/send-mail'name'send-mail')]
  178.     public function sendEmail(): JsonResponse
  179.     {
  180.         $template $this->twig->render('reset_password/_email.html.twig', [
  181.             'resetToken' => 'TEST',
  182.         ]);
  183.         $email = (new Email())
  184.             ->from(new Address($this->notAnswerMail'l\'agence.expert'))
  185.             //->to($user->getEmail())
  186.             ->to('testdevclaire@yopmail.com')
  187.             ->subject('Your password reset request')
  188.             ->html($template)
  189.         ;
  190.          //dd($template, $email);
  191.         try {
  192.             $result $this->mailer->send($email);
  193.         } catch (\Exception $exception) {
  194.             $result $exception->getMessage();
  195.         }
  196.         return $this->json(['send' => $result]);
  197.     }
  198. }