src/Controller/SecurityController.php line 95

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Constants\Setting;
  4. use App\Constants\Setting as SettingConst;
  5. use App\Constants\Sso;
  6. use App\Entity\User;
  7. use App\Exception\EncryptionException;
  8. use App\Factory\Security\SecurityFormFactory;
  9. use App\Form\Type\LoginType;
  10. use App\Services\Common\ModuleSettingService;
  11. use App\Services\Common\SettingService;
  12. use App\Services\Common\User\WorkflowUser;
  13. use App\Services\Common\UserService;
  14. use App\Services\DTV\YamlConfig\YamlReader;
  15. use App\Services\Security\EncryptionManager;
  16. use App\Services\Security\RegisterService;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use Exception;
  19. use LogicException;
  20. use Psr\Container\ContainerExceptionInterface;
  21. use Psr\Container\NotFoundExceptionInterface;
  22. use Psr\Log\LoggerInterface;
  23. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  24. use Symfony\Component\HttpFoundation\RedirectResponse;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\HttpFoundation\Response;
  27. use Symfony\Component\Routing\Annotation\Route;
  28. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  29. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  30. use Symfony\Component\Translation\TranslatableMessage;
  31. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  32. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  33. /**
  34. * Controller qui gère la sécurité
  35. */
  36. class SecurityController extends AbstractController
  37. {
  38. private YamlReader $yamlReader;
  39. private SecurityFormFactory $formFactory;
  40. private SettingService $settingService;
  41. private EntityManagerInterface $em;
  42. private RegisterService $registerService;
  43. private EncryptionManager $encryptionManager;
  44. private WorkflowUser $workflowUser;
  45. private LoggerInterface $logger;
  46. private string $env;
  47. private UserService $userService;
  48. private ModuleSettingService $moduleSettingService;
  49. public function __construct(YamlReader $yamlReader, SecurityFormFactory $formFactory, SettingService $settingService, EntityManagerInterface $em, RegisterService $registerService, EncryptionManager $encryptionManager, WorkflowUser $workflowUser, LoggerInterface $logger, string $env, UserService $userService, ModuleSettingService $moduleSettingService)
  50. {
  51. $this->yamlReader = $yamlReader;
  52. $this->formFactory = $formFactory;
  53. $this->settingService = $settingService;
  54. $this->em = $em;
  55. $this->registerService = $registerService;
  56. $this->encryptionManager = $encryptionManager;
  57. $this->workflowUser = $workflowUser;
  58. $this->logger = $logger;
  59. $this->env = $env;
  60. $this->userService = $userService;
  61. $this->moduleSettingService = $moduleSettingService;
  62. }
  63. /**
  64. * Formulaire de connexion
  65. *
  66. * @Route("/login", name="app_login")
  67. *
  68. * @param AuthenticationUtils $authenticationUtils
  69. * @param Request $request
  70. *
  71. * @return Response
  72. *
  73. * @throws EncryptionException
  74. * @throws ResetPasswordExceptionInterface
  75. * @throws TransportExceptionInterface
  76. * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
  77. */
  78. public function login(AuthenticationUtils $authenticationUtils, Request $request): Response
  79. {
  80. return $this->processLogin($authenticationUtils, $request);
  81. }
  82. /**
  83. * Formulaire de connexion secondaire
  84. *
  85. * @Route("/login-admin", name="app_login_admin")
  86. *
  87. * @param AuthenticationUtils $authenticationUtils
  88. * @param Request $request
  89. *
  90. * @return Response
  91. * @throws EncryptionException
  92. * @throws ResetPasswordExceptionInterface
  93. * @throws TransportExceptionInterface
  94. * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
  95. */
  96. public function loginAdmin(AuthenticationUtils $authenticationUtils, Request $request): Response
  97. {
  98. if($this->settingService->isExist(Setting::SSO_SETTINGS) && $this->moduleSettingService->isModuleActive(Sso::MODULE_NAME))
  99. {
  100. return $this->processLogin($authenticationUtils, $request, 'security/login_admin.html.twig');
  101. }
  102. throw $this->createNotFoundException();
  103. }
  104. /**
  105. * @throws TransportExceptionInterface
  106. * @throws ResetPasswordExceptionInterface
  107. * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
  108. * @throws EncryptionException
  109. * @throws Exception
  110. */
  111. protected function processLogin(AuthenticationUtils $authenticationUtils, Request $request, ?string $twigPath = null): Response
  112. {
  113. // On gère ici si on est sur un Portail/enfant
  114. $setting = $this->settingService->getSettingFromName(SettingConst::PORTAL_CHILDREN);
  115. $values = $setting !== NULL ? json_decode($setting->getValue(), TRUE) : [];
  116. $hasParent = !empty($values['parent_url']);
  117. if($hasParent)
  118. {
  119. $header = $request->headers;
  120. if($header->has('q') || $request->query->get('q'))
  121. {
  122. $q = base64_decode($header->get('q') ?? $request->query->get('q'));
  123. try
  124. {
  125. $q = $this->encryptionManager->decrypt($q);
  126. } catch(Exception $e)
  127. {
  128. $this->addFlash('danger', 'Un problème est survenu lors de la connexion');
  129. $this->logger->error('Erreur lors du décryptage du token de connexion', ['error' => $e->getMessage()]);
  130. return $this->redirectToRoute('app_login');
  131. }
  132. $q = json_decode($q, TRUE);
  133. $user = $this->em->getRepository(User::class)->findOneByEmailOrExtension([
  134. 'email' => $q['email'],
  135. 'extension1' => $q['extension1'],
  136. 'extension2' => $q['extension2'],
  137. ]);
  138. if($user instanceof User)
  139. {
  140. if($q['email'] !== $user->getEmail())
  141. {
  142. $user
  143. ->setEmail($q['email'])
  144. ->setFirstname($q['firstName'])
  145. ->setLastname($q['lastName'])
  146. ->setRoles($q['roles'])
  147. ;
  148. $this->registerService->registerReplaceFakeUserBySellerCode($user, $q['extension1'], TRUE);
  149. }
  150. // Gestion du cas où l'utilisateur existe en BDD (pas en fakeUser) mais ne s'est pas encore connecté à la plateforme
  151. if($q['cguAt'] !== NULL && $user->getStatus() === 'cgu_pending')
  152. {
  153. $this->workflowUser->acceptCGU($user);
  154. $user->setCguAt(new \DateTime($q['cguAt']));
  155. $this->em->flush();
  156. }
  157. // Créer un token de connexion
  158. $token = new UsernamePasswordToken($user, 'app', $user->getRoles());
  159. // Stocker le token dans le token storage
  160. try
  161. {
  162. $this->container->get('security.token_storage')->setToken($token);
  163. } catch(NotFoundExceptionInterface|ContainerExceptionInterface $e)
  164. {
  165. $this->addFlash('danger', 'Un problème est survenu lors de la connexion');
  166. $this->logger->error('Erreur lors de la récupération du token storage', ['error' => $e->getMessage()]);
  167. return $this->redirectToRoute('front_homepage');
  168. }
  169. }
  170. else
  171. {
  172. // on delog l'user
  173. $this->get('security.token_storage')->setToken(NULL);
  174. $this->logger->info('L\'utilisateur n\'existe pas en BDD', ['email' => $q['email']]);
  175. $request->getSession()->invalidate();
  176. }
  177. }
  178. }
  179. // Redirige sur la home-page si l'user est connecté
  180. if($this->getUser()) return $this->redirectToRoute('front_homepage');
  181. $user = $this->userService->initUser();
  182. $config = $this->yamlReader->getFrontSecurity();
  183. $configLogin = $config['login'];
  184. $globalRegister = $this->yamlReader->getRegister();
  185. $globalRegisterEnabled = $globalRegister['enabled'];
  186. $configRegister = $configLogin['sections']['section_register'] ?? FALSE;
  187. $hasFormRegister = FALSE;
  188. $formRegister = FALSE;
  189. if($globalRegisterEnabled && is_array($configRegister) && $configRegister['enabled'])
  190. {
  191. // Création du formulaire d'inscription
  192. try
  193. {
  194. $formRegister = $this->formFactory->generateRegisterForm($user);
  195. $hasFormRegister = TRUE;
  196. } catch(Exception $e)
  197. {
  198. throw $this->createNotFoundException($e->getMessage());
  199. }
  200. $formRegister->handleRequest($request);
  201. if($formRegister->isSubmitted())
  202. {
  203. // Validation spécifique du formulaire d'inscription
  204. try
  205. {
  206. $formRegister = $this->formFactory->postValidateRegisterForm($formRegister);
  207. } catch(Exception $e)
  208. {
  209. if($this->env != 'prod') throw $e;
  210. $this->addFlash('danger', new TranslatableMessage('impossible d\'exécuter la post validation du formulaire', []));
  211. $this->logger->error('Erreur lors de la post validation du formulaire d\'inscription', ['error' => $e->getMessage()]);
  212. $referer = $request->headers->get('referer');
  213. return $this->redirect($referer);
  214. }
  215. if($formRegister->isValid())
  216. {
  217. // Post traitement du formulaire d'inscription
  218. try
  219. {
  220. $response = $this->formFactory->postProcessingRegisterForm($formRegister, $user);
  221. } catch(Exception $e)
  222. {
  223. if($this->env != 'prod') throw $e;
  224. $this->addFlash('danger', 'impossible d\'exécuter le post traitement du formulaire');
  225. $this->logger->error('Erreur lors du post traitement du formulaire d\'inscription', ['error' => $e->getMessage()]);
  226. $referer = $request->headers->get('referer');
  227. return $this->redirect($referer);
  228. } catch(TransportExceptionInterface $e)
  229. {
  230. if($this->env != 'prod') throw $e;
  231. $this->addFlash('danger', 'impossible d\'exécuter le post traitement du formulaire');
  232. $this->logger->error('Erreur lors du post traitement du formulaire d\'inscription', ['error' => $e->getMessage()]);
  233. $referer = $request->headers->get('referer');
  234. return $this->redirect($referer);
  235. }
  236. if($response['message'] !== NULL)
  237. {
  238. $this->addFlash('success', $response['message']);
  239. }
  240. return $this->redirectToRoute($response['route']);
  241. }
  242. }
  243. }
  244. $formLogin = $this->createForm(LoginType::class);
  245. // get the login error if there is one
  246. $error = $authenticationUtils->getLastAuthenticationError();
  247. // last username entered by the user
  248. $lastUsername = $authenticationUtils->getLastUsername();
  249. if(!$twigPath)
  250. {
  251. $twigPath = 'security/login.html.twig';
  252. if(isset($configLogin['folder']) && !in_array($configLogin['folder'], [FALSE, '', NULL], TRUE))
  253. {
  254. $twigPath = 'security/' . $configLogin['folder'] . '/login.html.twig';
  255. }
  256. }
  257. return $this->render($twigPath, [
  258. 'last_username' => $lastUsername,
  259. 'error' => $error,
  260. 'loginForm' => $formLogin->createView(),
  261. 'registrationForm' => $hasFormRegister ? $formRegister->createView() : FALSE,
  262. 'hasFormRegister' => $hasFormRegister
  263. ]);
  264. }
  265. /**
  266. * Déconnexion
  267. *
  268. * @Route("/universal_logout", name="universal_logout")
  269. *
  270. * @return RedirectResponse
  271. */
  272. public function universalLogout(): RedirectResponse
  273. {
  274. if($this->isSamlSsoEnabled()) return $this->redirectToRoute('saml_logout');
  275. return $this->redirectToRoute('app_logout');
  276. }
  277. /**
  278. * Déconnexion
  279. *
  280. * @Route("/logout", name="app_logout")
  281. *
  282. * @return void
  283. */
  284. public function logout(): void
  285. {
  286. throw new LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.',);
  287. }
  288. private function isSamlSsoEnabled(): bool
  289. {
  290. if(!$this->moduleSettingService->isModuleActive(Sso::MODULE_NAME) || !$this->settingService->isExist(Setting::SSO_SETTINGS)) return false;
  291. $ssoSettings = $this->settingService->getSettingFromName(Setting::SSO_SETTINGS, true, true);
  292. return is_array($ssoSettings) && !empty($ssoSettings['ssoType']) && strtolower((string)$ssoSettings['ssoType']) === Sso::SSO_SAML;
  293. }
  294. }