src/Controller/RegistrationController.php line 297

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Datetime;
  4. use App\Entity\User;
  5. use App\Entity\Notification;
  6. use Psr\Log\LoggerInterface;
  7. use App\Service\EmailService;
  8. use App\Security\EmailVerifier;
  9. use App\Form\RegistrationFormType;
  10. use App\Repository\UserRepository;
  11. use Symfony\Component\Mime\Address;
  12. use App\Service\UserWordpressService;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Component\HttpFoundation\JsonResponse;
  19. use Symfony\Contracts\HttpClient\HttpClientInterface;
  20. use Symfony\Contracts\Translation\TranslatorInterface;
  21. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  22. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  23. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  24. use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
  25. use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
  26. class RegistrationController extends AbstractController
  27. {
  28.     private $logger;
  29.     private $httpClient;
  30.     private $emailService;
  31.     private $wordpressService;
  32.     private EmailVerifier $emailVerifier;
  33.     public function __construct(UserWordpressService $wordpressServiceEmailService $emailServiceLoggerInterface $loggerEmailVerifier $emailVerifierHttpClientInterface $httpClient)
  34.     {
  35.         $this->logger $logger;
  36.         $this->httpClient $httpClient;
  37.         $this->emailService $emailService;
  38.         $this->emailVerifier $emailVerifier;
  39.         $this->wordpressService $wordpressService;
  40.     }
  41.     #[Route('/register'name'app_register')]
  42.     public function register(Request $requestJWTTokenManagerInterface $JWTTokenManagerUserPasswordHasherInterface $userPasswordHasherEntityManagerInterface $entityManager): Response
  43.     {
  44.         $user = new User();
  45.         $form $this->createForm(RegistrationFormType::class, $user);
  46.         $form->handleRequest($request);
  47.         if ($form->isSubmitted() && $form->isValid()) {
  48.             if($form->has('seoPlugin') && $form->get('seoPlugin')->getData() === null ) {
  49.                 //dump("seoPlugin par défaut mis");
  50.                 $user->setSeoPlugin('yoastseo');
  51.             }
  52.             try {
  53.                 //dump($form);
  54.                 // encode le plain password
  55.                     $user->setPassword(
  56.                         $userPasswordHasher->hashPassword(
  57.                             $user,
  58.                             $form->get('plainPassword')->getData()
  59.                         )
  60.                     );
  61.                     //dump("Ici1");
  62.                 $user->setRoles(['ROLE_USER']);
  63.                 $creationDate = new Datetime('now');
  64.                 $user->setCreationDate($creationDate);
  65.                 if ($form->has('wordpressPassword') && $form->get('wordpressPassword')->getData() !== null ) {
  66.                     $user->setWordpressPassword($this->wordpressService->encryptPassword($user->getWordpressPassword()));
  67.                 }
  68.                 $user->setMemberOptionAutoPublish(false);
  69.                 $user->setAutoPublish(false);
  70.                 $customerKey $JWTTokenManager->create($user);
  71.                 $user->setCustomerKey($customerKey);
  72.                 $user->setNumberOfTestArticle(3);
  73.                 if($form->get('phoneNumber')->getData() === "null" ) {
  74.                     // Gestion des erreurs
  75.                         $this->addFlash('danger''Erreur : Numéro de téléphone invalide.');
  76.                     return $this->redirectToRoute('app_register');
  77.                 }
  78.                 //dump("Ici");
  79.                 if (preg_match('/^\+\d+/'$form->get('phoneNumber')->getData())) {     
  80.                     $phoneNumber $user->setPhoneNumber($form->get('phoneNumber')->getData());         
  81.                 } 
  82.                 else {
  83.                     throw new \InvalidArgumentException("Le numéro de téléphone doit inclure un préfixe international.");
  84.                 }
  85.                 //dump("Ici2");
  86.                 try {
  87.                     $entityManager->persist($user);
  88.                     $entityManager->flush();
  89.                 } catch (Exception $e) {
  90.                     $this->addFlash("danger" $e->getMessage());
  91.                 }
  92.                 //dump("Ici3");
  93.                 // A faire après la vérification d'email dans la prod
  94.                     $jsonData = [
  95.                         'authentication_key' => $_ENV['AUTHENTICATION_KEY'],
  96.                         'idcustomer' => $user->getId(),
  97.                         'customerkey' => $user->getCustomerKey(),
  98.                         'customerlastname' => $user->getLastname(),
  99.                         'customerfirstname' => $user->getFirstname(),
  100.                         'customeremail' => $user->getEmail(),
  101.                         'customerphonenumber' => $user->getPhoneNumber(),
  102.                         'customersubjects' => "",
  103.                         'companyname' => $user->getCompanyName(),
  104.                         'siteurl' => $user->getWordpressUrl(),
  105.                         'publishinguser' => $user->getWordpressUsername(),
  106.                         'publishinguserkey' => $user->getWordpressPassword() !== null $this->wordpressService->decryptPassword($user->getWordpressPassword()) : null,
  107.                         'seoplugin' => $user->getSeoPlugin(),
  108.                         'autopublish' => $user->isAutoPublish() == true 0
  109.                     ];
  110.                     //dump("Ici4");
  111.                     //dump($jsonData);
  112.                     try {
  113.                         // Envoyer les données à l'API externe
  114.                             $response $this->httpClient->request('POST''https://www.groupe-saven.fr/api.cpe/newcustomer.php'
  115.                             [
  116.                                 'json' => $jsonData
  117.                             ]);
  118.                             $statusCode $response->getStatusCode();
  119.                             //dump($response);
  120.                             $content $response->getContent(false);
  121.                             $data json_decode($contenttrue);
  122.                             //dump($statusCode);
  123.                             //dump($data);
  124.                             //dump($response);
  125.                             if ($statusCode !== 200) {
  126.                                 // Lancer une exception avec le contenu de la réponse si le code de statut n'est pas 200
  127.                                 throw new \Exception("Erreur HTTP $statusCode: " $content);
  128.                             }
  129.                             if ($data['status'] === 'success') {
  130.                                 //dump($data['id']);
  131.                                 $user->setPbnId($data['id']);
  132.                                 try {
  133.                                     $tokenVerif uniqid(md5($user->getEmail()), true) . bin2hex(random_bytes(5));
  134.                                     $user->setTempToken($tokenVerif);
  135.                                     $entityManager->persist($user);
  136.                                     $entityManager->flush();
  137.                                     // Je cree la notification pour l'historique d'activité
  138.                                         $notification = new Notification();
  139.                                         $creationDate = new Datetime('now');
  140.                                         $notification->setDateCreated($creationDate);
  141.                                         $notification->setTitle('Création du compte');
  142.                                         $notification->setUser($user);
  143.                                         $notification->setDetail('Vous avez créé votre compte');
  144.                                         $entityManager->persist($notification);
  145.                                         $entityManager->flush();
  146.                 
  147.                                 } catch (Exception $e) {
  148.                                     $this->logger->error('Erreur : '$e->getMessage());
  149.                                 }
  150.                             }
  151.                     } catch (Exception $e) {
  152.                         //dump($response);
  153.                         $this->logger->error("danger" $e->getMessage());
  154.                     }
  155.                 //
  156.                 // generate a signed url and email it to the user
  157.                 //dump('envoie de mail');
  158.                     $to $user->getEmail();
  159.                     // Sujet de l'e-mail
  160.                     $subject "Vérification d'adresse mail";
  161.                     $signedUrl $this->generateUrl('app_verify_email',['token' => $tokenVerif],  UrlGeneratorInterface::ABSOLUTE_URL, [
  162.                         'scheme' => 'https'
  163.                     ]);
  164.                     $profilUrl $this->generateUrl('app_profile', [], UrlGeneratorInterface::ABSOLUTE_URL, [
  165.                         'scheme' => 'https'
  166.                     ]);
  167.                     // Message
  168.                     $message "<h4>Bonjour! Veuillez confirmer votre adresse mail s'il vous plaît!</h4>
  169.                                 <p>
  170.                                 Confirmer votre adresse mail en appuyant sur le lien ci dessous: <br><br>
  171.                                     <a href=".$signedUrl.">Confirmer mon adresse mail</a>.
  172.                                     <p>
  173.                                         Vous trouverez votre clé pour l'utilisation de l'api dans votre profil : <br> $profilUrl
  174.                                     </p>
  175.                                 </p>
  176.                                 <p>
  177.                                     Bien à vous!
  178.                                 </p>";
  179.                     
  180.                     //dump($to);
  181.                     //dump($subject);
  182.                     //dump($message);
  183.                     if($this->emailService->sendMail($to$subject$message) == 'succeed') {
  184.                         $this->addFlash('success''Un email de confirmation vous a été envoyé dans votre boite mail '.$user->getEmail().', veuillez confirmer votre adresse afin de pouvoir vous connecter');
  185.                     }
  186.                     else {
  187.                         throw new \Exception("Erreur d'envoie de mail");
  188.                     }
  189.                 //
  190.                 return $this->redirectToRoute('app_login');
  191.             } catch (\InvalidArgumentException $e) {
  192.                     // Ajouter une erreur au champ du formulaire
  193.                     $this->addFlash('danger'$e->getMessage());
  194.             } catch (\Exception $e) {
  195.                 //dump($e->getCode());
  196.                 // Vérifiez si l'exception implémente HttpExceptionInterface
  197.                     if ($e->getCode() == 400) {
  198.                         $statusCode $e->getCode();
  199.                         $message $e->getMessage();
  200.                     }
  201.                     elseif ($e instanceof ClientException) {
  202.                         // Cas d'erreur côté client, comme une exception `BadRequestHttpException`
  203.                             $statusCode $e->getStatusCode();
  204.                             $message $e->getMessage();
  205.                     } else {
  206.                         if($e->getCode() == 0) {
  207.                             $statusCode Response::HTTP_INTERNAL_SERVER_ERROR;
  208.                             $message $e->getMessage();
  209.                         }
  210.                         else {
  211.                             // Cas d'erreur côté serveur
  212.                                 $statusCode Response::HTTP_INTERNAL_SERVER_ERROR;
  213.                                 $message 'Une erreur interne du serveur s\'est produite.';
  214.                         }
  215.                     }
  216.                     // Gestion des erreurs
  217.                         $this->addFlash('danger''Erreur : '$message);
  218.                     return $this->redirectToRoute('app_register');
  219.              }
  220.         }
  221.         return $this->render('registration/register.html.twig', [
  222.             'registrationForm' => $form->createView(),
  223.         ]);
  224.     }
  225.     #[Route('/verify/email'name'app_verify_email')]
  226.     public function verifyUserEmail(Request $requestUserRepository $userRepositoryTranslatorInterface $translatorEntityManagerInterface $entityManager): Response
  227.     {
  228.         // Je vérifie la présence du token dans l'url
  229.             if($request->get('token')) {
  230.                 // Je cherche la correspondance avec un User par token
  231.                     $user $userRepository->findOneByTempToken($request->get('token'));
  232.                 // Si je ne trouve pas de correspondance
  233.                     if(empty($user)) {
  234.                         return new JsonResponse('Votre lien a expiré, veuillez nous contacter par mail à l\'adresse : contact@leadplanet.fr'Response::HTTP_BAD_REQUEST);
  235.                     }
  236.                 // Si j'en trouve
  237.                     else {
  238.                         $user->setIsVerified(true);
  239.                         $user->setTempToken(null);
  240.                         //dump($user);
  241.                         $entityManager->persist($user);
  242.                         $entityManager->flush();
  243.                         $this->addFlash('success''Votre adresse mail a bien été vérifiée, vous pouvez vous connecter');
  244.                         // Je cree la notification pour l'historique d'activité
  245.                             $notification = new Notification();
  246.                             $creationDate = new Datetime('now');
  247.                             $notification->setDateCreated($creationDate);
  248.                             $notification->setTitle('Vérification du compte');
  249.                             $notification->setUser($user);
  250.                             $notification->setDetail('Vous avez vérifié votre compte');
  251.                             $entityManager->persist($notification);
  252.                             $entityManager->flush();
  253.                         return $this->redirectToRoute('app_login');
  254.                     }
  255.             }
  256.         return $this->redirectToRoute('app_register');
  257.     }
  258.     // Route de renvoie d'email de confirmation
  259.         #[Route('/resend/verify/email'name'resend_verification_email')]
  260.         public function sendVerifUserMail(Request $requestUserRepository $userRepositoryTranslatorInterface $translatorEntityManagerInterface $entityManager): Response
  261.         {
  262.             // Je vérifie la présence du token dans l'url
  263.                 if($request->get('email')) {
  264.                     // Je cherche la correspondance avec un User par token
  265.                         $user $userRepository->findOneByEmail($request->get('email'));
  266.                     // Si je ne trouve pas de correspondance
  267.                         if(empty($user)) {
  268.                             return new JsonResponse('Aucun utilisateur n\'est lié à cette email');
  269.                         }
  270.                         elseif($user->isVerified()) {
  271.                             $this->addFlash('danger''Utilisateur déjà vérifié');
  272.                             return $this->redirectToRoute('app_login');
  273.                         }
  274.                     // Si j'en trouve
  275.                         else {
  276.                             //dump('Renvoie de mail');
  277.                             $to $user->getEmail();
  278.                             // Sujet de l'e-mail
  279.                             $subject "Vérification d'adresse mail";
  280.                             if($user->getTempToken()) {
  281.                                 $tokenVerif $user->getTempToken();
  282.                             }
  283.                             else {
  284.                                 $tokenVerif uniqid(md5($user->getEmail()), true) . bin2hex(random_bytes(5));
  285.                                 $user->setTempToken($tokenVerif);
  286.                                 $entityManager->persist($user);
  287.                                 $entityManager->flush();
  288.                             }
  289.                             $signedUrl $this->generateUrl('app_verify_email',['token' => $tokenVerif],  UrlGeneratorInterface::ABSOLUTE_URL, [
  290.                                 'scheme' => 'https'
  291.                             ]);
  292.                             $profilUrl $this->generateUrl('app_profile', [], UrlGeneratorInterface::ABSOLUTE_URL, [
  293.                                 'scheme' => 'https'
  294.                             ]);
  295.         
  296.                             // Message
  297.                             $message "<h4>Bonjour! Veuillez confirmer votre adresse mail s'il vous plaît!</h4>
  298.                                         <p>
  299.                                         Confirmer votre adresse mail en appuyant sur le lien ci dessous: <br><br>
  300.                                             <a href=".$signedUrl.">Confirmer mon adresse mail</a>.
  301.                                             <p>
  302.                                                 Vous trouverez votre clé pour l'utilisation de l'api dans votre profil une fois ce dernier vérifié: <br> $profilUrl
  303.                                             </p>
  304.                                         </p>
  305.                                         <p>
  306.                                             Bien à vous!
  307.                                         </p>";
  308.                             //dump($to);
  309.                             //dump($subject);
  310.                             //dump($message);
  311.                             if($this->emailService->sendMail($to$subject$message) == 'succeed') {
  312.                                 $this->addFlash('success''Un email de confirmation vous a été envoyé dans votre boite mail '.$user->getEmail().', veuillez confirmer votre adresse afin de pouvoir vous connecter');
  313.                             }
  314.                             else {
  315.                                 throw new \Exception("Erreur d'envoie de mail");
  316.                             }
  317.                         }
  318.                         return $this->redirectToRoute('app_login');
  319.                 }
  320.             return $this->render('security/resend_verification_mail.html.twig');
  321.         }
  322. }