src/Controller/SecurityController.php line 31

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): Response
  92.     {
  93.        
  94.         $user $userRepository->findOneBy(['oneTimeLoginToken' => $token]);
  95.         if($user){
  96.            if($user->isDeleted() or !$user->isEnabled()){
  97.                 return $this->redirectToRoute('app_login',['message_login_without_password'=>'not-enabled']);
  98.            }
  99.             $authenticatedToken = new UsernamePasswordToken($usernull'main'$user->getRoles());
  100.             $tokenStorage->setToken($authenticatedToken);
  101.             // $user->setOneTimeLoginToken(null);
  102.             // $entityManager->flush();
  103.             if (in_array("ROLE_ADMIN"$user->getRoles()) || in_array("ROLE_SUBCONTRACTOR",$user->getRoles())) {
  104.              
  105.                 return $this->redirectToRoute('mission_index');
  106.             }
  107.            ///////////////
  108.            $redirectToWp in_array("ROLE_AUTHOR"$user->getRoles()) || in_array("ROLE_EDITOR"$user->getRoles()) ? true false;
  109.            // $response = $httpClient->request('GET', $parameterBag->get('front_website_url'), [
  110.            //      'query' => [
  111.            //          'tsso' => hash('sha256', $user->getEmail() . $user->getEmail()),
  112.            //          'discount'=> 0
  113.            //      ],
  114.            //      'max_redirects' => 0,
  115.            //  ]);
  116.     
  117.            //  $headers = $response->getHeaders(false);
  118.            //  foreach ($headers['set-cookie'] ?? [] as $cookie) {
  119.            //      $infos = explode(';', $cookie);
  120.            //      [$name, $value] = explode('=', $infos[0]);
  121.     
  122.            //      foreach ($infos as $info) {
  123.            //          if (preg_match('#path#', $info)) {
  124.            //              [$str, $path] = explode('=', $info);
  125.            //          }
  126.            //      }
  127.     
  128.            //      setrawcookie($name, $value, 0, $path ?? '', str_replace('https://', '', $parameterBag->get('front_website_url')));
  129.            //  }
  130.             ////////////
  131.             $ch curl_init();
  132.             
  133.             $url "{$parameterBag->get('front_website_url')}/?tsso=" hash('sha256'$user->getEmail() . $user->getEmail());
  134.             curl_setopt($chCURLOPT_URL$url);
  135.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  136.             $result curl_exec($ch);
  137.             curl_close($ch);
  138.             return $redirectToWp ?  $this->redirect("{$parameterBag->get('front_website_url')}/wp-admin") : $this->redirectToRoute('mission_index');
  139.         }
  140.         
  141.         return $this->redirectToRoute('app_login',['message_login_without_password'=>'unknown-token']);
  142.         
  143.     }
  144.     /**
  145.      * @Route("/logout", name="app_logout")
  146.      */
  147.     public function logout(): void
  148.     {
  149.         // This method intentionally left blank.
  150.     }
  151. }