<?php
namespace App\Controller;
use App\Services\CustomerService;
use App\Services\SSOApi;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\HttpFoundation\RedirectResponse;
use App\Entity\Wcocon;
use App\Entity\Wdeclar;
use App\Entity\Wtype;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class DefaultController extends AbstractController
{
/**
* @var ParameterBagInterface
*/
private $params;
/**
* @var UrlGeneratorInterface
*/
private $urlGenerator;
/**
* @var EntityManagerInterface
*/
private $entityManager;
/**
* @var Request|null
*/
private $request;
/**
* @var AuthenticationProviderManager
*/
private $authManager;
/**
* @var SessionAuthenticationStrategyInterface
*/
private $sessionStrategy;
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
/**
* @var EventDispatcherInterface
*/
private $dispatcher;
/**
* @var CustomerService
*/
private $customerService;
public function __construct(
CustomerService $customerService,
ParameterBagInterface $params,
UrlGeneratorInterface $urlGenerator,
RequestStack $requestStack,
EntityManagerInterface $entityManager,
AuthenticationManagerInterface $authManager,
SessionAuthenticationStrategyInterface $sessionStrategy,
TokenStorageInterface $tokenStorage,
EventDispatcherInterface $dispatcher
) {
$this->customerService = $customerService;
$this->params = $params;
$this->urlGenerator = $urlGenerator;
$this->request = $requestStack->getCurrentRequest();
$this->entityManager = $entityManager;
$this->authManager = $authManager;
$this->sessionStrategy = $sessionStrategy;
$this->tokenStorage = $tokenStorage;
$this->dispatcher = $dispatcher;
}
/**
* @Route("/deconnexion", name="security_logout")
*/
public function logout()
{
$this->tokenStorage->setToken(null);
$this->request->getSession()->invalidate();
}
/**
* @Route("/", name="index")
*/
public function login(Request $request,AuthenticationUtils $authenticationUtils): Response
{
$backUsername = $this->request->get('backToken', null);
$cookieChecked = $this->request->get('cookieChecked', null);
if ( ! $backUsername && ! $cookieChecked) {
//check cookie
$postAppKeyParam = 'appKey=' . $this->customerService->encryptParameter($this->params->get('webapp_key'));
$postAppSecretParam = '&appSecret=' . $this->customerService->encryptParameter($this->params->get('webapp_secret'));
$postUrlBackLinkParam = '&urlBackLink=' . $this->customerService->encryptParameter($this->urlGenerator->generate('index',
[], UrlGeneratorInterface::ABSOLUTE_URL));
return new RedirectResponse($this->params->get('sso_server_cache_saved_check') . '?' . $postAppKeyParam . $postAppSecretParam . $postUrlBackLinkParam,
Response::HTTP_MOVED_PERMANENTLY);
}
if ($backUsername && $cookieChecked) {
$user_data = json_decode($this->customerService->getUserDetail()->getContent());
$user = $this->customerService->syncUser($user_data);
$token = new UsernamePasswordToken(
$user,
$backUsername,//$user->getPassword(),
'main', // firewall name in security.yaml
['ROLE_USER']
);
$authenticatedToken = $this->authManager->authenticate($token);
$this->tokenStorage->setToken($authenticatedToken);
}
$auth_checker = $this->get('security.authorization_checker');
$isRoleUser = $auth_checker->isGranted('ROLE_USER');
if ($isRoleUser) {
$targetPath = $request->getSession()->get('_security.main.target_path');
if(!empty($targetPath)){
return new RedirectResponse($targetPath);
}else{
return new RedirectResponse($this->params->get('cocon_server_address'));
}
//return new RedirectResponse($this->generateUrl('interface_open'));
}else{
return new RedirectResponse($this->params->get('cocon_server_address'));
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('default/index.html.twig', [
'last_username' => $lastUsername,
'error' => $error
]);
}
/**
* @param null $partner_name
*
* @return JsonResponse
*
* @Route(name="login_check", path="/api/login_check")
*/
public function loginCheckAction(Request $request, SSOApi $crmApi)
{
$url = '/api/v1/security/login-grant';
$postFields = [
'username' => $request->get('_username'),
'password' => $request->get('_password'),
];
[$res, $code] = $crmApi->request($url, true, $postFields);
if ($res['status'] !== 'ok') {
return new JsonResponse([$res['message']]);
}
$this->customerService->logUser($request->get('_username'), $request->get('_password'));
return new JsonResponse([
'token' => $res['data']['tokens']['access_token']['hash'],
'refresh_token' => $res['data']['tokens']['refresh_token']['hash'],
'name' => $res['data']['user']['username'],
]);
}
}