src/Controller/AuthController.php line 113

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use DateTime;
  4. use Exception;
  5. use Dompdf\Dompdf;
  6. use Dompdf\Options;
  7. use App\Entity\User;
  8. use App\Entity\Users;
  9. use App\Entity\Wallet;
  10. use App\Entity\UserOTP;
  11. use App\Form\SignupType;
  12. use App\Entity\ContactUs;
  13. use App\Form\ContactUsType;
  14. use App\Service\OtpService;
  15. use App\Service\AuthService;
  16. use App\Service\MailService;
  17. use App\Service\DocumentService;
  18. use App\Service\ContactUsService;
  19. use App\Exception\CustomException;
  20. use App\Repository\UserRepository;
  21. use App\Repository\UsersRepository;
  22. use App\Repository\ContactUsRepository;
  23. use App\Service\ConfigService;
  24. use Doctrine\ORM\EntityManagerInterface;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\Security\Core\Security;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\HttpFoundation\File\File;
  29. use Symfony\Component\Routing\Annotation\Route;
  30. use Symfony\Component\HttpFoundation\JsonResponse;
  31. use Symfony\Component\HttpFoundation\RedirectResponse;
  32. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  33. use Symfony\Component\Form\Extension\Core\Type\TextType;
  34. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  35. use Symfony\Component\Form\Extension\Core\Type\EmailType;
  36. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  37. use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
  38. use Symfony\Component\Validator\Validator\ValidatorInterface;
  39. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  40. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  41. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  42. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  43. use Symfony\Contracts\Translation\TranslatorInterface;
  44. #[Route('/auth')]
  45. class AuthController extends AbstractController
  46. {
  47.     private $entityManager;
  48.     private $userRepository;
  49.     private $authService;
  50.     private $validator;
  51.     private $mailService;
  52.     public function __construct(EntityManagerInterface $entityManager
  53.         UsersRepository $userRepository,
  54.         AuthService $authService,
  55.         ValidatorInterface $validator,
  56.         MailService $mailService,
  57.         private OtpService $otpService,
  58.         private DocumentService $documentService,
  59.         private TranslatorInterface $translator
  60.     )
  61.     {
  62.         $this->entityManager $entityManager;
  63.         $this->userRepository $userRepository;
  64.         $this->authService $authService;
  65.         $this->validator $validator;
  66.         $this->mailService $mailService;
  67.     }
  68.     #[Route('/deconnexion'name'app_auth_logout')]
  69.     public function logout(): void
  70.     {
  71.         $this->otpService->removeChangePasswordData();
  72.         $this->otpService->removeEmailOtp();
  73.         $this->otpService->removeKycData();
  74.         $this->otpService->removeSignupData(false);
  75.         $this->otpService->removeSignupData(true);
  76.         $this->otpService->removeUpdateAccountData();
  77.     }
  78.     #[Route('/connexion'name'app_auth_login')]
  79.     public function login(AuthenticationUtils $authenticationUtils): Response
  80.     {
  81.         if ($this->getUser()) {
  82.             if(in_array("ROLE_ADMIN"$this->getUser()->getRoles())){
  83.                 return $this->redirectToRoute('app_admin_index');
  84.             } else if(in_array("ROLE_CLIENT"$this->getUser()->getRoles())){
  85.                 return $this->redirectToRoute('app_home_index');
  86.             }
  87.         }
  88.         $error $authenticationUtils->getLastAuthenticationError();
  89.         $lastUsername $authenticationUtils->getLastUsername();
  90.         return $this->render('auth/login.html.twig', [
  91.             'last_username' => $lastUsername,
  92.             'error'         => $error "Votre nom d'utilisateur ou votre mot de passe est invalide." null,
  93.         ]);
  94.     }
  95.     #[Route('/mot_de_passe_oubliee'name'app_auth_mot_de_passe_oubliee')]
  96.     public function forgotPasseword(AuthenticationUtils $authenticationUtils): Response
  97.     {
  98.         return $this->render('auth/forgotPassword.html.twig', [
  99.         ]);
  100.     }
  101.     
  102.     #[Route('/formulaire_contact'name'app_auth_formulaire_contact')]
  103.     public function formulaireContact(Request $request,ContactUsService $contactUsService): Response
  104.     {
  105.         $contactus= new ContactUs();
  106.         $form $this->createForm(ContactUsType::class, $contactus);
  107.         $form->handleRequest($request);
  108.         
  109.         if ($form->isSubmitted() && $form->isValid()) {
  110.             try {
  111.                 $contactUsService->addContactUs($contactus);
  112.                 $this->addFlash('success'$this->translator->trans("Votre message a été transmis avec succès à un administrateur. Veuillez patienter pour recevoir une réponse."));
  113.             
  114.             } 
  115.             catch (CustomException $ex) {
  116.                 $this->addFlash(
  117.                     'danger',
  118.                     $this->translator->trans($ex->getMessage())
  119.                 );
  120.             } catch (Exception $ex) {
  121.                 // Gérer toutes les autres exceptions
  122.                 $this->addFlash(
  123.                     'danger',
  124.                     $this->translator->trans($_ENV['ERROR_MESSAGE'])
  125.                 );
  126.             }
  127.         }
  128.         return $this->render('auth/formulaireContact.html.twig',[
  129.             "form" => $form->createView()
  130.         ]);
  131.     }
  132.     #[Route('/verification_email'name'app_auth_verification_email')]
  133.     public function verificationEmail(AuthenticationUtils $authenticationUtils): Response
  134.     {
  135.         return $this->render('auth/verification_email.html.twig', [
  136.         ]);
  137.     }
  138.     #[Route('/nouveau_mot_de_passe'name'app_nouveau_mot_de_passe')]
  139.     public function nouveauMotDePasse(AuthenticationUtils $authenticationUtils): Response
  140.     {
  141.         return $this->render('auth/nouveauMotDePasse.html.twig', [
  142.         ]);
  143.     }
  144.     
  145.     #[Route('/inscription/back-office'name'app_index_inscription')]
  146.     public function signup(Request $requestUserPasswordHasherInterface $passwordHasher): Response
  147.     {   
  148.         
  149.         $error null;
  150.         $user = new Users();
  151.         $form $this->createForm(SignupType::class, $user, ['signup' => true]);
  152.         $uplineUser $this->userRepository->findOneBy(['id' => $request->request->get('upline')]);
  153.         $user->setUpline($uplineUser ?? $this->getUser());
  154.         $side_of_team $request->get('side');
  155.         if($side_of_team == Users::GAUCHE || $side_of_team == Users::DROITE){
  156.             $user->setSide($side_of_team);
  157.             $form->remove('side'); 
  158.         }
  159.         $form->handleRequest($request);
  160.         if ($form->isSubmitted() && $form->isValid()) {
  161.           
  162.             try {
  163.                 if(count($this->userRepository->findByNameAndBirthdate($user)) > 0){
  164.                     throw new CustomException("L'utilisateur existe déjà");
  165.                 }
  166.                 $unhashedPassword=$user->getPlainPassword();
  167.                 $password $passwordHasher->hashPassword($user$unhashedPassword);
  168.                 $user->setPassword($password);
  169.                 $user->setRoles(["ROLE_CLIENT"]);
  170.                 $user->setParent($this->getUser());
  171.                 $errors $this->validator->validate($user);
  172.                 if (count($errors) > 0) {
  173.                     throw new Exception($errors->get(0)->getMessage());
  174.                 }
  175.                 $putToTheExtremePosition = ($uplineUser) ? false true;
  176.                 $userWithSameNumero $this->authService->getUserSameNumero($user);
  177.                 if($userWithSameNumero){
  178.                     throw new CustomException('Un compte avec les mêmes informations existe déjà');
  179.                 }
  180.                 $this->otpService->setSignupData($user$putToTheExtremePositiontrue);
  181.                 $this->otpService->sendOtp($userWithSameNumero$user->getEmail(), UserOTP::TYPE_SIGNUP_BACKOFFICE$user->getName(), $user->getSurname());
  182.                 return $this->redirectToRoute('app_otp_home', ['operationType' => UserOTP::TYPE_SIGNUP_BACKOFFICE]);
  183.                 //recuperation du path du logo
  184.                 // $imagePath = $this->getParameter('kernel.project_dir') . '/public/img/logo.png';
  185.                 
  186.                 // $this->authService->saveUser($user,$unhashedPassword,$putToTheExtremePosition,$imagePath);
  187.                 // if(!is_null($uplineUser)){
  188.                 //     return $this->redirectToRoute('app_equipe_binaire', ['username' => $uplineUser->getUsername()]);
  189.                 // }
  190.                 // $this->addFlash('success', 'Utilisateur ajouté avec succès');  
  191.                 // return $this->redirectToRoute('app_index_inscription');
  192.             
  193.             catch (CustomException $ex) {
  194.                 $this->addFlash(
  195.                     'danger',
  196.                     $this->translator->trans($ex->getMessage())
  197.                 );
  198.             } catch (Exception $ex) {
  199.                 // Gérer toutes les autres exceptions
  200.                 $this->addFlash(
  201.                     'danger',
  202.                     $this->translator->trans($_ENV['ERROR_MESSAGE'])
  203.                 );
  204.             }
  205.         }
  206.         return $this->render('inscription/inscription_back_office.html.twig', [
  207.             'form' => $form->createView(),
  208.             'error' => $error,
  209.             'uplineUser' => $uplineUser,
  210.             'side' => $side_of_team
  211.         ]);
  212.     }
  213.     #[Route('/inscription'name'app_mon_lien_inscription')]
  214.     public function signupViaMyLink(Request $requestUserPasswordHasherInterface $passwordHasherConfigService $configService): Response
  215.     {
  216.         $parrain_username $request->get('parrain');
  217.         if($parrain_username) {
  218.             $parrain_username $configService->decrypt($parrain_username);
  219.         }
  220.         $side_of_team $request->get('side');
  221.         $parrain $this->userRepository->findOneBy(['username' => $parrain_username]);
  222.         $error null;
  223.         $user = new Users();
  224.         if($parrain && $parrain->getState() == Users::SUSPENDED){
  225.             return $this->render('blocked/suspended_account_alert.html.twig');
  226.         }
  227.         if($parrain){
  228.             $user->setParent($parrain);
  229.             $user->setUpline($parrain);
  230.         }
  231.         if($side_of_team == Users::GAUCHE || $side_of_team == Users::DROITE){
  232.             $user->setSide($side_of_team);
  233.         }
  234.         $form $this->createForm(SignupType::class, $user, ['signup' => true]);
  235.         $form->remove('side'); 
  236.         $form->handleRequest($request);
  237.         if ($form->isSubmitted() && $form->isValid()) {
  238.           
  239.             try {
  240.                 if(count($this->userRepository->findByNameAndBirthdate($user)) > 0){
  241.                     throw new CustomException("L'utilisateur existe déjà");
  242.                 }
  243.                 $unhashedPassword=$user->getPlainPassword();
  244.                 $password $passwordHasher->hashPassword($user$unhashedPassword);
  245.                 $user->setPassword($password);
  246.                 $user->setRoles(["ROLE_CLIENT"]);
  247.                 
  248.                 $errors $this->validator->validate($user);
  249.                 if (count($errors) > 0) {
  250.                     throw new Exception($errors->get(0)->getMessage());
  251.                 }
  252.                 $userWithSameNumero $this->authService->getUserSameNumero($user);
  253.                 $this->otpService->setSignupData($usertruefalse);
  254.                 $this->otpService->sendOtp($userWithSameNumero$user->getEmail(), UserOTP::TYPE_SIGNUP$user->getName(), $user->getSurname());
  255.                 return $this->redirectToRoute('app_otp_home', ['operationType' => UserOTP::TYPE_SIGNUP]);
  256.                 //recuparation du repertoire du logo
  257.                 // $imagePath = $this->getParameter('kernel.project_dir') . '/public/img/logo.png';
  258.                 // $this->authService->saveUser($user,$unhashedPassword,true,$imagePath);
  259.                 // return $this->redirectToRoute('app_auth_login');
  260.             
  261.             catch (CustomException $ex) {
  262.                 $this->addFlash(
  263.                     'danger',
  264.                     $this->translator->trans($ex->getMessage())
  265.                 );
  266.             } catch (Exception $ex) {
  267.                 // Gérer toutes les autres exceptions
  268.                 $this->addFlash(
  269.                     'danger',
  270.                     $this->translator->trans($_ENV['ERROR_MESSAGE'])
  271.                 );
  272.             }
  273.         }
  274.         return $this->render('inscription/inscription.html.twig', [
  275.             'form' => $form->createView(),
  276.             'error' => $error,
  277.             'parrain' => $parrain
  278.         ]);
  279.     }
  280.     #[Route('/print_condition_utilisation'name'app_print_condition_utilisation')]
  281.     public function impressionConditionUtilisation(AuthenticationUtils $authenticationUtils): Response
  282.     {
  283.         $imagePath $this->getParameter('kernel.project_dir') . '/public/img/logo.png';
  284.         // Créer une instance de la classe File
  285.         $file = new File($imagePath);
  286.         // Vérifier si le fichier existe
  287.         if ($file->isFile()) {
  288.             // Convertir le contenu du fichier en base64
  289.             $fileContent base64_encode(file_get_contents($file->getPathname()));
  290.         }
  291.         $date = (new \DateTime())->format('Ymd_His');
  292.         $fileName "Condition_utilisation-".$date.".pdf";
  293.         $html $this->renderView('pdf/condition_utilisation.html.twig', [
  294.             'title' => $fileName,
  295.             'img'=>$fileContent
  296.         ]);
  297.         
  298.         $options = new Options();
  299.         $options->set('isHtml5ParserEnabled'true);
  300.         $options->set('isPhpEnabled'true);
  301.         $dompdf = new Dompdf();
  302.        
  303.         $dompdf->loadHtml($html);
  304.         $dompdf->setPaper('A4''portrait');
  305.         $dompdf->render();
  306.         $response = new Response($dompdf->output());
  307.         $response->headers->set('Content-Type''application/pdf');
  308.         $response->headers->set('Content-Disposition''attachment; filename="'.$fileName.'"');
  309.         return $response;
  310.     }
  311.     #[Route('/check-existing-user'name'app_auth_check_existing_user'methods:"POST")]
  312.     public function checkExistingUser(Request $request): JsonResponse
  313.     {
  314.         try{
  315.             $params json_decode$request->getContent(), true);
  316.             $user $this->userRepository->checkExistingUsers($params);
  317.             
  318.             return new JsonResponse(['user' => $user]);
  319.         } catch (CustomException $ex) {
  320.             return new JsonResponse(['message' => $ex->getMessage()], 500);
  321.         } catch (Exception $ex) {   
  322.             return new JsonResponse(['message' => $_ENV['ERROR_MESSAGE']], 500);
  323.         }
  324.     }
  325.     
  326.     #[Route('/back-office/condition-utilisation/{type}'name'app_show_document')]
  327.     public function showDocumentBackOffice(int $type): Response
  328.     {
  329.         $user $this->getUser();
  330.         return $this->render('term_condition/show_document_backoffice.html.twig',[
  331.             'user' => $user,
  332.             'type' => $type 
  333.         ]);
  334.     }
  335.     #[Route('/condition-utilisation/{type}'name'app_show_document_signupbylink')]
  336.     public function showDocument(int $type): Response
  337.     {
  338.         $user $this->getUser();
  339.         return $this->render('term_condition/show_document.html.twig',[
  340.             'user' => $user,
  341.             'type' => $type 
  342.         ]);
  343.     }
  344.     #[Route('/condition-utilisation/pdf/{type}'name'app_document_preview')]
  345.     public function getDocument(int $type,Request $request) : Response
  346.     {
  347.         $COMPRESSED_STATE 0;
  348.         $locale $request->getLocale();
  349.         $locale $locale ?? 'fr';
  350.         $file $this->documentService->getFileDocument$this->getParameter('files_directory'),$type,$COMPRESSED_STATE,$locale);
  351.         // Create a BinaryFileResponse object
  352.         $response = new BinaryFileResponse($file['filePath']);
  353.         // Set response headers
  354.         $response->headers->set('Content-Type''application/pdf');
  355.         return $response;
  356.     }
  357.     #[Route('/condition-utilisation/download/pdf/{type}'name'app_download_document')]
  358.     public function downloadDocument(int $type,Request $request)
  359.     {
  360.         $locale $request->getLocale();
  361.         $locale $locale ?? 'fr';
  362.         $NOT_COMPRESSED_STATE 1;
  363.         $file $this->documentService->getFileDocument$this->getParameter('files_directory'),$type,$NOT_COMPRESSED_STATE,$locale);
  364.         // Create a BinaryFileResponse object
  365.         $response = new BinaryFileResponse($file['filePath']);
  366.         // Set response headers
  367.         $response->setContentDisposition(
  368.             'attachment',
  369.             $file['filename']
  370.         );
  371.         return $response;
  372.     }
  373.     #[Route('/condition-utilisation/sendmail/pdf/{type}'name'app_send_document')]
  374.     public function sendDocument(Request $request,int $type,Security $security)
  375.     {
  376.         $locale $request->getLocale();
  377.         $locale $locale ?? 'fr';
  378.         try {
  379.             $email $request->get('email');
  380.             $NOT_COMPRESSED_STATE 1;
  381.             $this->documentService->sendDocument$email,$this->getParameter('files_directory'),$type,$NOT_COMPRESSED_STATE,$locale);
  382.             $this->addFlash('success_message''Document envoyé avec succès');  
  383.         }catch (CustomException $ex) {
  384.             $this->addFlash(
  385.                 'error_message',
  386.                 $this->translator->trans($ex->getMessage())
  387.             );
  388.         } catch (Exception $ex) {
  389.             // Gérer toutes les autres exceptions
  390.             $this->addFlash(
  391.                 'error_message',
  392.                 $this->translator->trans($_ENV['ERROR_MESSAGE'])
  393.             );
  394.         }
  395.         if ($security->getUser()){
  396.             return $this->redirectToRoute('app_show_document',["type" => $type]);
  397.         }
  398.         else{
  399.             return $this->redirectToRoute('app_show_document_signupbylink',["type" => $type]);
  400.         }
  401.     }
  402.    
  403.     
  404. }