src/Controller/SecurityController.php line 71

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Event\User\UserLoginWithoutPasswordEvent;
  4. use App\Repository\UserRepository;
  5. use App\Service\NotificationService;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use App\Entity\Company;
  15. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  16. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  17. use Symfony\Component\Mime\Address;
  18. // use Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface;
  19. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  20. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  21. use Symfony\Contracts\HttpClient\HttpClientInterface;
  22. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  23. class SecurityController extends AbstractController
  24. {
  25.     /**
  26.      * @Route("/login", name="app_login")
  27.      */
  28.     public function login(AuthenticationUtils $authenticationUtilsRequest $requestSessionInterface $session,EntityManagerInterface $entityManager,UrlMatcherInterface $urlMatcherInterface): Response
  29.     {
  30.         
  31.         $url $request->getUri();
  32.         $pattern "/^(https?:\/\/)?([a-zA-Z0-9.-]+)/";
  33.         preg_match($pattern$url$matches);
  34.         $sousDomaine $matches[2];
  35.         $company $entityManager->getRepository(Company::class)->findCompanyBySubDomain($sousDomaine);
  36.         if (null !== $request->query->get('redirect_to')) {
  37.             $session->set('redirect_to'$request->query->get('redirect_to'));
  38.             return $this->redirectToRoute('app_login');
  39.         }
  40.         if ($this->getUser()) {
  41.             if (null !== $redirect $session->get('redirect_to')) {
  42.                 $session->remove('redirect_to');
  43.             }
  44.             return $this->redirectToRoute('mission_index');
  45.         }
  46.         // get the login error if there is one
  47.         $error $authenticationUtils->getLastAuthenticationError();
  48.         // last username entered by the user
  49.         $lastUsername $authenticationUtils->getLastUsername();
  50.          if (isset($_COOKIE['PHPSESSID'])) {
  51.             setcookie('PHPSESSID'''time() - 14444444444444444'/''.my-flow.fr'truetrue);
  52.         }
  53.         return $this->render('security/login.html.twig', [
  54.             'last_username' => $lastUsername
  55.             'error' => $error,
  56.             'company' => $company
  57.         ]);
  58.     }
  59.      /**
  60.      * @Route("/login/request-login-without-password", name="request_login_without_password")
  61.      */
  62.     public function createAuthWithoutPassword(Request $request,EventDispatcherInterface $dispatcherEntityManagerInterface $entityManagerUserRepository $userRepository): Response JsonResponse
  63.     {
  64.       
  65.         if($request->isMethod('POST')){
  66.             $email $request->request->get('email');
  67.           
  68.             if($email == null) {
  69.                return  $this->redirectToRoute('request_login_without_password',['message_login_without_password'=>'unknown-email']);
  70.             }
  71.             
  72.             $user $userRepository->findOneBy(['email'=>$email]);
  73.             if($user == null ) {
  74.                return  $this->redirectToRoute('request_login_without_password',['message_login_without_password'=>'unknown-email']);
  75.             }
  76.             $token hash('sha256'uniqid(preg_replace('/\s/','-',$user->getFullName())));
  77.       
  78.             $user->setOneTimeLoginToken($token);
  79.             $entityManager->flush();
  80.             $event = new UserLoginWithoutPasswordEvent($user$token);
  81.             $dispatcher->dispatch($eventUserLoginWithoutPasswordEvent::NAME);
  82.             return  $this->redirectToRoute('app_login',['message_login_without_password'=>'send-success']);
  83.         }
  84.     
  85.        
  86.         return $this->render('security/login_without_password.html.twig', []);
  87.     }
  88.      /**
  89.      * @Route("/login/{token}", name="login-without-passWord")
  90.      */
  91.     public function loginWithoutPassWordHttpClientInterface $httpClientParameterBagInterface $parameterBag,  string $token,TokenStorageInterface $tokenStorage,  UserRepository $userRepository,EntityManagerInterface $entityManager,Request $request): Response
  92.     {
  93.         if ($request->query->get('role')) {
  94.             $request->getSession()->set('role_current_user'$request->query->get('role'));
  95.         }
  96.         $user $userRepository->findOneBy(['oneTimeLoginToken' => $token]);
  97.         if($user){
  98.            if($user->isDeleted() or !$user->isEnabled()){
  99.                 return $this->redirectToRoute('app_login',['message_login_without_password'=>'not-enabled']);
  100.            }
  101.             $authenticatedToken = new UsernamePasswordToken($usernull'main'$user->getRoles());
  102.             
  103.             $tokenStorage->setToken($authenticatedToken);
  104.             // $user->setOneTimeLoginToken(null);
  105.             // $entityManager->flush();
  106.             if (in_array("ROLE_ADMIN"$user->getRoles()) || in_array("ROLE_SUBCONTRACTOR",$user->getRoles())) {
  107.                 
  108.                 return $this->redirectToRoute('mission_index');
  109.             }
  110.            ///////////////
  111.            $redirectToWp in_array("ROLE_AUTHOR"$user->getRoles()) || in_array("ROLE_EDITOR"$user->getRoles()) ? true false;
  112.            // $response = $httpClient->request('GET', $parameterBag->get('front_website_url'), [
  113.            //      'query' => [
  114.            //          'tsso' => hash('sha256', $user->getEmail() . $user->getEmail()),
  115.            //          'discount'=> 0
  116.            //      ],
  117.            //      'max_redirects' => 0,
  118.            //  ]);
  119.     
  120.            //  $headers = $response->getHeaders(false);
  121.            //  foreach ($headers['set-cookie'] ?? [] as $cookie) {
  122.            //      $infos = explode(';', $cookie);
  123.            //      [$name, $value] = explode('=', $infos[0]);
  124.     
  125.            //      foreach ($infos as $info) {
  126.            //          if (preg_match('#path#', $info)) {
  127.            //              [$str, $path] = explode('=', $info);
  128.            //          }
  129.            //      }
  130.     
  131.            //      setrawcookie($name, $value, 0, $path ?? '', str_replace('https://', '', $parameterBag->get('front_website_url')));
  132.            //  }
  133.             ////////////
  134.             $ch curl_init();
  135.             
  136.             $url "{$parameterBag->get('front_website_url')}/?tsso=" hash('sha256'$user->getEmail() . $user->getEmail());
  137.             curl_setopt($chCURLOPT_URL$url);
  138.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  139.             $result curl_exec($ch);
  140.             curl_close($ch);
  141.             //set session if switch connection is active
  142.             if ($request->query->get('role')) {
  143.                 $request->getSession()->set('role_current_user'$request->query->get('role'));
  144.             }
  145.             //end set session
  146.             return $redirectToWp ?  $this->redirect("{$parameterBag->get('front_website_url')}/wp-admin") : $this->redirectToRoute('mission_index');
  147.         }
  148.         
  149.         return $this->redirectToRoute('app_login',['message_login_without_password'=>'unknown-token']);
  150.         
  151.     }
  152.     /**
  153.      * @Route("/logout", name="app_logout")
  154.      */
  155.     public function logout(): void
  156.     {
  157.         // This method intentionally left blank.
  158.     }
  159. }