src/App/Controller/AuthenticationController.php line 287

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Association\Adherent;
  4. use App\Entity\Parametre\Utilisateur;
  5. use App\Form\Authenticator\AdherentActivateAccountType;
  6. use App\Form\Authenticator\ForgotPasswordType;
  7. use App\Form\Authenticator\LoginAuthenticatorType;
  8. use App\Form\Authenticator\RenewPasswordType;
  9. use App\Helper\MailerHelper;
  10. use App\Helper\UserHelper;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  15. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. class AuthenticationController extends AbstractAppController {
  18.     /**
  19.      * Reset the password.
  20.      * @Route("/adherent/active-account/{token}", name="adherent_active_account", defaults={"token": null})
  21.      */
  22.     public function activeAccountAdherent(Request $requestTranslatorInterface $translatorUserPasswordEncoderInterface $passwordEncoder$token null) {
  23.         // If user was already connected, redirect to home page.
  24.         if ($this->getUser() !== null || $this->getAppParameter("ASSOCIATION_EXTRANET_ENABLED") !== "1") {
  25.             return $this->redirectToRoute("app");
  26.         }
  27.         // If a token was defined.
  28.         if ($token !== null) {
  29.             // Create form.
  30.             $form $this->createForm(RenewPasswordType::class);
  31.             $form->handleRequest($request);
  32.             $output = [
  33.                 "localeLangage" => $translator->getLocale(),
  34.                 "token"         => $token,
  35.                 "form"          => $form->createView(),
  36.             ];
  37.             // Check if token length is valid.
  38.             if (strlen($token) !== 36) {
  39.                 $output["errorMessage"] = $translator->trans("app_adherent_active_account.error_invalid_link", [], "authenticator");
  40.                 return $this->render('Authentication/create-password.html.twig'$output);
  41.             }
  42.             // Find user by her reset token.
  43.             $user $this->em()->getRepository(Utilisateur::class)->findOneBy([
  44.                 "activeAccountToken" => $token,
  45.             ]);
  46.             // If not found.
  47.             if (null === $user) {
  48.                 $output["errorMessage"] = $translator->trans("app_adherent_active_account.error_invalid_link", [], "authenticator");
  49.                 return $this->render('Authentication/create-password.html.twig'$output);
  50.             }
  51.             // Check the platform.
  52.             if (false === in_array($user->getPlatformId(), [getenv("PLATFORM_ID")])) {
  53.                 $output["errorMessage"] = $translator->trans("app_adherent_active_account.error_invalid_link", [], "authenticator");
  54.                 return $this->render('Authentication/create-password.html.twig'$output);
  55.             }
  56.             // Check date expiration.
  57.             if ($user->getDateActiveAccountExpire()->getTimestamp() < time()) {
  58.                 $output["errorMessage"] = $translator->trans("app_adherent_active_account.error_time_expire", [], "authenticator");
  59.                 return $this->render('Authentication/create-password.html.twig'$output);
  60.             }
  61.             // If new password was submitted.
  62.             if ($form->isSubmitted() && $form->isValid()) {
  63.                 $password      $form->get("_password")->getData();
  64.                 $passwordAgain $form->get("_passwordAgain")->getData();
  65.                 if ($password !== $passwordAgain) {
  66.                     $output["errorMessageForm"] = $translator->trans("app_reset_password.not_similar_password", [], "authenticator");
  67.                     return $this->render('Authentication/create-password.html.twig'$output);
  68.                 }
  69.                 if (false === Utilisateur::isValidPassword($password)) {
  70.                     $output["errorMessageForm"] = $translator->trans("app_reset_password.critere_password", [], "authenticator");
  71.                     return $this->render('Authentication/create-password.html.twig'$output);
  72.                 }
  73.                 // Set the new password.
  74.                 $password $passwordEncoder->encodePassword($user$password);
  75.                 $user->setPassword($password);
  76.                 $user->setActiveAccountToken(null);
  77.                 $user->setDateActiveAccountExpire(null);
  78.                 $this->em()->flush();
  79.                 $output["successMessage"] = $translator->trans("app_adherent_active_account.success", [], "authenticator");
  80.                 return $this->render('Authentication/create-password.html.twig'$output);
  81.             }
  82.             $output["infoMessage"] = $translator->trans("app_adherent_active_account.finalize_when_password_defined", [], "authenticator");
  83.             return $this->render('Authentication/create-password.html.twig'$output);
  84.         }
  85.         // Create form.
  86.         $form $this->createForm(AdherentActivateAccountType::class);
  87.         $form->handleRequest($request);
  88.         if ($form->isSubmitted() && $form->isValid()) {
  89.             $locale $translator->getLocale();
  90.             $currentPlatformId getenv("PLATFORM_ID");
  91.             $email             $form->get("_username")->getData();
  92.             // Find user.
  93.             $findUser $this->em()->getRepository(Utilisateur::class)->findOneBy([
  94.                 "email"      => $email,
  95.                 "platformId" => $currentPlatformId,
  96.             ]);
  97.             // Si aucun compte n'existe avec l'adresse email de l'adhérent, on lui créer un compte.
  98.             if ($findUser === null) {
  99.                 $findAdherent $this->em()->getRepository(Adherent::class)->findBy([
  100.                     "email"         => $email,
  101.                     "platformId"    => $currentPlatformId,
  102.                     "accesExtranet" => true,
  103.                 ]);
  104.                 if (count($findAdherent) > 0) {
  105.                     $utilisateur = new Utilisateur();
  106.                     $utilisateur->setCivilite($findAdherent[0]->getCivilite());
  107.                     $utilisateur->setPrenom($findAdherent[0]->getPrenom());
  108.                     $utilisateur->setNom($findAdherent[0]->getNom());
  109.                     $utilisateur->setEmail($findAdherent[0]->getEmail());
  110.                     $utilisateur->setLang($this->getAppParameter("LANGUAGE"));
  111.                     $utilisateur->setRoles([Utilisateur::ROLE_ADHERENT]);
  112.                     $utilisateur->setPassword(-1);
  113.                     $utilisateur->setSocieteSelected($findAdherent[0]->getSociete());
  114.                     // Generate new token forgot password.
  115.                     $token $utilisateur->generateActiveAccountToken();
  116.                     $this->em()->persist($utilisateur);
  117.                     // If token was returned, new token was generated.
  118.                     if (false !== $token) {
  119.                         $this->em()->flush();
  120.                         // Set locale lang.
  121.                         if (null !== $utilisateur->getLang()) {
  122.                             $locale $utilisateur->getLang();
  123.                         }
  124.                         // Submit mail to user.
  125.                         $mailer = new MailerHelper($this->getParameter("smtp"), $this->container->get("twig"), $locale);
  126.                         $mailer->sendMail(
  127.                             "Authentication/email/adherent/active-account.html.twig",
  128.                             [
  129.                                 "token" => $utilisateur->getActiveAccountToken(),
  130.                             ],
  131.                             $utilisateur->getEmail()
  132.                         );
  133.                     }
  134.                 }
  135.             } else {
  136.                 // Si un compte existe avec l'adresse email et qu'il s'agit d'un compte adhérent non activé, on renvoi le mail d'activation.
  137.                 if (UserHelper::hasRole(Utilisateur::ROLE_ADHERENT$findUser) && $findUser->getActiveAccountToken() !== null) {
  138.                     // Generate new token forgot password.
  139.                     $token $findUser->generateActiveAccountToken();
  140.                     // If token was returned, new token was generated.
  141.                     if (false !== $token) {
  142.                         $this->em()->flush();
  143.                         // Set locale lang.
  144.                         if (null !== $findUser->getLang()) {
  145.                             $locale $findUser->getLang();
  146.                         }
  147.                         // Submit mail to user.
  148.                         $mailer = new MailerHelper($this->getParameter("smtp"), $this->container->get("twig"), $locale);
  149.                         $mailer->sendMail(
  150.                             "Authentication/email/adherent/active-account.html.twig",
  151.                             [
  152.                                 "token" => $findUser->getActiveAccountToken(),
  153.                             ],
  154.                             $findUser->getEmail()
  155.                         );
  156.                     }
  157.                 }
  158.                 // Si un compte existe avec l'adresse email et qu'il s'agit d'un compte adhérent déjà activé, on envoi un mail d'information.
  159.                 if (UserHelper::hasRole(Utilisateur::ROLE_ADHERENT$findUser) && $findUser->getActiveAccountToken() === null) {
  160.                     // Submit mail to user.
  161.                     $mailer = new MailerHelper($this->getParameter("smtp"), $this->container->get("twig"), $locale);
  162.                     $mailer->sendMail("Authentication/email/adherent/already-activated.html.twig.html.twig", [], $findUser->getEmail());
  163.                 }
  164.             }
  165.             return $this->render('Authentication/adherent/active-account.html.twig', [
  166.                 "localeLangage" => $translator->getLocale(),
  167.                 "submitted"     => true,
  168.             ]);
  169.         }
  170.         return $this->render('Authentication/adherent/active-account.html.twig', [
  171.             "localeLangage" => $translator->getLocale(),
  172.             "form"          => $form->createView(),
  173.         ]);
  174.     }
  175.     /**
  176.      * Forgot password.
  177.      * @Route("/forgot-password", name="forgot_password")
  178.      */
  179.     public function forgotPassword(Request $requestTranslatorInterface $translator): Response {
  180.         // If user was already connected, redirect to home page.
  181.         if ($this->getUser() !== null) {
  182.             return $this->redirectToRoute("app");
  183.         }
  184.         // Create form.
  185.         $form $this->createForm(ForgotPasswordType::class);
  186.         $form->handleRequest($request);
  187.         if ($form->isSubmitted() && $form->isValid()) {
  188.             $locale $translator->getLocale();
  189.             $currentPlatformId getenv("PLATFORM_ID");
  190.             $email             $form->get("_username")->getData();
  191.             // Find user.
  192.             $findUser $this->em()->getRepository(Utilisateur::class)->findOneBy([
  193.                 "email" => $email,
  194.             ]);
  195.             // If user was found and platform match.
  196.             if ($findUser !== null && true === in_array($currentPlatformId, [false$findUser->getPlatformId()])) {
  197.                 putenv("PLATFORM_ID={$findUser->getPlatformId()}");
  198.                 // Generate new token forgot password.
  199.                 $token $findUser->generateForgotPasswordToken();
  200.                 // If token was returned, new token was generated.
  201.                 if (false !== $token) {
  202.                     $this->em()->flush();
  203.                     // Set locale lang.
  204.                     if (null !== $findUser->getLang()) {
  205.                         $locale $findUser->getLang();
  206.                     }
  207.                     // Submit mail to user.
  208.                     $mailer = new MailerHelper($this->getParameter("smtp"), $this->container->get("twig"), $locale);
  209.                     $mailer->sendMail(
  210.                         "Authentication/email/forgot-password.html.twig",
  211.                         [
  212.                             "token" => $findUser->getResetPasswordToken(),
  213.                         ],
  214.                         $findUser->getEmail()
  215.                     );
  216.                 }
  217.             }
  218.             return $this->render('Authentication/forgot-password.html.twig', [
  219.                 "localeLangage" => $translator->getLocale(),
  220.                 "submitted"     => true,
  221.             ]);
  222.         }
  223.         return $this->render('Authentication/forgot-password.html.twig', [
  224.             "localeLangage" => $translator->getLocale(),
  225.             "form"          => $form->createView(),
  226.         ]);
  227.     }
  228.     /**
  229.      * Login.
  230.      * @Route("/login", name="login")
  231.      */
  232.     public function index(AuthenticationUtils $authenticationUtilsTranslatorInterface $translator): Response {
  233.         // If user was already connected, redirect to home page.
  234.         if ($this->getUser() !== null) {
  235.             return $this->redirectToRoute("app");
  236.         }
  237.         // Create form.
  238.         $form $this->createForm(LoginAuthenticatorType::class);
  239.         // get the login error if there is one
  240.         $error $authenticationUtils->getLastAuthenticationError();
  241.         // last username entered by the user
  242.         $lastUsername $authenticationUtils->getLastUsername();
  243.         return $this->render('Authentication/login.html.twig', [
  244.             'last_username' => $lastUsername,
  245.             'error'         => $error,
  246.             "localeLangage" => $translator->getLocale(),
  247.             "form"          => $form->createView(),
  248.         ]);
  249.     }
  250.     /**
  251.      * Logout user.
  252.      * @Route("/logout", name="app_logout")
  253.      */
  254.     public function logout() {
  255.         /** @var Utilisateur $user */
  256.         $user $this->getUser();
  257.         if (null !== $user) {
  258.             $user->setDateSessionExpiration(null);
  259.             $user->setSessionToken(null);
  260.         }
  261.         $this->em()->persist($user);
  262.         $this->em()->flush();
  263.         if (isset($_COOKIE['REMEMBERME'])) {
  264.             unset($_COOKIE['REMEMBERME']);
  265.             setcookie('REMEMBERME'null, -1'/');
  266.         }
  267.         session_destroy();
  268.         return $this->redirectToRoute("login");
  269.     }
  270.     /**
  271.      * Logout user.
  272.      * @Route("/process-logout", name="app_process_logout")
  273.      */
  274.     public function processLogout() {
  275.         throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  276.     }
  277.     /**
  278.      * Reset the password.
  279.      * @Route("/reset/{token}", name="reset_password")
  280.      */
  281.     public function resetPassword(Request $requestTranslatorInterface $translatorUserPasswordEncoderInterface $passwordEncoder$token) {
  282.         // If user was already connected, redirect to home page.
  283.         if ($this->getUser() !== null) {
  284.             return $this->redirectToRoute("app");
  285.         }
  286.         $isCreationPassword $request->query->has("configure");
  287.         $twigView           = ($isCreationPassword "create-password" "reset");
  288.         // Create form.
  289.         $form $this->createForm(RenewPasswordType::class);
  290.         $form->handleRequest($request);
  291.         $output = [
  292.             "localeLangage" => $translator->getLocale(),
  293.             "token"         => $token,
  294.             "form"          => $form->createView(),
  295.         ];
  296.         // Check if token length is valid.
  297.         if (strlen($token) !== 36) {
  298.             $output["errorMessage"] = $translator->trans("app_reset_password.error_invalid_link", [], "authenticator");
  299.             return $this->render('Authentication/' $twigView '.html.twig'$output);
  300.         }
  301.         // Find user by her reset token.
  302.         $user $this->em()->getRepository(Utilisateur::class)->findOneBy([
  303.             "resetPasswordToken" => $token,
  304.         ]);
  305.         // If not found.
  306.         if (null === $user) {
  307.             $output["errorMessage"] = $translator->trans("app_reset_password.error_invalid_link", [], "authenticator");
  308.             return $this->render('Authentication/' $twigView '.html.twig'$output);
  309.         }
  310.         // Check the platform.
  311.         if (false === in_array($user->getPlatformId(), [falsegetenv("PLATFORM_ID")])) {
  312.             $output["errorMessage"] = $translator->trans("app_reset_password.error_invalid_link", [], "authenticator");
  313.             return $this->render('Authentication/' $twigView '.html.twig'$output);
  314.         }
  315.         // Check date expiration.
  316.         if ($user->getDateResetPasswordExpire()->getTimestamp() < time()) {
  317.             $output["errorMessage"] = $translator->trans("app_reset_password.error_time_expire", [], "authenticator");
  318.             return $this->render('Authentication/' $twigView '.html.twig'$output);
  319.         }
  320.         // If new password was submitted.
  321.         if ($form->isSubmitted() && $form->isValid()) {
  322.             $password      $form->get("_password")->getData();
  323.             $passwordAgain $form->get("_passwordAgain")->getData();
  324.             if ($password !== $passwordAgain) {
  325.                 $output["errorMessageForm"] = $translator->trans("app_reset_password.not_similar_password", [], "authenticator");
  326.                 return $this->render('Authentication/' $twigView '.html.twig'$output);
  327.             }
  328.             if (false === Utilisateur::isValidPassword($password)) {
  329.                 $output["errorMessageForm"] = $translator->trans("app_reset_password.critere_password", [], "authenticator");
  330.                 return $this->render('Authentication/' $twigView '.html.twig'$output);
  331.             }
  332.             // Set the new password.
  333.             $password $passwordEncoder->encodePassword($user$password);
  334.             $user->setPassword($password);
  335.             $user->setDateResetPasswordExpire(null);
  336.             $user->setResetPasswordToken(null);
  337.             $this->em()->flush();
  338.             $output["successMessage"] = $translator->trans("app_reset_password.success_change", [], "authenticator");
  339.             return $this->render('Authentication/' $twigView '.html.twig'$output);
  340.         }
  341.         return $this->render('Authentication/' $twigView '.html.twig'$output);
  342.     }
  343. }