src/Controller/RegistrationController.php line 90

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\DTO\ForgetPasswordDT0;
  4. use App\Entity\User;
  5. use App\Entity\Category;
  6. use App\Form\PasswordForgetType;
  7. use App\Form\PasswordResetType;
  8. use App\Form\RegistrationFormType;
  9. use App\Security\App\Security\LoginFormAuthenticator;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Doctrine\ORM\Mapping as ORM;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  16. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  17. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  18. use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
  19. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  20. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  21. class RegistrationController extends AbstractController
  22. {
  23.     /**
  24.      *
  25.      * @Route("/forgotpassword" , name="forgotpassword")
  26.      */
  27.     public function forgotpassword(Request $requestEntityManagerInterface $em,UserPasswordEncoderInterface $passwordEncoder,AuthorizationCheckerInterface $securityContext, \Swift_Mailer $mailer,AuthenticationUtils $authenticationUtils)
  28.     {
  29.         $forget=new ForgetPasswordDT0();
  30.         $formForgotPwd $this->createForm(PasswordForgetType::class, $forget);
  31.         return $this->render('refonte/Authentification/password/forgotPassword.html.twig',
  32.             [
  33.                 'formForgotPwd' => $formForgotPwd->createView(),
  34.             ]);
  35.     }
  36.         /**
  37.      *
  38.      * @Route("/login" , name="login_new")
  39.      */
  40.     public function loginNew(Request $requestEntityManagerInterface $em,UserPasswordEncoderInterface $passwordEncoder,AuthorizationCheckerInterface $securityContext, \Swift_Mailer $mailer,AuthenticationUtils $authenticationUtils){
  41.         if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  42.             $user $this->getUser();
  43.             return $this->redirectToRoute('publication_index', ['id' => $user->getId(), 'firstname' => $user->getFirstName(), "lastname" => $user->getLastName()]);
  44.         }
  45.         $user = new User();
  46.         $form $this->createForm(RegistrationFormType::class, $user);
  47.         $error $authenticationUtils->getLastAuthenticationError();
  48.         // last username entered by the user
  49.         $lastUsername $authenticationUtils->getLastUsername();
  50.         return $this->render('refonte/Authentification/login.html.twig',
  51.             [
  52.                 'form' => $form->createView(),
  53.                 'last_username' => $lastUsername,
  54.                 'error' => $error,
  55.             ]);
  56.     }
  57.     /**
  58.      *
  59.      * @Route("/authentification" , name="registre_user")
  60.      */
  61.     public function formulaire(Request $requestEntityManagerInterface $em,UserPasswordEncoderInterface $passwordEncoder,AuthorizationCheckerInterface $securityContext, \Swift_Mailer $mailer,AuthenticationUtils $authenticationUtils)
  62.     {
  63.         $referer $request->headers->get('referer');
  64.         $refererPath parse_url($refererPHP_URL_PATH);
  65.         $paths=['/query','/authors'];
  66.         if(in_array($refererPath,$paths)) {
  67.             if ($refererPath == "/query") {
  68.                 $message "You need to log in to access more journal details";
  69.             }
  70.             if ($refererPath == "/authors") {
  71.                 $message "You need to log in to access more author details";
  72.             }
  73.             $this->addFlash('info'$message);
  74.         }
  75.         return $this->render('refonte/Authentification/registration-form.html.twig');
  76.     }
  77.     /**
  78.      * @Route("/user-registration", name="register")
  79.      */
  80.     public function register(
  81.         Request $request,
  82.         EntityManagerInterface $em,
  83.         UserPasswordEncoderInterface $passwordEncoder,
  84.         AuthorizationCheckerInterface $securityContext,
  85.         \Swift_Mailer $mailer,
  86.         AuthenticationUtils $authenticationUtils,
  87.         SessionInterface $session
  88.     ) {
  89.         // Redirect authenticated users to homepage
  90.         if ($securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  91.             return $this->redirectToRoute('homepage');
  92.         }
  93.         // Initialize forms
  94.         $user = new User();
  95.         $form $this->createForm(RegistrationFormType::class, $user);
  96.         $form->handleRequest($request);
  97.         // Handle registration form submission
  98.         if ($form->isSubmitted() && $form->isValid()) {
  99.             // Check if email already exists
  100.             $email $form->get('email')->getData();
  101.             $recaptcha=$request->get('g-recaptcha-response');
  102.             $mailExist $em->getRepository(User::class)->findOneBy(['email' => $email]);
  103.             if ($mailExist) {
  104.                 $this->addFlash('error''Email already exists');
  105.                 return $this->render('refonte/Authentification/register.html.twig', [
  106.                     'form' => $form->createView(),
  107.                     'categories' => $em->getRepository(Category::class)->findAll(),
  108.                 ]);
  109.             }
  110.             if(!$recaptcha){
  111.                 $this->addFlash('error''Please check the recaptcha');
  112.                 return $this->render('refonte/Authentification/register.html.twig', [
  113.                     'form' => $form->createView(),
  114.                     'categories' => $em->getRepository(Category::class)->findAll(),
  115.                 ]);
  116.             }
  117.             // Check email format
  118.             if (substr_count($email'.') > 2) {
  119.                 $this->addFlash('error''Email format must be valid (e.g., email@example.com)');
  120.                 return $this->render('refonte/Authentification/register.html.twig', [
  121.                     'form' => $form->createView(),
  122.                     'categories' => $em->getRepository(Category::class)->findAll(),
  123.                     'last_username' => $authenticationUtils->getLastUsername(),
  124.                     'error' => $authenticationUtils->getLastAuthenticationError(),
  125.                 ]);
  126.             }
  127.             // Process favorite categories
  128.             $favoriteCategories $form->get('categories')->getData();
  129.             $favoriteCategories preg_replace('/\s+/'' '$favoriteCategories);
  130.             if ($favoriteCategories) {
  131.                 $favoriteCategories explode(','$favoriteCategories);
  132.                 // trim to remove white spaces in array elements
  133.                 $favoriteCategories array_map('trim'$favoriteCategories);
  134.                 foreach ($favoriteCategories as $categoryName) {
  135.                     $categoryEntity $em->getRepository(Category::class)->findOneBy(['name' => $categoryName]);
  136.                     if ($categoryEntity) {
  137.                         $user->addCategory($categoryEntity);
  138.                     }
  139.                 }
  140.             }
  141.             // Encode password
  142.             $encodedPassword $passwordEncoder->encodePassword($user$form->get('password')->getData());
  143.             $user->setPassword($encodedPassword);
  144.             // Process full name
  145.             $fullName trim($form->get('fullName')->getData());
  146.             $firstname $fullName;
  147.             $lastname $fullName;
  148.             if (str_contains($fullName' ')) {
  149.                 $fullNameParts explode(' '$fullName);
  150.                 $firstname $fullNameParts[0];
  151.                 if (count($fullNameParts) > 1) {
  152.                     $lastname implode(' 'array_slice($fullNameParts1));
  153.                 }
  154.             }
  155.             $user->setFirstName($firstname);
  156.             $user->setLastName($lastname);
  157.             $user->setFullName("$firstname $lastname");
  158.             // Set other user details
  159.             $user->setGender($form->get('gender')->getData() ? strtoupper($form->get('gender')->getData()[0]) : null);
  160.             $user->setBirthday($form->get('birthday')->getData());
  161.             $user->setCountry($form->get('country')->getData());
  162.             $user->setPhone($form->get('phone')->getData());
  163.             $user->addRole('ROLE_USER');
  164.             $user->setCreatedAt(new \DateTime());
  165.             // Generate verification token
  166.             $verificationToken rand(-21474836482147483647);
  167.             $user->setToken($verificationToken);
  168.             // Persist user to the database
  169.             $em->persist($user);
  170.             $em->flush();
  171.             // Send verification email
  172.             $fromEmail getenv('ADMIN_EMAIL');
  173.             $body $this->renderView('email/verification_code.html.twig', [
  174.                 'verificationCode' => $verificationToken,
  175.                 "email"=>$user->getEmail(),
  176.             ]);
  177.             $emailMessage = (new \Swift_Message('Confirmation of your ResearchGuide registration'))
  178.                 ->setFrom($fromEmail)
  179.                 ->setTo($user->getEmail())
  180.                 ->setBody($body'text/html');
  181.             $mailer->send($emailMessage);
  182.             // Store unverified user email in session
  183.             $session->set('unverified_user_email'$user->getEmail());
  184.             // Redirect to verification page
  185.             return $this->redirectToRoute('verification_page');
  186.         } elseif ($form->isSubmitted() && !$form->isValid()) {
  187.             $success false;
  188.         }
  189.         // Render the registration page
  190.         return $this->render('refonte/Authentification/register.html.twig', [
  191.             'form' => $form->createView(),
  192.             'categories' => $em->getRepository(Category::class)->findAll(),
  193.             'last_username' => $authenticationUtils->getLastUsername(),
  194.             'error' => $authenticationUtils->getLastAuthenticationError(),
  195.         ]);
  196.     }
  197.     /**
  198.      *
  199.      * @Route("/media-registration" , name="registre_user_media")
  200.      */
  201.     public function registerMedia(Request $request){
  202.         $em $this->getDoctrine()->getManager();
  203.         $email$request->query->get('email');
  204.         $user $em->getRepository(User::class)->findOneBy(['email' => $email]);
  205.         $form $this->createForm(PasswordResetType::class, $user);
  206.         $form->handleRequest($request);
  207.         if ($form->isSubmitted() && $form->isValid()) {
  208.             $user $this->setUserPasswordAndSalt($form->getData(), $form);
  209.             $this->saveEntities();
  210.         }
  211.         return $this->render('connexion/register_media.html.twig', ['form'=> $form->createView()]);
  212.     }
  213.     /**
  214.      *
  215.      * @Route("/verify_email" , name="verify_email")
  216.      */
  217.     public function verifyEmail(Request $requestUserPasswordEncoderInterface $passwordEncoder,GuardAuthenticatorHandler $guardHandler,LoginFormAuthenticator $authenticator)
  218.     {
  219.         $em $this->getDoctrine()->getManager();
  220.         $code $request->query->get('code');
  221.         $user $em->getRepository(User::class)->findOneBy(['token' => $code]);
  222.         if ($user) {
  223.                 $user->setIsVerified(true);
  224.                 $user->setToken(null);
  225.                 $em->persist($user);
  226.                 $em->flush();
  227.             $guardHandler->authenticateUserAndHandleSuccess(
  228.                 $user,                  // L'utilisateur nouvellement créé
  229.                 $request,               // La requête en cours
  230.                 $authenticator,         // L'authenticator utilisé
  231.                 'guidejournal'          // Le firewall configuré dans security.yaml
  232.             );
  233. //            $this->addFlash('success', 'Your email has been verified successfully');
  234.             return $this->redirectToRoute('homepage');
  235.         } else {
  236.             $this->addFlash('error''Invalid email');
  237.         }
  238.         return $this->redirectToRoute('login_new');
  239.     }
  240. /**
  241.      *
  242.      * @Route("/reset-password" , name="reset-password" , methods={"POST"})
  243.      */
  244.     public function resetPasswordForm(Request $request,EntityManagerInterface $em, \Swift_Mailer $mailer,SessionInterface $session)
  245.     {
  246.         $forget=new ForgetPasswordDT0();
  247.         $formForgotPwd $this->createForm(PasswordForgetType::class, $forget);
  248.         $formForgotPwd->handleRequest($request);
  249.         if ($formForgotPwd->isSubmitted() && $formForgotPwd->isValid()) {
  250.             $emailForget $request->request->get('password_forget')['emailForget'];
  251.             $token $request->request->get('password_forget')['_token'];
  252.             $user=$em->getRepository(User::class)->findOneBy(['email' => $emailForget]);
  253.             if($user && (!$user->getIsDeleted() && !$user->getDeletedAt())){
  254.                 $user->setToken($token);
  255.                 $user->setIsVerified(false);
  256.                 $em->persist($user);
  257.                 $em->flush();
  258.                 $fromEmail=getenv("ADMIN_EMAIL");
  259.                 $body $this->renderView('email/password-forget-email.html.twig', ['user' => $user]);
  260.                 $email = (new \Swift_Message())
  261.                     ->setFrom($fromEmail)
  262.                     ->setTo($emailForget)
  263.                     ->setSubject('Reset password')
  264.                     ->setBody($body'text/html');
  265.                 $mailer->send($email);
  266.                 $session->set('reset_email'$user->getEmail());
  267.                 return $this->redirectToRoute('verification_page_email_forgot');
  268.             }else{
  269.                 $this->addFlash('error''This email does not exist');
  270.                 return $this->redirectToRoute('forgotpassword');
  271.             }
  272.         }
  273.         return $this->render('refonte/Authentification/password/forgotPassword.html.twig',['formForgotPwd' => $formForgotPwd->createView(),]);
  274.     }
  275.     /**
  276.      *
  277.      * @Route("/reset_password" , name="reset_password")
  278.      */
  279.     public function resetPassword(Request $requestUserPasswordEncoderInterface $passwordEncoder)
  280.     {
  281.         $em $this->getDoctrine()->getManager();
  282.         $email $request->query->get('email');
  283.         $user $em->getRepository(User::class)->findOneBy(['email' => $email]);
  284.             $form $this->createForm(PasswordResetType::class, $user);
  285.             $form->handleRequest($request);
  286.             if ($form->isSubmitted() && $form->isValid()) {
  287.                $email=$form->get('email')->getData();
  288.                 if(!$email){
  289.                     $this->addFlash('error''Email is required');
  290.                     return $this->render('refonte/Authentification/password/newPassword.html.twig', ['form'=> $form->createView(),'email'=>$email]);
  291.                 }
  292.                        $user $em->getRepository(User::class)->findOneBy(['email' => $email]);
  293.              $encodedPassword $passwordEncoder->encodePassword($user$form->get('password')->getData());
  294.                 if($passwordEncoder->isPasswordValid($user$form->get('password')->getData())){
  295.                 $this->addFlash('error''Your new password must be different to previously used passwords.');
  296.                 return $this->render('refonte/Authentification/password/newPassword.html.twig', ['form'=> $form->createView(),'email'=>$email]);
  297.             }
  298.              $user->setPassword($encodedPassword);
  299.                 $newVerificationToken rand(-21474836482147483647);
  300.                 $user->setToken($newVerificationToken);
  301.             $em->persist($user);
  302.             $em->flush();
  303.                // login the user after password reset
  304. //                $this->addFlash('success', 'Your password has been reset successfully');
  305. //                return $this->redirectToRoute('login_new');
  306.                 return $this->render('refonte/Authentification/password/newPassword-verified.html.twig', ['user'=> $user]);
  307.             }
  308.             return $this->render('refonte/Authentification/password/newPassword.html.twig', ['form'=> $form->createView(),'email'=>$email]);
  309.     }
  310.     /**
  311.      * @Route("/verification", name="verification_page")
  312.      */
  313.     public function verification(SessionInterface $sessionEntityManagerInterface $em)
  314.     {
  315.         $email $session->get('unverified_user_email');
  316.         if (!$email) {
  317.             return $this->redirectToRoute('register'); // Redirect to registration if no email is found
  318.         }
  319.         $user $em->getRepository(User::class)->findOneBy(['email' => $email]);
  320.         if (!$user) {
  321.             return $this->redirectToRoute('register'); // Redirect to registration if user does not exist
  322.         }
  323.         return $this->render('refonte/Authentification/verification/verification.html.twig', [
  324.             'user' => $user,
  325.         ]);
  326.     }
  327.     /**
  328.      * @Route("/verification-email-forgot", name="verification_page_email_forgot")
  329.      */
  330.     public function verificationEmailForgot(SessionInterface $sessionEntityManagerInterface $em){
  331.         $email $session->get('reset_email');
  332.         $user $em->getRepository(User::class)->findOneBy(['email' => $email]);
  333.         if (!$user) {
  334.             $this->addFlash('error''This email does not exist');
  335.         }
  336.         return $this->render('refonte/Authentification/verification/verification-email-forgot.html.twig', [
  337.             'user' => $user,
  338.         ]);
  339.     }
  340.     /**
  341.      * @Route("/resend-verification-forgot-password", name="resend_verification_forgot_password")
  342.      */
  343.     public function resendVerificationForgotPassword(SessionInterface $sessionEntityManagerInterface $em, \Swift_Mailer $mailer){
  344.         // Get user email from session
  345.         $email $session->get('reset_email');
  346.         $user=$em->getRepository(User::class)->findOneBy(['email' => $email]);
  347.         if($user){
  348.             $fromEmail=getenv("ADMIN_EMAIL");
  349.             $body $this->renderView('email/password-forget-email.html.twig', ['user' => $user]);
  350.             $email = (new \Swift_Message())
  351.                 ->setFrom($fromEmail)
  352.                 ->setTo($email)
  353.                 ->setSubject('Reset password')
  354.                 ->setBody($body'text/html');
  355.             $mailer->send($email);
  356.         }
  357.         return $this->redirectToRoute('verification_page_email_forgot');
  358.     }
  359.     /**
  360.      * @Route("/resend-verification", name="resend_verification")
  361.      */
  362.     public function resendVerification(SessionInterface $sessionEntityManagerInterface $em, \Swift_Mailer $mailer)
  363.     {
  364.         $email $session->get('unverified_user_email');
  365.         if (!$email) {
  366.             return $this->redirectToRoute('register'); // Redirect to registration if no email is found
  367.         }
  368.         $user $em->getRepository(User::class)->findOneBy(['email' => $email]);
  369.         if (!$user) {
  370.             return $this->redirectToRoute('register'); // Redirect to registration if user does not exist
  371.         }
  372.         // Generate a new verification token
  373.         $newVerificationToken rand(-21474836482147483647);
  374.         $user->setToken($newVerificationToken);
  375.         $em->persist($user);
  376.         $em->flush();
  377.         // Send verification email
  378.         $fromEmail getenv("ADMIN_EMAIL");
  379.         $body $this->renderView('email/verification_code.html.twig', ['verificationCode' => $newVerificationToken,'user'=>$user]);
  380.         $emailMessage = (new \Swift_Message())
  381.             ->setFrom($fromEmail)
  382.             ->setTo($user->getEmail())
  383.             ->setSubject('Resend: Confirmation of your ResearchGuide registration')
  384.             ->setBody($body'text/html');
  385.         $mailer->send($emailMessage);
  386.         $this->addFlash('success''A new verification email has been sent to your email address.');
  387.         return $this->redirectToRoute('verification_page');
  388.     }
  389.     /**
  390.      * @Route("/pre_verify_email", name="pre_verify_email")
  391.      */
  392.     public function preVerifyEmail(Request $request)
  393.     {
  394.         $code=$request->request->get('code');
  395.         if($code){
  396.             $em $this->getDoctrine()->getManager();
  397.             $user $em->getRepository(User::class)->findOneBy(['token' => $code]);
  398.             if ($user) {
  399.                 return $this->render('refonte/Authentification/verification/email-verified.html.twig', ['user' => $user]);
  400.             }
  401.         }
  402.         return $this->redirectToRoute('login_new');
  403.     }
  404. }