OtAuthenticationService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. <?php
  2. namespace Opentalent\OtConnect\Service;
  3. use DateTime;
  4. use GuzzleHttp\Cookie\CookieJar;
  5. use GuzzleHttp\Cookie\SetCookie;
  6. use GuzzleHttp\Exception\GuzzleException;
  7. use GuzzleHttp\Exception\RequestException;
  8. use Opentalent\OtCore\Exception\ApiRequestException;
  9. use Opentalent\OtCore\Logging\OtLogger;
  10. use Opentalent\OtCore\Service\OpentalentApiService;
  11. use Opentalent\OtCore\Service\OpentalentEnvService;
  12. use Opentalent\OtCore\Utility\NavigationUtils;
  13. use Opentalent\OtCore\Utility\UrlUtils;
  14. use TYPO3\CMS\Core\Crypto\Random;
  15. use TYPO3\CMS\Core\Database\ConnectionPool;
  16. use TYPO3\CMS\Core\Database\Query\QueryHelper;
  17. use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
  18. use TYPO3\CMS\Core\TimeTracker\TimeTracker;
  19. use TYPO3\CMS\Core\Utility\GeneralUtility;
  20. use \TYPO3\CMS\Core\Authentication\AbstractAuthenticationService;
  21. /**
  22. * Authentication service based on the Opentalent API.
  23. * See the README for more
  24. */
  25. class OtAuthenticationService extends AbstractAuthenticationService
  26. {
  27. CONST LOGIN_URI = 'api/login_check';
  28. CONST GET_USER_DATA_URI = 'api/user/datafortypo3';
  29. CONST ISAUTH_URI = 'api/user/isauthenticated';
  30. CONST LOGOUT_URI = 'logout';
  31. CONST GROUP_FE_ALL_UID = 18076;
  32. CONST GROUP_ADMIN_STANDARD_UID = 1;
  33. CONST GROUP_ADMIN_PREMIUM_UID = 3;
  34. CONST GROUP_EDITOR_STANDARD_UID = 6;
  35. CONST GROUP_EDITOR_PREMIUM_UID = 7;
  36. // Cookies' domain needs to be the same that the api's cookies, or guzzle will ignore them.
  37. CONST COOKIE_DOMAIN = 'opentalent.fr';
  38. CONST PRODUCT_MAPPING = [
  39. "school-standard" => 1, // Association writer basic
  40. "artist-standard" => 1, // Association writer basic
  41. "school-premium" => 3, // Association writer full
  42. "artist-premium" => 3, // Association writer full
  43. "manager" => 3, // Association writer full
  44. ];
  45. /**
  46. * The time in seconds during which the user's data in DB won't be re-updated after the last successful update
  47. * Set it to 0 to disable the delay
  48. */
  49. CONST USER_UPDATE_DELAY = 300;
  50. /**
  51. * 0 - Authentification failed, no more services will be called...
  52. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-service-chain
  53. *
  54. * @var int
  55. */
  56. const STATUS_AUTHENTICATION_FAILURE = 0;
  57. /**
  58. * 100 - OK, but call next services...
  59. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-service-chain
  60. *
  61. * @var int
  62. */
  63. const STATUS_AUTHENTICATION_CONTINUE = 100;
  64. /**
  65. * 200 - authenticated and no more checking needed
  66. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-service-chain
  67. *
  68. * @var int
  69. */
  70. const STATUS_AUTHENTICATION_SUCCESS = 200;
  71. /**
  72. * @var object
  73. */
  74. private object $apiService;
  75. /**
  76. * Guzzle Cookie Jar
  77. *
  78. * @var CookieJar
  79. */
  80. private CookieJar $jar;
  81. /**
  82. * @var \TYPO3\CMS\Core\Database\ConnectionPool
  83. */
  84. private $connectionPool;
  85. public function injectConnectionPool(ConnectionPool $connectionPool)
  86. {
  87. $this->connectionPool = $connectionPool;
  88. }
  89. /**
  90. * OtAuthenticationService constructor.
  91. */
  92. public function __construct() {
  93. $this->jar = new CookieJar;
  94. $this->apiService = GeneralUtility::makeInstance(OpentalentApiService::class, null, null, $this->jar);
  95. $this->connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
  96. }
  97. /**
  98. * This function returns the user record back to the AbstractUserAuthentication.
  99. * It does not mean that user is authenticated, it only means that user is found.
  100. * /!\ The 'getUser' method is required by the Typo3 authentification system
  101. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
  102. *
  103. * @return array|bool User record or false (content of fe_users/be_users as appropriate for the current mode)
  104. * @throws GuzzleException
  105. */
  106. public function getUser()
  107. {
  108. // Does the user already have a session on the Opentalent API?
  109. $username = $this->getAuthenticatedUsername();
  110. $isBackend = $this->authInfo['loginType'] === 'BE';
  111. if ($username != null && !$isBackend && $this->login['status'] === 'logout') {
  112. // This is a logout request
  113. $this->logout();
  114. return false;
  115. }
  116. if ($username != null && $this->login['status'] === 'login' && $this->login['uname'] != $username) {
  117. // The user trying to log in is not the one authenticated on the Opentalent API
  118. // We let the TYPO3 auth service handle it
  119. return false;
  120. } else if ($username == null && $this->login['status'] != 'login') {
  121. // The user has no current session on Opentalent.fr and this is not a login request
  122. return false;
  123. } else if ($this->login['status'] === 'login' && $this->login['uname'] && $this->login['uident']) {
  124. // This is a login request
  125. $username = $this->login['uname'];
  126. $password = $this->login['uident'];
  127. // Send a login request for the user to the Opentalent Api, and return the data
  128. // of the matching user, or false if le login failed
  129. $logged = $this->logUser($username, $password);
  130. if (!$logged) {
  131. return false;
  132. }
  133. }
  134. /// At this point, username should be set
  135. if ($username === null) {
  136. return false;
  137. }
  138. // Request the latest data for the user and write it in the Typo3 DB
  139. // * The shouldUserBeUpdated() method checks if the user was already
  140. // generated in the last minutes, to avoid unnecessary operations *
  141. if ($this->shouldUserBeUpdated($username, $isBackend)) {
  142. try {
  143. $wasUpdated = $this->createOrUpdateUser($isBackend);
  144. } catch (\RuntimeException) {
  145. $wasUpdated = false;
  146. }
  147. if (!$wasUpdated) {
  148. // An error happened during the update of the user's data
  149. // since its data may have changed (credentials, rights, rôles...)
  150. // we can't allow him to connect.
  151. return false;
  152. }
  153. }
  154. // No need to check Pid for those users
  155. $this->authInfo['db_user']['checkPidList'] = '';
  156. $this->authInfo['db_user']['check_pid_clause'] = '';
  157. // Fetch the typo3 user from the database
  158. return $this->fetchUserRecord($username, '', $this->authInfo['db_user']);
  159. }
  160. /**
  161. * Returns the name of the user currently authenticated on the API side, or null if no user is logged in
  162. *
  163. * @return string|null
  164. * @throws GuzzleException
  165. */
  166. protected function getAuthenticatedUsername(): ?string
  167. {
  168. $this->fillCookieJar();
  169. try {
  170. if (!$this->jar->getCookieByName('BEARER')) {
  171. // Missing cookie : No need to ask API
  172. return null;
  173. }
  174. $response = $this->apiService->get(self::ISAUTH_URI, [], ['cookies' => $this->jar]);
  175. if ($response->getStatusCode() != 200) {
  176. return null;
  177. }
  178. return json_decode((string)$response->getBody());
  179. } catch (ApiRequestException $e) {
  180. return null;
  181. }
  182. }
  183. /**
  184. * Update the guzzle cookie jar with the current session's ones
  185. */
  186. private function fillCookieJar() {
  187. foreach (['BEARER', 'SFSESSID', 'AccessId'] as $cookieName) {
  188. if (array_key_exists($cookieName, $_COOKIE)) {
  189. $cookie = new SetCookie();
  190. $cookie->setName($cookieName);
  191. $cookie->setValue($_COOKIE[$cookieName]);
  192. $cookie->setDomain(self::COOKIE_DOMAIN);
  193. $this->jar->setCookie($cookie);
  194. }
  195. }
  196. }
  197. /**
  198. * Submit a login request to the API
  199. *
  200. * @param string $username
  201. * @param string $password
  202. * @return bool Returns true if the api accepted the login request
  203. * @throws GuzzleException
  204. */
  205. protected function logUser(string $username, string $password): bool
  206. {
  207. try {
  208. $response = $this->apiService->request(
  209. 'POST',
  210. self::LOGIN_URI,
  211. [],
  212. ['form_params' => ['_username' => $username, '_password' => $password]]
  213. );
  214. if ($response->getStatusCode() != 200) {
  215. return false;
  216. }
  217. $data = json_decode((string)$response->getBody(), true);
  218. # Redirect the user if the password needs to be changed
  219. if (isset($data['type']) && $data['type'] === 'change_password') {
  220. $redirectTo = UrlUtils::join(
  221. OpentalentEnvService::get('ADMIN_BASE_URL'), "/#/account/", $data['organization'], "/secure/password/", $data['token']
  222. );
  223. NavigationUtils::redirect($redirectTo);
  224. }
  225. // The API accepted the login request
  226. // Set the cookies returned by the Api (SESSID and BEARER)
  227. $this->setCookiesFromApiResponse($response);
  228. return true;
  229. } catch (ApiRequestException $e) {
  230. return false;
  231. }
  232. }
  233. /**
  234. * Get the cookies from the API response and set them
  235. *
  236. * @param $response
  237. */
  238. private function setCookiesFromApiResponse($response) {
  239. foreach ($response->getHeader('Set-Cookie') as $cookieStr) {
  240. $cookie = SetCookie::fromString($cookieStr);
  241. $name = $cookie->getName();
  242. $value = $cookie->getValue();
  243. $expires = $cookie->getExpires() ?? 0;
  244. $path = $cookie->getPath();
  245. $secure = $cookie->getSecure();
  246. $httpOnly = $cookie->getHttpOnly();
  247. $_COOKIE[$name] = $value;
  248. setcookie($name, $value, $expires, $path, self::COOKIE_DOMAIN, $secure, $httpOnly);
  249. setcookie($name, $value, $expires, $path, '.' . self::COOKIE_DOMAIN, $secure, $httpOnly);
  250. if (!preg_match('/(.*\.)?opentalent\.fr/', $_SERVER['HTTP_HOST'])) {
  251. setcookie($name, $value, $expires, $path, $_SERVER['HTTP_HOST'], $secure, $httpOnly);
  252. }
  253. }
  254. }
  255. /**
  256. * Compare the last update date for the user to the GENERATION_DELAY delay
  257. * and return wether the user's data may be created/updated in the Typo3 DB
  258. *
  259. * @param string $username
  260. * @return bool
  261. */
  262. protected function shouldUserBeUpdated(string $username, bool $isBackend = false): bool
  263. {
  264. $table = $isBackend ? 'be_users' : 'fe_users';
  265. $cnn = $this->connectionPool->getConnectionForTable($table);
  266. $q = $cnn->select(['tx_opentalent_generationDate'], $table, ['username' => $username]);
  267. $strGenDate = $q->fetch(3)[0] ?? '1970-01-01 00:00:00';
  268. $genDate = DateTime::createFromFormat("Y-m-d H:i:s", $strGenDate);
  269. if ($genDate == null) {
  270. return true;
  271. }
  272. $now = new DateTime();
  273. $diff = $now->getTimestamp() - $genDate->getTimestamp();
  274. return true || ($diff > self::USER_UPDATE_DELAY);
  275. }
  276. /**
  277. * Create or update the Frontend-user record in the typo3 database (table 'fe_users')
  278. * with the data fetched from the Api
  279. *
  280. * @return bool
  281. */
  282. protected function createOrUpdateUser(bool $isBackend = false): bool
  283. {
  284. $table = $isBackend ? 'be_users' : 'fe_users';
  285. $group_table = $isBackend ? 'be_groups' : 'fe_groups';
  286. $prefix = $isBackend ? 'BE' : 'FE';
  287. // Get user's data from the API
  288. $userApiData = $this->getUserData();
  289. if (empty($userApiData)) {
  290. // An error happened, and even if the user was logged, we can not continue
  291. // (user's data and rights could have changed)
  292. return false;
  293. }
  294. $connection = $this->connectionPool->getConnectionForTable($table);
  295. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  296. $randomStr = (new Random)->generateRandomHexString(30);
  297. // Front-end user
  298. $user_row = [
  299. 'username' => $userApiData['username'],
  300. 'password' => $randomStr,
  301. 'description' => "[Warning: auto-generated record, do not modify] $prefix User",
  302. 'deleted' => 0,
  303. 'tx_opentalent_opentalentId' => $userApiData['id'],
  304. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  305. ];
  306. if ($isBackend) {
  307. $user_row['lang'] = 'fr';
  308. $user_row['options'] = "3";
  309. $user_row['TSconfig'] = "options.uploadFieldsInTopOfEB = 1";
  310. } else {
  311. $user_row['name'] = $userApiData['name'];
  312. $user_row['first_name'] = $userApiData['first_name'];
  313. }
  314. $groupsUid = [];
  315. if (!$isBackend) {
  316. $groupsUid[] = self::GROUP_FE_ALL_UID;
  317. }
  318. // Loop over the accesses of the user to list the matching organization groups
  319. if ($userApiData['accesses']) {
  320. foreach ($userApiData['accesses'] as $accessData) {
  321. if ($isBackend && !$accessData['isEditor'] && !$accessData['admin_access']) {
  322. continue;
  323. }
  324. if ($isBackend) {
  325. if ($accessData['admin_access']) {
  326. $mainGroupUid = $accessData['product'] === 'artist_premium' ?
  327. self::GROUP_ADMIN_PREMIUM_UID :
  328. self::GROUP_ADMIN_STANDARD_UID;
  329. } else {
  330. $mainGroupUid = $accessData['product'] === 'artist_premium' ?
  331. self::GROUP_EDITOR_PREMIUM_UID :
  332. self::GROUP_EDITOR_STANDARD_UID;
  333. }
  334. if (!in_array($mainGroupUid, $groupsUid)) {
  335. $groupsUid[] = $mainGroupUid;
  336. }
  337. }
  338. $organizationId = $accessData['organizationId'];
  339. // get the group for this organization
  340. $groupUid = $connection->fetchOne(
  341. "select g.uid
  342. from typo3.$group_table g
  343. inner join (select uid, ot_website_uid from typo3.pages where is_siteroot) p
  344. on g." . ($isBackend ? 'db_mountpoints' : 'pid') . " = p.uid
  345. inner join typo3.ot_websites w on p.ot_website_uid = w.uid
  346. where w.organization_id=:organizationId;",
  347. ['organizationId' => $organizationId]
  348. );
  349. // <-- TODO: supprimer après la fin des tests sur cmf-test
  350. if ($organizationId === 616134) {
  351. // Groupe "hard-codé" pour le compte admincmf-test
  352. $groupUid = 4925;
  353. }
  354. // --->
  355. if ($groupUid) {
  356. $groupsUid[] = $groupUid;
  357. } else {
  358. OtLogger::warning("Warning: no " . strtolower($prefix) . "_group found for organization " . $organizationId);
  359. }
  360. }
  361. }
  362. if ($isBackend && empty($groupsUid)) {
  363. throw new \RuntimeException("No BE_group found for user " . $userApiData['username']);
  364. }
  365. $user_row['usergroup'] = join(',', $groupsUid);
  366. // TODO: log a warning if a user with the same opentalentId exists (the user might have changed of username)
  367. $q = $connection->select(
  368. ['uid', 'tx_opentalent_opentalentId'],
  369. $table,
  370. ['username' => $userApiData['username']]
  371. );
  372. $row = $q->fetch(3);
  373. $uid = $row[0] ?? null;
  374. $tx_opentalent_opentalentId = $row[1] ?? null;
  375. if (!$uid) {
  376. // No existing user: create
  377. $connection->insert($table, $user_row);
  378. } else {
  379. // User exists: update
  380. if (!$tx_opentalent_opentalentId > 0) {
  381. OtLogger::warning(
  382. "WARNING: $prefix user " . $userApiData['username'] .
  383. ' has been replaced by an auto-generated version.'
  384. );
  385. }
  386. $connection->update($table, $user_row, ['uid' => $uid]);
  387. }
  388. return true;
  389. }
  390. /**
  391. * Get the data for the current authenticated user from the API
  392. *
  393. * @return array
  394. */
  395. protected function getUserData(): ?array
  396. {
  397. $this->fillCookieJar();
  398. try {
  399. $response = $this->apiService->request('GET', self::GET_USER_DATA_URI, [], ['cookies' => $this->jar]);
  400. } catch (ApiRequestException $e) {
  401. return [];
  402. }
  403. return json_decode($response->getBody(), true);
  404. }
  405. /**
  406. * Authenticates user using Opentalent auth service.
  407. * /!\ The 'authUser' method is required by the Typo3 authentification system
  408. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
  409. *
  410. * @param array $user Data of user.
  411. * @return int Code that shows if user is really authenticated.
  412. * @throws GuzzleException
  413. */
  414. public function authUser(array $user): int
  415. {
  416. if ($user['username'] == $this->getAuthenticatedUsername()) {
  417. // Tha API just validated this user's auth
  418. return self::STATUS_AUTHENTICATION_SUCCESS;
  419. } else if ($this->authInfo['loginType'] === 'FE') {
  420. return self::STATUS_AUTHENTICATION_FAILURE;
  421. } else if (isset($user['tx_opentalent_opentalentId']) and $user['tx_opentalent_opentalentId'] != null) {
  422. // This is a user from the Opentalent DB, and the API refused its auth
  423. // (For performance only, since the password stored in the Typo3 is a random string,
  424. // the auth will be refused by the other services anyway)
  425. return self::STATUS_AUTHENTICATION_FAILURE;
  426. }
  427. // This may be a user using another auth system
  428. return self::STATUS_AUTHENTICATION_CONTINUE;
  429. }
  430. /**
  431. * Send a logout request to the API, remove the sessions cookies then logout
  432. * /!\ Frontend only
  433. */
  434. public function logout(): bool
  435. {
  436. try {
  437. $response = $this->apiService->request(
  438. 'GET',
  439. self::LOGOUT_URI
  440. );
  441. if ($response->getStatusCode() != 200) {
  442. return false;
  443. }
  444. // The API accepted the logout request
  445. // Unset the session cookies (SESSID and BEARER)
  446. if (isset($_COOKIE['BEARER'])) {
  447. unset($_COOKIE['BEARER']);
  448. $this->unset_cookie('BEARER');
  449. }
  450. if (isset($_COOKIE['SFSESSID'])) {
  451. unset($_COOKIE['SFSESSID']);
  452. $this->unset_cookie('SFSESSID');
  453. }
  454. $this->pObj->logoff();
  455. return true;
  456. } catch (RequestException $e) {
  457. return false;
  458. } catch (GuzzleException $e) {
  459. return false;
  460. }
  461. }
  462. /**
  463. * Unset a cookie by reducing its expiration date
  464. *
  465. * @param string $name
  466. */
  467. protected function unset_cookie(string $name)
  468. {
  469. setcookie($name, '', 1, '/', $_SERVER['HTTP_HOST']); // for custom domains (not in .opentalent.fr)
  470. setcookie($name, '', 1, '/', self::COOKIE_DOMAIN); // for opentalent.fr subdomains
  471. }
  472. /**
  473. * Get a user from DB by username
  474. *
  475. * @param string $username User name
  476. * @param string $extraWhere Additional WHERE clause: " AND ...
  477. * @param array|string $dbUserSetup User db table definition, or empty string for $this->db_user
  478. * @return mixed User array or FALSE
  479. */
  480. public function fetchUserRecordTemp($username, $extraWhere = '', $dbUserSetup = '')
  481. {
  482. $dbUser = is_array($dbUserSetup) ? $dbUserSetup : $this->db_user;
  483. $user = false;
  484. if ($username || $extraWhere) {
  485. $query = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($dbUser['table']);
  486. $query->getRestrictions()->removeAll()
  487. ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
  488. $constraints = array_filter([
  489. QueryHelper::stripLogicalOperatorPrefix($dbUser['check_pid_clause']),
  490. QueryHelper::stripLogicalOperatorPrefix($dbUser['enable_clause']),
  491. QueryHelper::stripLogicalOperatorPrefix($extraWhere),
  492. ]);
  493. if (!empty($username)) {
  494. array_unshift(
  495. $constraints,
  496. $query->expr()->eq(
  497. $dbUser['username_column'],
  498. $query->createNamedParameter($username, \PDO::PARAM_STR)
  499. )
  500. );
  501. }
  502. $user = $query->select('*')
  503. ->from($dbUser['table'])
  504. ->where(...$constraints)
  505. ->execute()
  506. ->fetch();
  507. }
  508. return $user;
  509. }
  510. }