OtAuthenticationService.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. $wasUpdated = $this->createOrUpdateUser($isBackend);
  143. if (!$wasUpdated) {
  144. // An error happened during the update of the user's data
  145. // since its data may have changed (credentials, rights, rôles...)
  146. // we can't allow him to connect.
  147. return false;
  148. }
  149. }
  150. // No need to check Pid for those users
  151. $this->authInfo['db_user']['checkPidList'] = '';
  152. $this->authInfo['db_user']['check_pid_clause'] = '';
  153. // Fetch the typo3 user from the database
  154. return $this->fetchUserRecord($username, '', $this->authInfo['db_user']);
  155. }
  156. /**
  157. * Returns the name of the user currently authenticated on the API side, or null if no user is logged in
  158. *
  159. * @return string|null
  160. * @throws GuzzleException
  161. */
  162. protected function getAuthenticatedUsername(): ?string
  163. {
  164. $this->fillCookieJar();
  165. try {
  166. if (!$this->jar->getCookieByName('BEARER')) {
  167. // Missing cookie : No need to ask API
  168. return null;
  169. }
  170. $response = $this->apiService->get(self::ISAUTH_URI, [], ['cookies' => $this->jar]);
  171. if ($response->getStatusCode() != 200) {
  172. return null;
  173. }
  174. return json_decode((string)$response->getBody());
  175. } catch (ApiRequestException $e) {
  176. return null;
  177. }
  178. }
  179. /**
  180. * Update the guzzle cookie jar with the current session's ones
  181. */
  182. private function fillCookieJar() {
  183. foreach (['BEARER', 'SFSESSID', 'AccessId'] as $cookieName) {
  184. if (array_key_exists($cookieName, $_COOKIE)) {
  185. $cookie = new SetCookie();
  186. $cookie->setName($cookieName);
  187. $cookie->setValue($_COOKIE[$cookieName]);
  188. $cookie->setDomain(self::COOKIE_DOMAIN);
  189. $this->jar->setCookie($cookie);
  190. }
  191. }
  192. }
  193. /**
  194. * Submit a login request to the API
  195. *
  196. * @param string $username
  197. * @param string $password
  198. * @return bool Returns true if the api accepted the login request
  199. * @throws GuzzleException
  200. */
  201. protected function logUser(string $username, string $password): bool
  202. {
  203. try {
  204. $response = $this->apiService->request(
  205. 'POST',
  206. self::LOGIN_URI,
  207. [],
  208. ['form_params' => ['_username' => $username, '_password' => $password]]
  209. );
  210. if ($response->getStatusCode() != 200) {
  211. return false;
  212. }
  213. $data = json_decode((string)$response->getBody(), true);
  214. # Redirect the user if the password needs to be changed
  215. if (isset($data['type']) && $data['type'] === 'change_password') {
  216. $redirectTo = UrlUtils::join(
  217. OpentalentEnvService::get('ADMIN_BASE_URL'), "/#/account/", $data['organization'], "/secure/password/", $data['token']
  218. );
  219. NavigationUtils::redirect($redirectTo);
  220. }
  221. // The API accepted the login request
  222. // Set the cookies returned by the Api (SESSID and BEARER)
  223. $this->setCookiesFromApiResponse($response);
  224. return true;
  225. } catch (ApiRequestException $e) {
  226. return false;
  227. }
  228. }
  229. /**
  230. * Get the cookies from the API response and set them
  231. *
  232. * @param $response
  233. */
  234. private function setCookiesFromApiResponse($response) {
  235. foreach ($response->getHeader('Set-Cookie') as $cookieStr) {
  236. $cookie = SetCookie::fromString($cookieStr);
  237. $name = $cookie->getName();
  238. $value = $cookie->getValue();
  239. $expires = $cookie->getExpires() ?? 0;
  240. $path = $cookie->getPath();
  241. $secure = $cookie->getSecure();
  242. $httpOnly = $cookie->getHttpOnly();
  243. $_COOKIE[$name] = $value;
  244. setcookie($name, $value, $expires, $path, self::COOKIE_DOMAIN, $secure, $httpOnly);
  245. setcookie($name, $value, $expires, $path, '.' . self::COOKIE_DOMAIN, $secure, $httpOnly);
  246. if (!preg_match('/(.*\.)?opentalent\.fr/', $_SERVER['HTTP_HOST'])) {
  247. setcookie($name, $value, $expires, $path, $_SERVER['HTTP_HOST'], $secure, $httpOnly);
  248. }
  249. }
  250. }
  251. /**
  252. * Compare the last update date for the user to the GENERATION_DELAY delay
  253. * and return wether the user's data may be created/updated in the Typo3 DB
  254. *
  255. * @param string $username
  256. * @return bool
  257. */
  258. protected function shouldUserBeUpdated(string $username, bool $isBackend = false): bool
  259. {
  260. $table = $isBackend ? 'be_users' : 'fe_users';
  261. $cnn = $this->connectionPool->getConnectionForTable($table);
  262. $q = $cnn->select(['tx_opentalent_generationDate'], $table, ['username' => $username]);
  263. $strGenDate = $q->fetch(3)[0] ?? '1970-01-01 00:00:00';
  264. $genDate = DateTime::createFromFormat("Y-m-d H:i:s", $strGenDate);
  265. if ($genDate == null) {
  266. return true;
  267. }
  268. $now = new DateTime();
  269. $diff = $now->getTimestamp() - $genDate->getTimestamp();
  270. return ($diff > self::USER_UPDATE_DELAY);
  271. }
  272. /**
  273. * Create or update the Frontend-user record in the typo3 database (table 'fe_users')
  274. * with the data fetched from the Api
  275. *
  276. * @return bool
  277. */
  278. protected function createOrUpdateUser(bool $isBackend = false): bool
  279. {
  280. $table = $isBackend ? 'be_users' : 'fe_users';
  281. $group_table = $isBackend ? 'be_groups' : 'fe_groups';
  282. $prefix = $isBackend ? 'BE' : 'FE';
  283. // Get user's data from the API
  284. $userApiData = $this->getUserData();
  285. if (empty($userApiData)) {
  286. // An error happened, and even if the user was logged, we can not continue
  287. // (user's data and rights could have changed)
  288. return false;
  289. }
  290. $connection = $this->connectionPool->getConnectionForTable($table);
  291. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  292. $randomStr = (new Random)->generateRandomHexString(30);
  293. // Front-end user
  294. $user_row = [
  295. 'username' => $userApiData['username'],
  296. 'password' => $randomStr,
  297. 'description' => "[Warning: auto-generated record, do not modify] $prefix User",
  298. 'deleted' => 0,
  299. 'tx_opentalent_opentalentId' => $userApiData['id'],
  300. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  301. ];
  302. if ($isBackend) {
  303. $user_row['lang'] = 'fr';
  304. $user_row['options'] = "3";
  305. $user_row['TSconfig'] = "options.uploadFieldsInTopOfEB = 1";
  306. } else {
  307. $user_row['name'] = $userApiData['name'];
  308. $user_row['first_name'] = $userApiData['first_name'];
  309. }
  310. $groupsUid = [];
  311. if (!$isBackend) {
  312. $groupsUid[] = self::GROUP_FE_ALL_UID;
  313. }
  314. // Loop over the accesses of the user to list the matching organization groups
  315. if ($userApiData['accesses']) {
  316. foreach ($userApiData['accesses'] as $accessData) {
  317. if ($isBackend && !$accessData['isEditor'] && !$accessData['admin_access']) {
  318. continue;
  319. }
  320. if ($isBackend) {
  321. if ($accessData['admin_access']) {
  322. $mainGroupUid = $accessData['product'] === 'artist_premium' ?
  323. self::GROUP_ADMIN_PREMIUM_UID :
  324. self::GROUP_ADMIN_STANDARD_UID;
  325. } else {
  326. $mainGroupUid = $accessData['product'] === 'artist_premium' ?
  327. self::GROUP_EDITOR_PREMIUM_UID :
  328. self::GROUP_EDITOR_STANDARD_UID;
  329. }
  330. if (!in_array($mainGroupUid, $groupsUid)) {
  331. $groupsUid[] = $mainGroupUid;
  332. }
  333. }
  334. $organizationId = $accessData['organizationId'];
  335. // get the group for this organization
  336. $groupUid = $connection->fetchOne(
  337. "select g.uid
  338. from typo3.$group_table g
  339. inner join (select uid, ot_website_uid from typo3.pages where is_siteroot) p
  340. on g." . ($isBackend ? 'db_mountpoints' : 'pid') . " = p.uid
  341. inner join typo3.ot_websites w on p.ot_website_uid = w.uid
  342. where w.organization_id=:organizationId;",
  343. ['organizationId' => $organizationId]
  344. );
  345. if ($groupUid) {
  346. $groupsUid[] = $groupUid;
  347. } else {
  348. OtLogger::warning("Warning: no " . strtolower($prefix) . "_group found for organization " . $organizationId);
  349. }
  350. }
  351. }
  352. if ($isBackend && empty($groupsUid)) {
  353. throw new \Exception("No BE_group found for user " . $userApiData['username']);
  354. }
  355. $user_row['usergroup'] = join(',', $groupsUid);
  356. // TODO: log a warning if a user with the same opentalentId exists (the user might have changed of username)
  357. $q = $connection->select(
  358. ['uid', 'tx_opentalent_opentalentId'],
  359. $table,
  360. ['username' => $userApiData['username']]
  361. );
  362. $row = $q->fetch(3);
  363. $uid = $row[0] ?? null;
  364. $tx_opentalent_opentalentId = $row[1] ?? null;
  365. if (!$uid) {
  366. // No existing user: create
  367. $connection->insert($table, $user_row);
  368. } else {
  369. // User exists: update
  370. if (!$tx_opentalent_opentalentId > 0) {
  371. OtLogger::warning(
  372. "WARNING: $prefix user " . $userApiData['username'] .
  373. ' has been replaced by an auto-generated version.'
  374. );
  375. }
  376. $connection->update($table, $user_row, ['uid' => $uid]);
  377. }
  378. return true;
  379. }
  380. /**
  381. * Get the data for the current authenticated user from the API
  382. *
  383. * @return array
  384. */
  385. protected function getUserData(): ?array
  386. {
  387. $this->fillCookieJar();
  388. try {
  389. $response = $this->apiService->request('GET', self::GET_USER_DATA_URI, [], ['cookies' => $this->jar]);
  390. } catch (ApiRequestException $e) {
  391. return [];
  392. }
  393. return json_decode($response->getBody(), true);
  394. }
  395. /**
  396. * Authenticates user using Opentalent auth service.
  397. * /!\ The 'authUser' method is required by the Typo3 authentification system
  398. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
  399. *
  400. * @param array $user Data of user.
  401. * @return int Code that shows if user is really authenticated.
  402. * @throws GuzzleException
  403. */
  404. public function authUser(array $user): int
  405. {
  406. if ($user['username'] == $this->getAuthenticatedUsername()) {
  407. // Tha API just validated this user's auth
  408. return self::STATUS_AUTHENTICATION_SUCCESS;
  409. } else if ($this->authInfo['loginType'] === 'FE') {
  410. return self::STATUS_AUTHENTICATION_FAILURE;
  411. } else if (isset($user['tx_opentalent_opentalentId']) and $user['tx_opentalent_opentalentId'] != null) {
  412. // This is a user from the Opentalent DB, and the API refused its auth
  413. // (For performance only, since the password stored in the Typo3 is a random string,
  414. // the auth will be refused by the other services anyway)
  415. return self::STATUS_AUTHENTICATION_FAILURE;
  416. }
  417. // This may be a user using another auth system
  418. return self::STATUS_AUTHENTICATION_CONTINUE;
  419. }
  420. /**
  421. * Send a logout request to the API, remove the sessions cookies then logout
  422. * /!\ Frontend only
  423. */
  424. public function logout(): bool
  425. {
  426. try {
  427. $response = $this->apiService->request(
  428. 'GET',
  429. self::LOGOUT_URI
  430. );
  431. if ($response->getStatusCode() != 200) {
  432. return false;
  433. }
  434. // The API accepted the logout request
  435. // Unset the session cookies (SESSID and BEARER)
  436. if (isset($_COOKIE['BEARER'])) {
  437. unset($_COOKIE['BEARER']);
  438. $this->unset_cookie('BEARER');
  439. }
  440. if (isset($_COOKIE['SFSESSID'])) {
  441. unset($_COOKIE['SFSESSID']);
  442. $this->unset_cookie('SFSESSID');
  443. }
  444. $this->pObj->logoff();
  445. return true;
  446. } catch (RequestException $e) {
  447. return false;
  448. } catch (GuzzleException $e) {
  449. return false;
  450. }
  451. }
  452. /**
  453. * Unset a cookie by reducing its expiration date
  454. *
  455. * @param string $name
  456. */
  457. protected function unset_cookie(string $name)
  458. {
  459. setcookie($name, '', 1, '/', $_SERVER['HTTP_HOST']); // for custom domains (not in .opentalent.fr)
  460. setcookie($name, '', 1, '/', self::COOKIE_DOMAIN); // for opentalent.fr subdomains
  461. }
  462. /**
  463. * Get a user from DB by username
  464. *
  465. * @param string $username User name
  466. * @param string $extraWhere Additional WHERE clause: " AND ...
  467. * @param array|string $dbUserSetup User db table definition, or empty string for $this->db_user
  468. * @return mixed User array or FALSE
  469. */
  470. public function fetchUserRecordTemp($username, $extraWhere = '', $dbUserSetup = '')
  471. {
  472. $dbUser = is_array($dbUserSetup) ? $dbUserSetup : $this->db_user;
  473. $user = false;
  474. if ($username || $extraWhere) {
  475. $query = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($dbUser['table']);
  476. $query->getRestrictions()->removeAll()
  477. ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
  478. $constraints = array_filter([
  479. QueryHelper::stripLogicalOperatorPrefix($dbUser['check_pid_clause']),
  480. QueryHelper::stripLogicalOperatorPrefix($dbUser['enable_clause']),
  481. QueryHelper::stripLogicalOperatorPrefix($extraWhere),
  482. ]);
  483. if (!empty($username)) {
  484. array_unshift(
  485. $constraints,
  486. $query->expr()->eq(
  487. $dbUser['username_column'],
  488. $query->createNamedParameter($username, \PDO::PARAM_STR)
  489. )
  490. );
  491. }
  492. $user = $query->select('*')
  493. ->from($dbUser['table'])
  494. ->where(...$constraints)
  495. ->execute()
  496. ->fetch();
  497. }
  498. return $user;
  499. }
  500. }