src/Controller/ActivationCompteController.php line 46

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller;
  4. use App\Entity\Hermes\Client;
  5. use App\Form\ActivationCompteType;
  6. use App\Form\ChangePasswordFormType;
  7. use App\Repository\Ariane\CompteRepository;
  8. use App\Services\GenerateUserClientServices;
  9. use App\Services\Mail\SendEmailServices;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Doctrine\Persistence\ManagerRegistry;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Mailer\MailerInterface;
  17. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Contracts\Translation\TranslatorInterface;
  20. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  21. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  22. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  23. #[Route('/activation-compte')]
  24. class ActivationCompteController extends AbstractController
  25. {
  26.     use ResetPasswordControllerTrait;
  27.     public function __construct(
  28.         private ResetPasswordHelperInterface $resetPasswordHelper,
  29.         private EntityManagerInterface $entityManager,
  30.         private ManagerRegistry $managerRegistry,
  31.         private GenerateUserClientServices $generateUserClientServices,
  32.         private CompteRepository $compteRepository,
  33.         private SendEmailServices $sendEmailServices
  34.     ) {
  35.     }
  36.     /**
  37.      * Display & process form to request a password reset.
  38.      */
  39.     #[Route(''name'app_activation_compte_request')]
  40.     public function request(Request $requestMailerInterface $mailerTranslatorInterface $translator): Response
  41.     {
  42.         $form $this->createForm(ActivationCompteType::class);
  43.         $form->handleRequest($request);
  44.         if ($form->isSubmitted() && $form->isValid()) {
  45.             return $this->processSendingPasswordResetEmail(
  46.                 $form->get('codeClient')->getData(),
  47.                 $mailer,
  48.                 $translator
  49.             );
  50.         }
  51.         return $this->render('activation_compte/request.html.twig', [
  52.             'requestForm' => $form->createView(),
  53.         ]);
  54.     }
  55.     /**
  56.      * Confirmation page after a user has requested a password reset.
  57.      */
  58.     #[Route('/check-code'name'app_check_code')]
  59.     public function checkEmail(): Response
  60.     {
  61.         // Generate a fake token if the user does not exist or someone hit this page directly.
  62.         // This prevents exposing whether or not a user was found with the given email address or not
  63.         if (null === ($resetToken $this->getTokenObjectFromSession())) {
  64.             $resetToken $this->resetPasswordHelper->generateFakeResetToken();
  65.         }
  66.         return $this->render('activation_compte/check_email.html.twig', [
  67.             'resetToken' => $resetToken,
  68.         ]);
  69.     }
  70.     /**
  71.      * Validates and process the reset URL that the user clicked in their email.
  72.      */
  73.     #[Route('/reset/{token}'name'app_reset_password')]
  74.     public function reset(Request $requestUserPasswordHasherInterface $userPasswordHasherTranslatorInterface $translatorstring $token null): Response
  75.     {
  76.         if ($token) {
  77.             // We store the token in session and remove it from the URL, to avoid the URL being
  78.             // loaded in a browser and potentially leaking the token to 3rd party JavaScript.
  79.             $this->storeTokenInSession($token);
  80.             return $this->redirectToRoute('app_reset_password');
  81.         }
  82.         $token $this->getTokenFromSession();
  83.         if (null === $token) {
  84.             throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
  85.         }
  86.         try {
  87.             $user $this->resetPasswordHelper->validateTokenAndFetchUser($token);
  88.         } catch (ResetPasswordExceptionInterface $e) {
  89.             $this->addFlash('reset_password_error'sprintf(
  90.                 '%s - %s',
  91.                 $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
  92.                 $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  93.             ));
  94.             return $this->redirectToRoute('app_activation_compte_request');
  95.         }
  96.         // The token is valid; allow the user to change their password.
  97.         $form $this->createForm(ChangePasswordFormType::class);
  98.         $form->handleRequest($request);
  99.         if ($form->isSubmitted() && $form->isValid()) {
  100.             // A password reset token should be used only once, remove it.
  101.             $this->resetPasswordHelper->removeResetRequest($token);
  102.             // Encode(hash) the plain password, and set it.
  103.             $encodedPassword $userPasswordHasher->hashPassword(
  104.                 $user,
  105.                 $form->get('plainPassword')->getData()
  106.             );
  107.             $user->setPassword($encodedPassword);
  108.             $this->entityManager->flush();
  109.             // The session is cleaned up after the password has been changed.
  110.             $this->cleanSessionAfterReset();
  111.             return $this->redirectToRoute('app_accueil_index');
  112.         }
  113.         return $this->render('activation_compte/reset.html.twig', [
  114.             'resetForm' => $form->createView(),
  115.         ]);
  116.     }
  117.     private function processSendingPasswordResetEmail(string $codeClientFormDataMailerInterface $mailerTranslatorInterface $translator): RedirectResponse
  118.     {
  119.         $compteExist $this->compteRepository->findOneBy(['codeClient' => $codeClientFormData]);
  120.         if ($compteExist) {
  121.             $this->addFlash('danger''Votre compte existe déjà');
  122.             return $this->redirectToRoute('app_login');
  123.         }
  124.         $client $this->managerRegistry->getRepository(Client::class, 'hermes')->findOneBy([
  125.             'numero' => $codeClientFormData,
  126.         ]);
  127.         if (null !== $client && !== $client->getClientStatut()->getId()) {
  128.             $this->addFlash('danger''Ce compte ne peut être activé. Merci de nous contacter pour plus d\'informations.');
  129.             return $this->redirectToRoute('app_login');
  130.         }
  131.         // Do not reveal whether a user account was found or not.
  132.         if (!$client) {
  133.             return $this->redirectToRoute('app_check_code');
  134.         }
  135.         if (!filter_var($client->getEmail(), \FILTER_VALIDATE_EMAIL)) {
  136.             $this->addFlash('danger''Oups, Veuillez contacter SRDI');
  137.             return $this->redirectToRoute('app_check_code');
  138.         }
  139.         $userClient $this->generateUserClientServices->create($client);
  140.         if (null === $userClient) {
  141.             $this->addFlash('danger''L\'adresse email associée à votre compte semble déjà utilisée sur un compte tiers. Merci de vous rapprocher de notre service client.');
  142.             return $this->redirectToRoute('app_activation_compte_request');
  143.         }
  144.         try {
  145.             $resetToken $this->resetPasswordHelper->generateResetToken($userClient);
  146.         } catch (ResetPasswordExceptionInterface $e) {
  147.             // If you want to tell the user why a reset email was not sent, uncomment
  148.             // the lines below and change the redirect to 'app_forgot_password_request'.
  149.             // Caution: This may reveal if a user is registered or not.
  150.             //
  151.             // $this->addFlash('reset_password_error', sprintf(
  152.             //     '%s - %s',
  153.             //     $translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  154.             //     $translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  155.             // ));
  156.             return $this->redirectToRoute('app_check_code');
  157.         }
  158.         $this->sendEmailServices->sendResetPassword($userClient$resetTokentrue);
  159.         $this->setTokenObjectInSession($resetToken);
  160.         return $this->redirectToRoute('app_check_code');
  161.     }
  162. }