src/Controller/ResetPasswordController.php line 46

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\Form\RequestResetPasswordType;
  7. use App\Form\ResetPasswordWithSecurityQuestionType;
  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 SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  18. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  19. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  20. use Doctrine\ORM\EntityManagerInterface;
  21. /**
  22.  * @Route("/reset-password")
  23.  */
  24. class ResetPasswordController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     private $resetPasswordHelper;
  28.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelper)
  29.     {
  30.         $this->resetPasswordHelper $resetPasswordHelper;
  31.     }
  32.     /**
  33.      * Display & process form to request a password reset.
  34.      *
  35.      * @Route("", name="app_forgot_password_request")
  36.      */
  37.     public function requestResetPassword(Request $requestEntityManagerInterface $em): Response
  38.     {
  39.         $form $this->createForm(RequestResetPasswordType::class);
  40.         $form->handleRequest($request);
  41.         if ($form->isSubmitted() && $form->isValid()) {
  42.             $email $form->get('email')->getData();
  43.             $user $em->getRepository(User::class)->findOneBy(['email' => $email]);
  44.             if (!$user) {
  45.                 $this->addFlash('error''No user found with this email.');
  46.                 return $this->redirectToRoute('app_reset_password');
  47.             }
  48.             // Rediriger vers l'étape de réponse à la question de sécurité
  49.             return $this->redirectToRoute('app_verify_security_answer', ['id' => $user->getId()]);
  50.         }
  51.         return $this->render('reset_password/request.html.twig', [
  52.             'requestForm' => $form->createView(),
  53.         ]);
  54.     }
  55.     /*public function request(Request $request, MailerInterface $mailer): Response
  56.     {
  57.         $form = $this->createForm(ResetPasswordRequestFormType::class);
  58.         $form->handleRequest($request);
  59.         if ($form->isSubmitted() && $form->isValid()) {
  60.             return $this->processSendingPasswordResetEmail(
  61.                 $form->get('email')->getData(),
  62.                 $mailer
  63.             );
  64.         }
  65.         return $this->render('reset_password/request.html.twig', [
  66.             'requestForm' => $form->createView(),
  67.         ]);
  68.     }*/
  69.     /**
  70.      * Confirmation page after a user has requested a password reset.
  71.      *
  72.      * @Route("/check-email", name="app_check_email")
  73.      */
  74.     public function checkEmail(): Response
  75.     {
  76.         // Generate a fake token if the user does not exist or someone hit this page directly.
  77.         // This prevents exposing whether or not a user was found with the given email address or not
  78.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  79.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  80.         }
  81.         return $this->render('reset_password/check_email.html.twig', [
  82.             'resetToken' => $resetToken,
  83.         ]);
  84.     }
  85.     /**
  86.      * Validates and process the reset URL that the user clicked in their email.
  87.      *
  88.      * @Route("/reset/{token}", name="app_reset_password")
  89.      */
  90.     public function reset(Request $requestUserPasswordEncoderInterface $userPasswordEncoderInterfacestring $token null): Response
  91.     {
  92.         if ($token) {
  93.             // We store the token in session and remove it from the URL, to avoid the URL being
  94.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  95.             $this->storeTokenInSession($token);
  96.             return $this->redirectToRoute('app_reset_password');
  97.         }
  98.         $token $this->getTokenFromSession();
  99.         if (null === $token) {
  100.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  101.         }
  102.         try {
  103.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  104.         } catch (ResetPasswordExceptionInterface $e) {
  105.             $this->addFlash('reset_password_error'sprintf(
  106.                 'There was a problem validating your reset request - %s',
  107.                 $e->getReason()
  108.             ));
  109.             return $this->redirectToRoute('app_forgot_password_request');
  110.         }
  111.         // The token is valid; allow the user to change their password.
  112.         $form $this->createForm(ChangePasswordFormType::class);
  113.         $form->handleRequest($request);
  114.         if ($form->isSubmitted() && $form->isValid()) {
  115.             // A password reset token should be used only once, remove it.
  116.             $this->resetPasswordHelper->removeResetRequest($token);
  117.             // Encode(hash) the plain password, and set it.
  118.             $encodedPassword $userPasswordEncoderInterface->encodePassword(
  119.                 $user,
  120.                 $form->get('plainPassword')->getData()
  121.             );
  122.             $user->setPassword($encodedPassword);
  123.             $this->getDoctrine()->getManager()->flush();
  124.             // The session is cleaned up after the password has been changed.
  125.             $this->cleanSessionAfterReset();
  126.             $this->addFlash('success''Your password has been successfully reset. You can log in with the new password');
  127.             return $this->redirectToRoute('app_login');
  128.         }
  129.         return $this->render('reset_password/reset.html.twig', [
  130.             'resetForm' => $form->createView(),
  131.         ]);
  132.     }
  133.     private function processSendingPasswordResetEmail(string $emailFormDataMailerInterface $mailer): RedirectResponse
  134.     {
  135.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  136.             'email' => $emailFormData,
  137.         ]);
  138.         // Do not reveal whether a user account was found or not.
  139.         if (!$user) {
  140.             return $this->redirectToRoute('app_check_email');
  141.         }
  142.         try {
  143.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  144.         } catch (ResetPasswordExceptionInterface $e) {
  145.             // If you want to tell the user why a reset email was not sent, uncomment
  146.             // the lines below and change the redirect to 'app_forgot_password_request'.
  147.             // Caution: This may reveal if a user is registered or not.
  148.             //
  149.             $this->addFlash('reset_password_error'sprintf(
  150.                 'There was a problem handling your password reset request - %s',
  151.                 $e->getReason()
  152.             ));
  153.             return $this->redirectToRoute('app_check_email');
  154.         }
  155.         $email = (new TemplatedEmail())
  156.             ->from(new Address(
  157.                 $this->getParameter('app_mail_from_address'),
  158.                 $this->getParameter('app_mail_from_name')
  159.             ))
  160.             ->to($user->getEmail())
  161.             ->subject('Your password reset request')
  162.             ->htmlTemplate('reset_password/email.html.twig')
  163.             ->context([
  164.                 'resetToken' => $resetToken,
  165.                 'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),
  166.             ]);
  167.         $mailer->send($email);
  168.         // Store the token object in session for retrieval in check-email route.
  169.         $this->setTokenObjectInSession($resetToken);
  170.         return $this->redirectToRoute('app_check_email');
  171.     }
  172.      
  173.     /**
  174.      * @Route("/verify-security-answer/{id}", name="app_verify_security_answer")
  175.      */
  176.     public function verifySecurityAnswer(User $userRequest $requestEntityManagerInterface $emUserPasswordEncoderInterface $passwordEncoder): Response
  177.     {
  178.         $form $this->createForm(ResetPasswordWithSecurityQuestionType::class);
  179.         $form->handleRequest($request);
  180.         if ($form->isSubmitted() && $form->isValid()) {
  181.             $securityAnswer $form->get('securityAnswer')->getData();
  182.             // Vérification de la réponse à la question de sécurité
  183.             if ($user->getSecurityAnswer() !== $securityAnswer) {
  184.                 $this->addFlash('error''Incorrect answer to the security question.');
  185.                 return $this->redirectToRoute('app_verify_security_answer', ['id' => $user->getId()]);
  186.             }
  187.            
  188.             // Si la réponse est correcte, réinitialiser le mot de passe
  189.             $newPassword $form->get('newPassword')->getData();
  190.             $encodedPassword $passwordEncoder->encodePassword($user$newPassword);
  191.             $user->setPassword($encodedPassword);
  192.             $em->flush();
  193.             $this->addFlash('success''Password successfully reset!');
  194.             return $this->redirectToRoute('app_login');
  195.         }
  196.         switch ( $user->getSecurityQuestion()) {
  197.             case "cin_number":
  198.                 $securityQuestion=  'Numero de CNI?';
  199.                 break;
  200.         
  201.             case "mother_birthplace":
  202.                 $securityQuestion ='Quelle est la ville de naissance de maman?';
  203.                 break;
  204.         
  205.             case "favorite_job":
  206.                 $securityQuestion ='Le metier dont tu reves d\'exercer depuis ton enfance?';
  207.                 break;
  208.             case "residence":
  209.                 $securityQuestion =  'Quel est ton quartier de residence?';
  210.                 break;
  211.         
  212.             default:
  213.                  $securityQuestion =" Quel est le nom de l'etablisement ?";
  214.                 break;
  215.         }
  216.         return $this->render('reset_password/verify_security_answer.html.twig', [
  217.             'securityQuestion' => $securityQuestion,
  218.             'verifyForm' => $form->createView(),
  219.         ]);
  220.     }
  221. }