OtAuthenticationService.php 20 KB

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