src/Controller/AuthController.php line 113

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\RegisterType;
  5. use App\Services\UserSession;
  6. use App\Form\UpdatePasswordType;
  7. use App\Repository\UserRepository;
  8. use Symfony\Component\Mime\Address;
  9. use App\Form\ChangePasswordFormType;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use App\Form\ResetPasswordRequestFormType;
  12. use App\Form\RequestVerifyUserEmailFormType;
  13. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\Mailer\MailerInterface;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  19. use SymfonyCasts\Bundle\VerifyEmail\VerifyEmailHelperInterface;
  20. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  21. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  22. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  23. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  24. use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
  25. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  26. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  27. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  28. use Symfony\Component\Security\Http\Attribute\IsGranted;
  29. class AuthController extends AbstractController
  30. {
  31.     use ResetPasswordControllerTrait;
  32.     private $verifyEmailHelper;
  33.     private $mailer;
  34.     private $manager;
  35.     private $userSession;
  36.     public function __construct(
  37.         private ResetPasswordHelperInterface $resetPasswordHelper,
  38.         private EntityManagerInterface $entityManager,
  39.         VerifyEmailHelperInterface $helper,
  40.         MailerInterface $mailer,
  41.         EntityManagerInterface $manager,
  42.         UserSession $userSession,
  43.     ) {
  44.         $this->verifyEmailHelper $helper;
  45.         $this->mailer $mailer;
  46.         $this->manager $manager;
  47.         $this->userSession $userSession;
  48.     }
  49.     //  /**
  50.     //  * @Route("/connexion", name="security.login", methods={"GET","POST"})
  51.     //  */
  52.      #[Route('/connexion'name:'security.login'methods: ['POST','GET'])]
  53.     public function login(AuthenticationUtils $authenticationUtilsRequest $request): Response
  54.     {
  55.         $previousRoutePath $request->headers->get('referer');
  56.         
  57.         // dd($_COOKIE["__ga_ru__"]);
  58.         
  59.         if (!empty($previousRoutePath)) {
  60.             if (!isset($_COOKIE["__ga_ru__"])) {
  61.                 $this->userSession->setCookies($previousRoutePath);
  62.             }
  63.         }
  64.         if ($this->userSession->checkIfSessionAndConnected() == true) {
  65.             return $this->redirect($previousRoutePath,302);
  66.         }
  67.         
  68.         // if ($this->getUser()) {
  69.         //     return $this->redirect($previousRoutePath,302);
  70.         // }
  71.         // last username entered by the user
  72.         $lastUsername $authenticationUtils->getLastUsername();
  73.         // dd($authenticationUtils->getLastAuthenticationError()->getMessage());
  74.         // get the login error if there is one
  75.         $error $authenticationUtils->getLastAuthenticationError();
  76.         if ($error && $error->getMessage() != "An authentication exception occurred.") {
  77.             return $this->render('auth/login.html.twig', [
  78.                 'last_username' => $lastUsername,
  79.                 'error' => $error
  80.             ]);
  81.         } else {
  82.             return $this->render('auth/login.html.twig', [
  83.                 'last_username' => $lastUsername,
  84.             ]);
  85.         }
  86.     }
  87.     //  /**
  88.     //  * Formulaire d'inscription utilisateur
  89.     //  * @Route("/inscription", name="register", methods={"GET", "POST"})
  90.     //  *
  91.     //  * @param Request $request
  92.     //  * @param EntityManagerInterface $manager
  93.     //  * @return Response
  94.     //  */
  95.     #[Route('/inscription'name:'register'methods: ["GET","POST"])]
  96.     public function register(Request $request): Response
  97.     {
  98.         $previousRoutePath $request->headers->get('referer');
  99.         $parsedUrl parse_url($previousRoutePath);
  100.         $previousDomain = isset($parsedUrl['host']) ? $parsedUrl['host'] : null;
  101.         $user = new User();
  102.         $user->setRoles(['ROLE_USER']);
  103.         $form $this->createForm(RegisterType::class, $user);
  104.         if (in_array($previousDomain,['annonces.abidjan.net','ticket.abidjan.net'])) {
  105.             $form->add('typeCompte'ChoiceType::class, [
  106.                 'choices'  => [
  107.                     'Organisation' => 'Organisation',
  108.                     'Particulier' => 'Particulier',
  109.                 ],
  110.                 'attr' => [
  111.                     'class' => 'form-control form-select-styled',
  112.                 ],
  113.                 'label' => 'Type de compte*',
  114.                 'label_attr' => [
  115.                     'class' => 'form-label'
  116.                 ],
  117.             ]);
  118.         }else{
  119.             $user->setTypeCompte('Particulier');
  120.         }
  121.         $form->handleRequest($request);
  122.         if ($form->isSubmitted() && $form->isValid()) {
  123.             $user $form->getData();
  124.             $dialCode $request->request->get('dial_code');
  125.             if (empty($dialCode)) {
  126.                 $this->addFlash(
  127.                     'error',
  128.                     'Veuillez sélectionner le code pays!'
  129.                 );
  130.                 return $this->redirectToRoute('register');
  131.             }
  132.             $nom_complet $user->getNom() . ' ' $user->getPrenoms();
  133.             $user->setNomComplet($nom_complet);
  134.             $user->setUsername($user->getEmail());
  135.             $user->setDialCode($dialCode);
  136.             $user->setIsAdmin(false);
  137.             $this->manager->persist($user);
  138.             $this->manager->flush();
  139.             $signatureComponents $this->verifyEmailHelper->generateSignature(
  140.                 'registration_confirmation_route',
  141.                 $user->getId(),
  142.                 $user->getEmail(),
  143.                 ['id' => $user->getId()]
  144.             );
  145.             $email = new TemplatedEmail();
  146.             $email->from('abidjan.net@weblogy.com');
  147.             $email->to($user->getEmail());
  148.             $email->subject('Vérification de compte');
  149.             $email->htmlTemplate('auth/confirmation_email.html.twig');
  150.             $email->context(['signedUrl' => $signatureComponents->getSignedUrl()]);
  151.             $this->mailer->send($email);
  152.             $this->addFlash(
  153.                 'info',
  154.                 'Un email de confirmation vous a été envoyé pour la vérification de votre compte. Si le mail n\'apparait pas dans la boite de réception, veuillez vérifier dans les spams!'
  155.             );
  156.             if (isset($_COOKIE['__ga_reu__'])) {
  157.                 $url $_COOKIE['__ga_reu__'];
  158.                 return $this->redirect($url);
  159.             }
  160.             return $this->redirectToRoute('security.login');
  161.         }
  162.         return $this->render('auth/register.html.twig', ['form' => $form->createView()]);
  163.     }
  164.     //   /**
  165.     //  * @Route("/verify", name="registration_confirmation_route")
  166.     //  */
  167.     #[Route('/verify'name:'registration_confirmation_route'methods: ["GET","POST"])]
  168.     public function verifyUserEmail(Request $requestUserRepository $userRepository): Response
  169.     {
  170.         // $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  171.         // $user = $this->getUser();
  172.         $user $userRepository->find($request->get('id'));
  173.         if (!$user) {
  174.             $this->addFlash(
  175.                 'error',
  176.                 'Utilisateur non trouvé!'
  177.             );
  178.             return $this->redirectToRoute('security.login');
  179.         }
  180.         // Do not get the User's Id or Email Address from the Request object
  181.         try {
  182.             $this->verifyEmailHelper->validateEmailConfirmation($request->getUri(), $user->getId(), $user->getEmail());
  183.         } catch (VerifyEmailExceptionInterface $e) {
  184.             $this->addFlash('error'$e->getReason());
  185.             return $this->redirectToRoute('register');
  186.         }
  187.         // Mark your user as verified. e.g. switch a User::verified property to true
  188.         $user->setEmailVerified(true);
  189.         $user->setActif(true);
  190.         $this->manager->persist($user);
  191.         $this->manager->flush();
  192.         $this->addFlash(
  193.             'success',
  194.             'Votre adresse email a été vérifiée avec succès!'
  195.         );
  196.         if (isset($_COOKIE['__ga_reu__'])) {
  197.             $url $_COOKIE['__ga_reu__'];
  198.             return $this->redirect($url);
  199.         }
  200.         return $this->redirectToRoute('app_front_home');
  201.     }
  202.     //   /**
  203.     //  * @Route("/verify/resend", name="app_verify_resend_email")
  204.     //  */
  205.     #[Route('/verify/resend'name:'app_verify_resend_email'methods: ["GET","POST"])]
  206.     public function resendVerifyEmail(Request $requestUserRepository $userRepository)
  207.     {
  208.         if ($this->getUser()) {
  209.             return $this->redirectToRoute('app_front_home');
  210.         }
  211.         $userEmail $request->get('email');
  212.         // $this->addFlash(
  213.         //     'r_info',
  214.         //     'Un courriel de vérification d\'email vous a été envoyé par mail, veuillez cliquer le lien dans le mail pour activer votre compte avant connexion.!'
  215.         // );
  216.         $form $this->createForm(RequestVerifyUserEmailFormType::class);
  217.         $form->handleRequest($request);
  218.         if ($form->isSubmitted() && $form->isValid()) {
  219.             // generate a signed url and email it to the user
  220.             $user =  $userRepository->findOneByEmail($form->get('email')->getData());
  221.             if ($user) {
  222.                 $signatureComponents $this->verifyEmailHelper->generateSignature(
  223.                     'registration_confirmation_route',
  224.                     $user->getId(),
  225.                     $user->getEmail(),
  226.                     ['id' => $user->getId()]
  227.                 );
  228.                 $email = new TemplatedEmail();
  229.                 $email->from('abidjan.net@weblogy.com');
  230.                 $email->to($user->getEmail());
  231.                 $email->subject('Vérification de compte');
  232.                 $email->htmlTemplate('auth/confirmation_email.html.twig');
  233.                 $email->context(['signedUrl' => $signatureComponents->getSignedUrl()]);
  234.                 $this->mailer->send($email);
  235.                 $this->addFlash(
  236.                     'info',
  237.                     'Un email de confirmation vous a été envoyé pour la vérification de votre compte. Si le mail n\'apparait pas dans la boite de réception, veuillez vérifier dans les spams!'
  238.                 );
  239.                 return $this->redirectToRoute('app_verify_resend_email');
  240.             } else {
  241.                 $this->addFlash('error',  'Email inconnu.');
  242.             }
  243.         }
  244.         return $this->render('auth/resend_verify_email.html.twig', ['form' => $form->createView(), 'userEmail' => $userEmail]);
  245.     }
  246.     // /**
  247.     //  * @Route("/deconnexion", name="security.logout")
  248.     //  * @IsGranted("ROLE_USER")
  249.     //  */
  250.     #[Route('/deconnexion'name:'security.logout'methods: ["GET","POST"])]
  251.     #[IsGranted('ROLE_USER')]
  252.     public function logout()
  253.     {
  254.     }
  255.     // /**
  256.     //  * @Route("/mon-compte/utilisateurs/{id}/modification-mot-de-passe", name="security.update.pwd")
  257.     //  * @Security("is_granted('ROLE_USER')")
  258.     //  */
  259.     #[Route('/mon-compte/utilisateurs/{id}/modification-mot-de-passe'name:'security.update.pwd')]
  260.     #[IsGranted('ROLE_USER')]
  261.     public function updatePassword(User $userRequest $requestUserPasswordHasherInterface $passwordEncoder)
  262.     {
  263.         $loggedUser $this->getUser();
  264.         if ($loggedUser != $user) {
  265.             $this->addFlash(
  266.                 'error',
  267.                 'Vous n\'êtes pas autorisé à éffectuer cette action !'
  268.             );
  269.             return $this->redirectToRoute('my_account');
  270.         }
  271.         $form $this->createForm(UpdatePasswordType::class, $user);
  272.         $form->handleRequest($request);
  273.         if ($form->isSubmitted() && $form->isValid()) {
  274.             // $password = $passwordEncoder->encodePassword($user, $form->getData()->getPlainPassword());
  275.             $password $passwordEncoder->hashPassword($user$form->getData()->getPlainPassword());
  276.             $user->setPassword($password);
  277.             $this->manager->persist($user);
  278.             $this->manager->flush();
  279.             $this->addFlash(
  280.                 'success',
  281.                 'Votre mot de passe a bien été mise à jour !'
  282.             );
  283.             return $this->redirectToRoute('my_account');
  284.         }
  285.         return $this->render('auth/update_password.html.twig', ['form' => $form->createView()]);
  286.     }
  287.     // /**
  288.     //  * @Route("/go_to", name="go_to")
  289.     //  */
  290.     #[Route('/go_to'name:'go_to')]
  291.     public function go_to()
  292.     {
  293.         if (isset($_COOKIE["__ga_ru__"])) {
  294.             $url $_COOKIE["__ga_ru__"];
  295.             return $this->redirect($url);
  296.         } else {
  297.             return $this->redirectToRoute('app_front_home');
  298.         }
  299.     }
  300.     #[Route('/'name:'app_front_home'methods: ["GET","POST"])]
  301.     public function home()
  302.     {
  303.         // dd('HOME PAGE');
  304.         if (isset($_COOKIE["__ga_ru__"])) {
  305.             $url $_COOKIE["__ga_ru__"];
  306.             return $this->redirect($url);
  307.         } else {
  308.             return $this->redirect('https://www.abidjan.net',302);
  309.         }
  310.         // return $this->render('base.html.twig',[
  311.             
  312.         // ]);
  313.     }
  314. }