src/Controller/SecurityController.php line 107

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.             $users $userRepository->findAllUserByEmaiAndEmailParent($email);
  73.             $user null;
  74.             foreach ($users as $u) {
  75.                 if ($u->isEnabled() and !$u->isDeleted()) {
  76.                     $user $u;
  77.                     break;
  78.                 }
  79.             }
  80.             if($user == null ) {
  81.                return  $this->redirectToRoute('request_login_without_password',['message_login_without_password'=>'unknown-email']);
  82.             }
  83.             $token hash('sha256'uniqid(preg_replace('/\s/','-',$user->getFullName())));
  84.       
  85.             $user->setOneTimeLoginToken($token);
  86.             $entityManager->flush();
  87.             $event = new UserLoginWithoutPasswordEvent($user$token);
  88.             $dispatcher->dispatch($eventUserLoginWithoutPasswordEvent::NAME);
  89.             return  $this->redirectToRoute('app_login',['message_login_without_password'=>'send-success']);
  90.         }
  91.     
  92.        
  93.         return $this->render('security/login_without_password.html.twig', []);
  94.     }
  95.      /**
  96.      * @Route("/login/{token}", name="login-without-passWord")
  97.      */
  98.     public function loginWithoutPassWordHttpClientInterface $httpClientParameterBagInterface $parameterBag,  string $token,TokenStorageInterface $tokenStorage,  UserRepository $userRepository,EntityManagerInterface $entityManager,Request $request): Response
  99.     {
  100.         if ($request->query->get('role')) {
  101.             $request->getSession()->set('role_current_user'$request->query->get('role'));
  102.         }
  103.         $user $userRepository->findOneBy(['oneTimeLoginToken' => $token]);
  104.         if($user){
  105.            if($user->isDeleted() or !$user->isEnabled()){
  106.                 return $this->redirectToRoute('app_login',['message_login_without_password'=>'not-enabled']);
  107.            }
  108.             $authenticatedToken = new UsernamePasswordToken($usernull'main'$user->getRoles());
  109.             
  110.             $tokenStorage->setToken($authenticatedToken);
  111.             // $user->setOneTimeLoginToken(null);
  112.             // $entityManager->flush();
  113.             if (in_array("ROLE_ADMIN"$user->getRoles()) || in_array("ROLE_SUBCONTRACTOR",$user->getRoles())) {
  114.                 
  115.                 return $this->redirectToRoute('mission_index');
  116.             }
  117.            ///////////////
  118.            $redirectToWp in_array("ROLE_AUTHOR"$user->getRoles()) || in_array("ROLE_EDITOR"$user->getRoles()) ? true false;
  119.            // $response = $httpClient->request('GET', $parameterBag->get('front_website_url'), [
  120.            //      'query' => [
  121.            //          'tsso' => hash('sha256', $user->getEmail() . $user->getEmail()),
  122.            //          'discount'=> 0
  123.            //      ],
  124.            //      'max_redirects' => 0,
  125.            //  ]);
  126.     
  127.            //  $headers = $response->getHeaders(false);
  128.            //  foreach ($headers['set-cookie'] ?? [] as $cookie) {
  129.            //      $infos = explode(';', $cookie);
  130.            //      [$name, $value] = explode('=', $infos[0]);
  131.     
  132.            //      foreach ($infos as $info) {
  133.            //          if (preg_match('#path#', $info)) {
  134.            //              [$str, $path] = explode('=', $info);
  135.            //          }
  136.            //      }
  137.     
  138.            //      setrawcookie($name, $value, 0, $path ?? '', str_replace('https://', '', $parameterBag->get('front_website_url')));
  139.            //  }
  140.             ////////////
  141.             $ch curl_init();
  142.             
  143.             $url "{$parameterBag->get('front_website_url')}/?tsso=" hash('sha256'$user->getEmail() . $user->getEmail());
  144.             curl_setopt($chCURLOPT_URL$url);
  145.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  146.             $result curl_exec($ch);
  147.             curl_close($ch);
  148.             //set session if switch connection is active
  149.             if ($request->query->get('role')) {
  150.                 $request->getSession()->set('role_current_user'$request->query->get('role'));
  151.             }
  152.             //end set session
  153.             return $redirectToWp ?  $this->redirect("{$parameterBag->get('front_website_url')}/wp-admin") : $this->redirectToRoute('mission_index');
  154.         }
  155.         
  156.         return $this->redirectToRoute('app_login',['message_login_without_password'=>'unknown-token']);
  157.         
  158.     }
  159.     /**
  160.      * @Route("/logout", name="app_logout")
  161.      */
  162.     public function logout(): void
  163.     {
  164.         // This method intentionally left blank.
  165.     }
  166. }