src/Controller/AuthController.php line 195

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Dto\Request\DtoSaveInstructorRequest;
  4. use App\Entity\Contact;
  5. use App\Entity\Prestashop\Customers;
  6. use App\Form\ContactAskPasswordResetType;
  7. use App\Form\ContactResetType;
  8. use App\Helper\StringHelper;
  9. use App\Repository\ContactRepository;
  10. use App\Security\ConnectAsAuthenticator;
  11. use App\Security\ConnectAsAuthenticatorextends;
  12. use App\Security\WebsiteFormAuthenticator;
  13. use App\Service\ContactManager;
  14. use App\Service\InstructorService;
  15. use App\Service\LanguageManager;
  16. use App\Service\NotificationManager;
  17. use App\Service\NotificationService;
  18. use Doctrine\ORM\EntityManagerInterface;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\HttpFoundation\RequestStack;
  21. use Symfony\Component\HttpFoundation\Response;
  22. use Symfony\Component\Routing\RouterInterface;
  23. use Symfony\Component\Security\Core\Security;
  24. use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
  25. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  26. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  27. class AuthController extends EntityController
  28. {
  29.     use TargetPathTrait;
  30.     private ContactManager $contactManager;
  31.     /**
  32.      * ApiController constructor.
  33.      * @param EntityManagerInterface $em
  34.      * @param ContactManager $contactManager
  35.      * @param NotificationManager $notificationManager
  36.      * @param RequestStack $request
  37.      * @param LanguageManager $languageManager
  38.      */
  39.     public function __construct(EntityManagerInterface $em,
  40.                                 ContactManager $contactManager,
  41.                                 NotificationManager $notificationManager,
  42.                                 RequestStack $request,
  43.                                 LanguageManager $languageManager,
  44.                                 NotificationService $notificationService)
  45. //<<<<<<< HEAD
  46. //                                LanguageManager $languageManager,
  47. //                                SessionInterface $session,
  48. //                                NotificationService $notificationService)
  49. //    {
  50. //        parent::__construct($em, $notificationManager, $request, $languageManager, $session, $notificationService);
  51. //=======
  52. //                                LanguageManager $languageManager)
  53.     {
  54.         parent::__construct($em$notificationManager$request$languageManager$notificationService);
  55. //>>>>>>> 92-achat-unique
  56.         $this->contactManager $contactManager;
  57.     }
  58.     /**
  59.      * This is a form for a customer to ask to change password for the email submitted.
  60.      * Route : /password-reset
  61.      * @param Request $request
  62.      * @return Response
  63.      */
  64.     public function viewAskPasswordReset(Request $requestRouterInterface $router) : Response
  65.     {
  66.         $this->getNavigationContext($request$router);
  67.         $emptyAccount = (new Contact())
  68.             ->setPassword('12345')
  69.             ->setRepeatedPassword('12345');
  70.         // generate the form with the email
  71.         // todo : add captcha ?
  72.         $form $this->createForm(ContactAskPasswordResetType::class, $emptyAccount);
  73.         // Get the email from the form and process like apiAskPasswordReset
  74.         if ($request->isMethod('POST')) {
  75.             $form->submit($request->request->get($form->getName()));
  76.             // If form is correct
  77.             if ($form->isSubmitted()) {
  78.                 $email $emptyAccount->getEmail();
  79.                 $contact $this->contactManager->getContactByMail($email);
  80.                 // get account by mail
  81.                 if(!is_null($contact)){
  82.                     // if the user has no validity date or a old validity date
  83.                     $this->contactManager->sendResetPassword($contact$this->language$this->viewData["context"]);
  84.                 }
  85.                 else{
  86.                     $this->notificationManager::addError('Le compte n\'existe pas');
  87.                 }
  88.             }
  89.         }
  90.         $this->createFlashs();
  91.         $this->addViewDataObject('form'$form->createView())
  92.             ->addViewDataArray('response'$this->getMessages());
  93.         return $this->render('contact/ask_account_password_reset.html.twig',
  94.             $this->viewData
  95.         );
  96.     }
  97.     /**
  98.      * The FORM to reset password with password and repeated password
  99.      * Route : ResetPassword
  100.      * @param Request $request
  101.      * @return Response
  102.      */
  103.     public function viewResetPassword(Request $requestRouterInterface $router) : Response
  104.     {
  105.         $token $request->query->get('token'''); // the static + the temporary token
  106.         //test data = 86ae4cbe2a4650d7fa91655948c6e5de38ba907fdd0eff7ea4085efc7a780dd3
  107.         $this->getNavigationContext($request$router);
  108.         if(empty($token) || strlen($token) !== 128){
  109.             $this->notificationManager::addError('Utilisateur non valable');
  110. //            $this->notificationManager::addError('86ae4cbe2a4650d7fa91655948c6e5de38ba907fdd0eff7ea4085efc7a780dd3' . $this->getTemporaryAccessToken('toto@toto.com'));
  111.         }
  112.         else{
  113.             $staticToken substr($token064); // The account static token
  114.             $currentAccount $this->contactManager->getContactByStaticToken($staticToken);
  115.             // Check if the email exists and the token is correct
  116.             if($currentAccount !== null
  117.                 && $currentAccount->getResetPasswordValidity() !== null
  118.                 && $currentAccount->getResetPasswordValidity() <= new \DateTime('NOW')
  119.             ){
  120.                 $this->notificationManager::addError('Utilisateur non valable ou délai dépassé : réessayez');
  121.                 $this->createFlashs();
  122.                 return $this->redirectToRoute('Index',
  123.                     $this->viewData
  124.                 );
  125.             }
  126.             else{
  127.                 // Now we add the form to change the password
  128.                 $form $this->createForm(ContactResetType::class, $currentAccount);
  129.                 if ($request->isMethod('POST')) {
  130.                     $form->submit($request->request->get($form->getName()));
  131.                     // If form is correct
  132.                     if ($form->isSubmitted() && $form->isValid()){
  133.                         // save the account
  134.                         $clearPassword $currentAccount->getPassword();
  135.                         if($this->contactManager->updatePasswordFromToken($currentAccount->getEmail(), $currentAccount->getPassword(), $staticToken)){
  136.                             $this->notificationManager::addInfo("Mot de passe mis à jour");
  137.                             $contact $this->contactManager->getContactByMail($currentAccount->getEmail());
  138.                             $contact->setLastConnexion();
  139.                             $this->entityManager->flush();
  140.                         }
  141.                         else{
  142.                             $this->notificationManager::addError("Utilisateur invalide");
  143.                         }
  144.                         // if the account exists on Prestashop
  145.                         $psCustomer Customers::getByEmail($currentAccount->getEmail(),true);
  146.                         // Insert the user if he doesn't exist
  147.                         if(!is_null($psCustomer)){
  148.                             if($psCustomer->updatePassword($clearPassword) !==0){
  149.                                 $this->notificationManager::addInfo("Mot de passe modifié sur Prestashop");
  150.                             }
  151.                         }
  152.                         $this->createFlashs();
  153.                         return $this->redirectToRoute('PreLogin', [
  154.                             "brandCode" => $_GET["brandCode"] ?? null,
  155.                             "apiKey" => $_GET["apiKey"] ?? null,
  156.                         ]);
  157.                     }
  158.                 }
  159.                 $this->createFlashs();
  160.                 $this->addViewDataObject('form'$form->createView())
  161.                     ->addViewDataArray('response'$this->getMessages());
  162.                 return $this->render('contact/account_password_reset.html.twig',
  163.                     $this->viewData
  164.                 );
  165.             }
  166.         }
  167.         return $this->render('home.html.twig', ['response' => $this->getMessages()]);
  168.     }
  169.     /**
  170.      * Login to the app
  171.      * Set a session with the contact and all related accounts
  172.      * Route : login
  173.      * @param Request $request
  174.      * @return Response
  175.      */
  176.     public function viewPreLogin(Request $requestRouterInterface $router): Response
  177.     {
  178. //        dd($request->getSession()->get('_security.default.target_path'));
  179.         if (isset($_GET["lang"]) && StringHelper::isNullOrEmptyWithSpace($_GET["lang"]) == false)
  180.         {
  181.             return $this->redirectToRoute('PreLogin', [
  182.                 "_locale" => $_GET["lang"],
  183.                 "brandCode" => $_GET["brandCode"]?? null,
  184.                 "apiKey" => $_GET["apiKey"]?? null
  185.             ]);
  186.         }
  187.         if($_ENV["MAINTENANCE"] === "true") {
  188.             return $this->render('maintainance.html.twig'$this->viewData);
  189.         }
  190.         $responseAction 'pre-login';
  191.         $response null;
  192.         $data = [];
  193.         if(isset($_COOKIE["contactDeleted"])) {
  194.             $this->notificationManager::addError('Oops, il y a un souci ! Soit il y a eu une erreur avec votre adresse email, soit nos serveurs sont pris d\'assaut par trop de monde en même temps. Veuillez vérifier votre saisie ou réessayer plus tard :)');
  195.         }
  196.         // If user is connected
  197.         /*if (!is_null($this->getUser())) {
  198.             $responseAction = 'ContactAccounts';
  199.         }*/
  200.         if (!is_null($this->getUser())) {
  201.             if(!is_null($request->getSession()->get('_security.default.target_path'))) {
  202.                 return $this->redirect($request->getSession()->get('_security.default.target_path'));
  203.             }
  204.             else {
  205.                 $responseAction 'ContactAccounts';
  206.             }
  207.         }
  208.         else{
  209.             $this->getNavigationContext($request$router);
  210.             $submitted $request->request->get('submitLogin');
  211.             // if the form is submitted
  212.             if(!is_null($submitted)){
  213.                 $contactEmail $request->request->get('email');
  214.                 // If the email address exists and is a correct email address
  215.                 if(!is_null($contactEmail) || !filter_var($contactEmailFILTER_VALIDATE_EMAIL)){
  216.                     $contact $this->contactManager->getContactByMail($contactEmail);
  217.                     // Si le contact n'est pas trouvé, on tente de le rechercher dans salesforce et de le synchroniser
  218.                     if (is_null($contact))
  219.                     {
  220.                         $contact $this->contactManager->syncContactFormSF($contactEmail);
  221.                     }
  222.                     // If the contact exists
  223.                     if(!is_null($contact)){
  224.                         // If its the first connexion
  225.                         if(is_null($contact->getLastConnexion())){
  226.                             $this->contactManager->getContactByMail($contactEmail);
  227.                             if(strpos($request->getSession()->get('_security.default.target_path'), 'external_access/buy')) {
  228.                                 $currentContact $this->entityManager->getRepository(Contact::class)->findOneBy(['email' => $contactEmail]);
  229.                                 $currentContact->setInternalReturnUrl($request->getSession()->get('_security.default.target_path'));
  230.                                 $this->entityManager->persist($currentContact);
  231.                                 $this->entityManager->flush();
  232.                             }
  233.                             $responseAction 'FirstConnexionResetPassword';
  234.                         }
  235.                         // if its a normal connexion
  236.                         else{
  237.                             $responseAction 'Login';
  238.                             if($request->request->get('brandCode') != null && $request->request->get('brandCode') != "") {
  239.                                 $brandCode $request->request->get('brandCode');
  240.                                 $data['brandCode'] = $brandCode;
  241.                             }
  242.                             if($request->request->get('apiKey') != null && $request->request->get('apiKey') != "") {
  243.                                 $apiKey $request->request->get('apiKey');
  244.                                 $data['apiKey'] = $apiKey;
  245.                             }
  246.                         }
  247.                         $data['email'] = $contact->getEmail();
  248.                     }
  249.                     // contact not existing
  250.                     else{
  251.                         if($request->request->get('brandCode') != null && $request->request->get('brandCode') != "") {
  252.                             $brandCode $request->request->get('brandCode');
  253.                             $data['brandCode'] = $brandCode;
  254.                         }
  255.                         $responseAction 'Register';
  256.                         $data['email'] = $contactEmail;
  257. //                        $this->notificationManager::addError('Le compte n\'existe pas.');
  258.                     }
  259.                 }
  260.                 // Contact email not filled
  261.                 else{
  262.                     $this->notificationManager::addError('Adresse email incorrecte');
  263.                 }
  264.             }
  265.             $this->createFlashs();
  266.         }
  267.         if ($responseAction === 'ContactAccounts'){
  268.             $response $this->redirectToRoute('ContactAccounts');
  269.         }
  270.         elseif ($responseAction === 'FirstConnexionResetPassword'){
  271.             $data["brandCode"] = $_GET["brandCode"]?? null;
  272.             $data["apiKey"] = $_GET["apiKey"]?? null;
  273.             $response $this->redirectToRoute('FirstConnexionResetPassword'$data);
  274.         }
  275.         elseif ($responseAction === 'Login'){
  276.             $response $this->redirectToRoute('Login'$data);
  277.         }
  278.         elseif ($responseAction === 'Register'){
  279.             $response $this->redirectToRoute('Register'$data);
  280.         }
  281.         else{
  282.             $response $this->render('login/pre-login.html.twig'$this->viewData);
  283.         }
  284.         return $response;
  285.     }
  286.     /**
  287.      * Login to the app
  288.      * Set a session with the contact and all related accounts
  289.      * Route : login
  290.      * @param AuthenticationUtils $authenticationUtils
  291.      * @param Request $request
  292.      * @return Response
  293.      */
  294.     public function viewLogin(AuthenticationUtils $authenticationUtilsRequest $requestRouterInterface $router): Response
  295.     {
  296.         $responseRoute 'Login';
  297.         $data = [];
  298.         if (!is_null($this->getUser())) {
  299.             $responseRoute 'ContactAccounts';
  300.         }
  301.         else{
  302.             $this->getNavigationContext($request$router);
  303.             $contactEmail $request->query->get('email');
  304.             if(is_null($contactEmail)){
  305.                 $responseRoute 'PreLogin';
  306.             }
  307.             else{
  308. //                if(is_null($contactEmail)){
  309. //                    $contactEmail = $authenticationUtils->getLastUsername();
  310. //                }
  311.                 // get the login error if there is one
  312.                 $error $authenticationUtils->getLastAuthenticationError();
  313.                 // last username entered by the user
  314.                 $lastUsername $authenticationUtils->getLastUsername();
  315.                 $this->addViewDataString('last_username'$lastUsername)
  316.                     ->addViewDataObject('error'$error)
  317.                     ->addViewDataString('email'$contactEmail);
  318.             }
  319.         }
  320.         $this->createFlashs();
  321.         if($responseRoute === 'ContactAccounts'){
  322.             $response $this->redirectToRoute('ContactAccounts');
  323.         }
  324.         elseif($responseRoute === 'PreLogin'){
  325.             $response $this->redirectToRoute('PreLogin');
  326.         }
  327.         else{
  328.             $response $this->render('login/login.html.twig'$this->viewData);
  329.         }
  330.         return $response;
  331.     }
  332.     public function logout()
  333.     {
  334.     }
  335.     /**
  336.      * First connexion email
  337.      * @param Request $request
  338.      * @return Response
  339.      */
  340.     public function viewFirstConnexionResetPassword(Request $requestRouterInterface $router) : Response
  341.     {
  342.         $contactEmail $request->query->get('email''');
  343.         $contact $this->contactManager->getContactByMail($contactEmail);
  344.         $this->getNavigationContext($request$router);
  345.         if(!is_null($contact) && is_null($contact->getLastConnexion())){
  346.             // if the user has no validity date or a old validity date
  347.             $this->contactManager->sendResetPassword($contact$this->language$this->viewData['context']);
  348. //            $contact->setLastConnexion();
  349. //            $this->entityManager->flush();
  350.         }
  351.         else{
  352.             $this->notificationManager::addError('Le compte n\'existe pas ou l\'e-mail de première connexion a déjà été envoyé');
  353.         }
  354.         $this->createFlashs();
  355.         return $this->render('contact/first_connexion_ask_account_password_reset.html.twig'$this->viewData);
  356.     }
  357.     /**
  358.      * Register account
  359.      * @param Request $request
  360.      * @return Response
  361.      */
  362.     public function viewRegisterAccount(Request $requestRouterInterface $routerInstructorService $instructorServiceGuardAuthenticatorHandler $guardWebsiteFormAuthenticator $autoLoginAuthenticator) : Response
  363.     {
  364.         if (!is_null($this->getUser()) || $this->language == 'it') {
  365.             $responseRoute $this->redirectToRoute('ContactAccounts'$this->viewData);
  366.         }
  367.         else {
  368.             $this->getNavigationContext($request$router);
  369.             $dtoRequest = new DtoSaveInstructorRequest();
  370.             $submitted $request->request->get('submitRegister');
  371.             // if the form is submitted
  372.             if (!is_null($submitted)) {
  373.                 $dtoRequest->email $request->request->get('email') ?? '';
  374.                 $dtoRequest->emailCompta $request->request->get('email') ?? '';
  375.                 $dtoRequest->lastName $request->request->get('lastName') ?? '';
  376.                 $dtoRequest->firstName $request->request->get('firstName') ?? '';
  377.                 $dtoRequest->phone $request->request->get('phone') ?? '';
  378.                 $dtoRequest->address $request->request->get('address') ?? '';
  379.                 $dtoRequest->zipCode $request->request->get('zipCode') ?? '';
  380.                 $dtoRequest->city $request->request->get('city') ?? '';
  381.                 $dtoRequest->siret $request->request->get('siret') ?? '';
  382.                 $dtoRequest->tva $request->request->get('tva') ?? '';
  383.                 $dtoRequest->password $request->request->get('password') ?? '';
  384.                 $dtoRequest->checkPassword $request->request->get('checkPassword') ?? '';
  385.                 $dtoRequest->billingCountryCode $request->request->get('country') ?? '';
  386.                 $dtoRequest->isPro $request->request->get('isPro');
  387.                 $dtoResponse $instructorService->createInstructor($dtoRequest);
  388.                 $this->createFlashsFromDtoResponse($dtoResponse);
  389.                 if($dtoResponse->isSuccess()) {
  390.                     $referent $this->contactManager->fillSessionContactFromContactEmail($dtoRequest->email);
  391.                     $request->getSession()->set(Security::LAST_USERNAME$request->get('email'));
  392.                     $request->getSession()->set('contact'$referent);
  393.                     $request->getSession()->set('contactCsrfToken'$this->contactManager->getContactApiTokenByEmail($dtoRequest->email));
  394.                     // Handle user as if he just logged-in
  395.                     // after validating the user and saving it to the database
  396.                     // authenticate the user and use onAuthenticationSuccess on the authenticator
  397.                     $user $this->contactManager->getContactByMail($dtoRequest->email);
  398.                     $guard->authenticateUserAndHandleSuccess(
  399.                         $user,
  400.                         $request,
  401.                         $autoLoginAuthenticator,
  402.                         'main'
  403.                     );
  404.                     $responseRoute $this->redirectToRoute('PreLogin'$this->viewData);
  405.                 } else {
  406.                     $this->addViewDataObject('newInstructorAccount'$dtoRequest);
  407.                     $responseRoute $this->render('contact/register.html.twig'$this->viewData);
  408.                 }
  409.             } else {
  410.                 $responseRoute $this->render('contact/register.html.twig'$this->viewData);
  411.             }
  412.         }
  413.         return $responseRoute;
  414.     }
  415.     /**
  416.      * Autologin from Salesforce
  417.      * path: /{_locale}/switch
  418.      * name: SwitchUser
  419.      * @return \Symfony\Component\HttpFoundation\Response
  420.      */
  421.     public function switchUser(GuardAuthenticatorHandler $guardSecurity $securityConnectAsAuthenticator $customAuthenticatorRequest $request)
  422.     {
  423.         if ($this->getUser() == null)
  424.         {
  425.             $this->saveTargetPath($request->getSession(), "default"$request->getUri());
  426.             return $this->redirectToRoute('PreLogin');
  427.         }
  428.         $user $this->entityManager->getRepository(Contact::class)->findOneBy(["email" => $request->get("email")]);
  429.         if ($user == null || $security->isGranted('ROLE_ADMIN') == false)
  430.         {
  431.             throw $this->createNotFoundException("L'action demandée ne peut pas être exécutée.");
  432.         }
  433.         else
  434.         {
  435.             $currentUser $security->getUser();
  436.             $customAuthenticator->setCurrentUser($currentUser);
  437.             // Handle user as if he just logged-in
  438.             // after validating the user and saving it to the database
  439.             // authenticate the user and use onAuthenticationSuccess on the authenticator
  440.             $guard->authenticateUserAndHandleSuccess(
  441.                 $user,
  442.                 $request,
  443.                 $customAuthenticator,
  444.                 'main'
  445.             );
  446.             // Redirection vers la page Home
  447.             return $this->redirectToRoute('ContactAccounts');
  448.         }
  449.     }
  450.     /**
  451.      * disconnect to previous account from Salesforce
  452.      * path: /{_locale}/exit
  453.      * name: ExitUser
  454.      * @return Response
  455.      */
  456.     public function exitUser(GuardAuthenticatorHandler $guardSecurity $securityConnectAsAuthenticator $customAuthenticatorRequest $request) : Response
  457.     {
  458.         // Récupération des données de l'administrateur dans la session
  459.         $previousAdminUsername $request->getSession()->get('previousAdminUsername');
  460.         if (StringHelper::isNullOrEmptyWithSpace($previousAdminUsername) == false)
  461.         {
  462.             $user $this->entityManager->getRepository(Contact::class)->findOneBy(["email" => $previousAdminUsername]);
  463.             if ($user == null)
  464.             {
  465.                 throw $this->createNotFoundException("L'action demandée ne peut pas être exécutée.");
  466.             }
  467.             else
  468.             {
  469.                 $customAuthenticator->setCurrentUser(null);
  470.                 $guard->authenticateUserAndHandleSuccess(
  471.                     $user,
  472.                     $request,
  473.                     $customAuthenticator,
  474.                     'main'
  475.                 );
  476.                 // Redirection vers la page Home
  477.                 return $this->redirectToRoute('ContactAccounts');
  478.             }
  479.         }
  480.         else
  481.         {
  482.             throw $this->createNotFoundException("L'action demandée ne peut pas être exécutée.");
  483.         }
  484.     }
  485. }