OtAuthenticationService.php 20 KB

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