src/Controller/ResetPasswordController.php line 49

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Twig\Environment;
  4. use App\Entity\Uid;
  5. use Symfony\Component\Mime\Address;
  6. use App\Form\ChangePasswordFormType;
  7. use App\Repository\ParamsRepository;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use App\Form\ResetPasswordRequestFormType;
  10. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\Mailer\MailerInterface;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Component\HttpFoundation\RedirectResponse;
  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. /**
  22.  * @Route("/reset-password")
  23.  */
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     private $resetPasswordHelper;
  28.     private $entityManager;
  29.     private $paramsRepository;
  30.     private $twig;
  31.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperEntityManagerInterface $entityManagerParamsRepository $paramsRepositoryEnvironment $twig)
  32.     {
  33.         $this->resetPasswordHelper $resetPasswordHelper;
  34.         $this->entityManager $entityManager;
  35.         $this->paramsRepository $paramsRepository;
  36.         $this->twig $twig;
  37.     }
  38.     /**
  39.      * Display & process form to request a password reset.
  40.      *
  41.      * @Route("", name="app_forgot_password_request")
  42.      */
  43.     public function request(Request $requestMailerInterface $mailer): Response
  44.     {
  45.         $form $this->createForm(ResetPasswordRequestFormType::class);
  46.         $form->handleRequest($request);
  47.         if ($form->isSubmitted() && $form->isValid()) {
  48.             return $this->processSendingPasswordResetEmail(
  49.                 $form->get('email')->getData(),
  50.                 $mailer
  51.             );
  52.         }
  53.         return $this->render('reset_password/request.html.twig', [
  54.             'current' => 'reset_password',
  55.             'params' => $this->paramsRepository->findAll(),
  56.             'requestForm' => $form->createView(),
  57.         ]);
  58.     }
  59.     /**
  60.      * Confirmation page after a user has requested a password reset.
  61.      *
  62.      * @Route("/check-email", name="app_check_email")
  63.      */
  64.     public function checkEmail(): Response
  65.     {
  66.         // Generate a fake token if the user does not exist or someone hit this page directly.
  67.         // This prevents exposing whether or not a user was found with the given email address or not
  68.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  69.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  70.         }
  71.         return $this->render('reset_password/check_email.html.twig', [
  72.             'current' => 'reset_password',
  73.             'params' => $this->paramsRepository->findAll(),
  74.             'resetToken' => $resetToken,
  75.         ]);
  76.     }
  77.     /**
  78.      * Validates and process the reset URL that the user clicked in their email.
  79.      *
  80.      * @Route("/reset/{token}", name="app_reset_password")
  81.      */
  82.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherstring $token null): Response
  83.     {
  84.         if ($token) {
  85.             // We store the token in session and remove it from the URL, to avoid the URL being
  86.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  87.             $this->storeTokenInSession($token);
  88.             return $this->redirectToRoute('app_reset_password');
  89.         }
  90.         $token $this->getTokenFromSession();
  91.         if (null === $token) {
  92.             throw $this->createNotFoundException('Demande de mot de passe introuvable.');
  93.         }
  94.         try {
  95.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  96.         } catch (ResetPasswordExceptionInterface $e) {
  97.             $this->addFlash('reset_password_error'sprintf(
  98.                 'There was a problem validating your reset request - %s',
  99.                 $e->getReason()
  100.             ));
  101.             return $this->redirectToRoute('app_forgot_password_request');
  102.         }
  103.         // The token is valid; allow the user to change their password.
  104.         $form $this->createForm(ChangePasswordFormType::class);
  105.         $form->handleRequest($request);
  106.         if ($form->isSubmitted() && $form->isValid()) {
  107.             // A password reset token should be used only once, remove it.
  108.             $this->resetPasswordHelper->removeResetRequest($token);
  109.             // Encode(hash) the plain password, and set it.
  110.             $encodedPassword $userPasswordHasher->hashPassword(
  111.                 $user,
  112.                 $form->get('plainPassword')->getData()
  113.             );
  114.             $user->setPassword($encodedPassword);
  115.             $this->entityManager->flush();
  116.             $this->addFlash('success''Mot de passe ré-initialisé');
  117.             // The session is cleaned up after the password has been changed.
  118.             $this->cleanSessionAfterReset();
  119.             return $this->redirectToRoute('home');
  120.         }
  121.         return $this->render('reset_password/reset.html.twig', [
  122.             'current' => 'reset_password',
  123.             'params' => $this->paramsRepository->findAll(),
  124.             'resetForm' => $form->createView(),
  125.         ]);
  126.     }
  127.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  128.     {
  129.         $user $this->entityManager->getRepository(Uid::class)->findOneBy([
  130.             'email' => $emailFormData,
  131.         ]);
  132.         // Do not reveal whether a user account was found or not.
  133.         if (!$user) {
  134.             return $this->redirectToRoute('app_check_email');
  135.         }
  136.         try {
  137.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  138.         } catch (ResetPasswordExceptionInterface $e) {
  139.             // If you want to tell the user why a reset email was not sent, uncomment
  140.             // the lines below and change the redirect to 'app_forgot_password_request'.
  141.             // Caution: This may reveal if a user is registered or not.
  142.             //
  143.              $this->addFlash('reset_password_error'sprintf(
  144.                  'There was a problem handling your password reset request - %s',
  145.                  $e->getReason()
  146.              ));
  147.             return $this->redirectToRoute('app_check_email');
  148.         }
  149.         /*$email = (new TemplatedEmail())
  150.             ->from(new Address('no-reply@mazykkavinyles.fr', 'No reply mail'))
  151.             ->to($user->getEmail())
  152.             ->subject('Demande de changement de mot de passe')
  153.             ->htmlTemplate('reset_password/email.html.twig')
  154.             ->context([
  155.                 'resetToken' => $resetToken,
  156.             ])
  157.         ;
  158.         $mailer->send($email);*/
  159.         $parameters = [
  160.             'user' => $user,
  161.             'resetToken' => $resetToken,
  162.         ];
  163.         $headers "From:no-reply@mazykkavinyles.fr" "\r\n";
  164.         $headers .= "MIME-Version: 1.0" "\r\n";
  165.         $headers .= "Content-type:text/html;charset=UTF-8" "\r\n";
  166.         mail($user->getEmail(),"Demande de changement de mot de passe" ,$this->twig->render("reset_password/email.html.twig"$parameters),$headers);
  167.         // Store the token object in session for retrieval in check-email route.
  168.         $this->setTokenObjectInSession($resetToken);
  169.         return $this->redirectToRoute('app_check_email');
  170.     }
  171. }