src/Controller/DefaultController.php line 112

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Services\CustomerService;
  4. use App\Services\SSOApi;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  8. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  9. use Symfony\Component\Form\FormInterface;
  10. use Symfony\Component\Form\Extension\Core\Type\TextType;
  11. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  12. use Symfony\Component\HttpFoundation\Cookie;
  13. use Symfony\Component\HttpFoundation\JsonResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\RequestStack;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\Routing\Annotation\Route;
  18. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  19. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  20. use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
  21. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  22. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  23. use Symfony\Component\Security\Core\Security;
  24. use Symfony\Component\Security\Core\User\UserInterface;
  25. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  26. use Symfony\Component\HttpFoundation\RedirectResponse;
  27. use App\Entity\Wcocon;
  28. use App\Entity\Wdeclar;
  29. use App\Entity\Wtype;
  30. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  31. use Symfony\Component\Security\Http\SecurityEvents;
  32. use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
  33. use Symfony\Component\EventDispatcher\EventDispatcher;
  34. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  35. class DefaultController extends AbstractController
  36. {
  37.     /**
  38.      * @var ParameterBagInterface
  39.      */
  40.     private $params;
  41.     /**
  42.      * @var UrlGeneratorInterface
  43.      */
  44.     private $urlGenerator;
  45.     /**
  46.      * @var EntityManagerInterface
  47.      */
  48.     private $entityManager;
  49.     /**
  50.      * @var Request|null
  51.      */
  52.     private $request;
  53.     /**
  54.      * @var AuthenticationProviderManager
  55.      */
  56.     private $authManager;
  57.     /**
  58.      * @var SessionAuthenticationStrategyInterface
  59.      */
  60.     private $sessionStrategy;
  61.     /**
  62.      * @var TokenStorageInterface
  63.      */
  64.     private $tokenStorage;
  65.     /**
  66.      * @var EventDispatcherInterface
  67.      */
  68.     private $dispatcher;
  69.     /**
  70.      * @var CustomerService
  71.      */
  72.     private $customerService;
  73.     public function __construct(
  74.         CustomerService $customerService,
  75.         ParameterBagInterface $params,
  76.         UrlGeneratorInterface $urlGenerator,
  77.         RequestStack $requestStack,
  78.         EntityManagerInterface $entityManager,
  79.         AuthenticationManagerInterface $authManager,
  80.         SessionAuthenticationStrategyInterface $sessionStrategy,
  81.         TokenStorageInterface $tokenStorage,
  82.         EventDispatcherInterface $dispatcher
  83.     ) {
  84.         $this->customerService $customerService;
  85.         $this->params          $params;
  86.         $this->urlGenerator    $urlGenerator;
  87.         $this->request         $requestStack->getCurrentRequest();
  88.         $this->entityManager   $entityManager;
  89.         $this->authManager     $authManager;
  90.         $this->sessionStrategy $sessionStrategy;
  91.         $this->tokenStorage    $tokenStorage;
  92.         $this->dispatcher      $dispatcher;
  93.     }
  94.     /**
  95.      * @Route("/deconnexion", name="security_logout")
  96.      */
  97.     public function logout()
  98.     {
  99.         $this->tokenStorage->setToken(null);
  100.         $this->request->getSession()->invalidate();
  101.     }
  102.     /**
  103.      * @Route("/", name="index")
  104.      */
  105.     public function login(Request $request,AuthenticationUtils $authenticationUtils): Response
  106.     {
  107.         $backUsername  $this->request->get('backToken'null);
  108.         $cookieChecked $this->request->get('cookieChecked'null);
  109.         if (  ! $backUsername && ! $cookieChecked) {
  110.             //check cookie
  111.             $postAppKeyParam      'appKey=' $this->customerService->encryptParameter($this->params->get('webapp_key'));
  112.             $postAppSecretParam   '&appSecret=' $this->customerService->encryptParameter($this->params->get('webapp_secret'));
  113.             $postUrlBackLinkParam '&urlBackLink=' $this->customerService->encryptParameter($this->urlGenerator->generate('index',
  114.                     [], UrlGeneratorInterface::ABSOLUTE_URL));
  115.             return new RedirectResponse($this->params->get('sso_server_cache_saved_check') . '?' $postAppKeyParam $postAppSecretParam $postUrlBackLinkParam,
  116.                 Response::HTTP_MOVED_PERMANENTLY);
  117.         }
  118.         if ($backUsername && $cookieChecked) {
  119.             $user_data json_decode($this->customerService->getUserDetail()->getContent());
  120.             $user $this->customerService->syncUser($user_data);
  121.             $token = new UsernamePasswordToken(
  122.                 $user,
  123.                 $backUsername,//$user->getPassword(),
  124.                 'main'// firewall name in security.yaml
  125.                 ['ROLE_USER']
  126.             );
  127.             $authenticatedToken $this->authManager->authenticate($token);
  128.             $this->tokenStorage->setToken($authenticatedToken);
  129.         }
  130.         $auth_checker $this->get('security.authorization_checker');
  131.         $isRoleUser $auth_checker->isGranted('ROLE_USER');
  132.         if ($isRoleUser) {
  133.             $targetPath $request->getSession()->get('_security.main.target_path');
  134.             if(!empty($targetPath)){
  135.                 return new RedirectResponse($targetPath);
  136.             }else{
  137.                 return new RedirectResponse($this->params->get('cocon_server_address'));
  138.             }
  139.             //return new RedirectResponse($this->generateUrl('interface_open'));
  140.         }else{
  141.             return new RedirectResponse($this->params->get('cocon_server_address'));
  142.         }
  143.         // get the login error if there is one
  144.         $error $authenticationUtils->getLastAuthenticationError();
  145.         // last username entered by the user
  146.         $lastUsername $authenticationUtils->getLastUsername();
  147.         return $this->render('default/index.html.twig', [
  148.             'last_username' => $lastUsername,
  149.             'error'         => $error
  150.         ]);
  151.     }
  152.     /**
  153.      * @param null $partner_name
  154.      *
  155.      * @return JsonResponse
  156.      *
  157.      * @Route(name="login_check", path="/api/login_check")
  158.      */
  159.     public function loginCheckAction(Request $requestSSOApi $crmApi)
  160.     {
  161.         $url '/api/v1/security/login-grant';
  162.         $postFields = [
  163.             'username' => $request->get('_username'),
  164.             'password' => $request->get('_password'),
  165.         ];
  166.         [$res$code] = $crmApi->request($urltrue$postFields);
  167.         
  168.         if ($res['status'] !== 'ok') {
  169.             return new JsonResponse([$res['message']]);
  170.         }
  171.         $this->customerService->logUser($request->get('_username'), $request->get('_password'));
  172.         return new JsonResponse([
  173.             'token'         => $res['data']['tokens']['access_token']['hash'],
  174.             'refresh_token' => $res['data']['tokens']['refresh_token']['hash'],
  175.             'name'          => $res['data']['user']['username'],
  176.         ]);
  177.     }
  178. }