OtAuthenticationService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. <?php
  2. namespace Opentalent\OtConnect\Service;
  3. use DateTime;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Cookie\CookieJar;
  6. use GuzzleHttp\Cookie\SetCookie;
  7. use GuzzleHttp\Exception\GuzzleException;
  8. use GuzzleHttp\Exception\RequestException;
  9. use TYPO3\CMS\Core\Crypto\Random;
  10. use TYPO3\CMS\Core\Database\ConnectionPool;
  11. use TYPO3\CMS\Core\TimeTracker\TimeTracker;
  12. use TYPO3\CMS\Core\Utility\GeneralUtility;
  13. use \TYPO3\CMS\Core\Authentication\AbstractAuthenticationService;
  14. /**
  15. * Authentication service based on the Opentalent API.
  16. * See the README for more
  17. */
  18. class OtAuthenticationService extends AbstractAuthenticationService
  19. {
  20. CONST DOMAIN = 'https://api.opentalent.fr';
  21. CONST API_URI = self::DOMAIN . '/api/';
  22. CONST LOGIN_URI = self::API_URI . 'login_check';
  23. CONST GET_USER_DATA_URI = self::API_URI . 'user/datafortypo3';
  24. CONST ISAUTH_URI = self::API_URI . 'user/isauthenticated';
  25. CONST LOGOUT_URI = self::API_URI . 'logout';
  26. // Cookies'domain needs to be the same that the api's cookies, or guzzle will ignore them.
  27. CONST COOKIE_DOMAIN = 'opentalent.fr';
  28. CONST PRODUCT_MAPPING = [
  29. "school-standard" => 1, // Association writer basic
  30. "artist-standard" => 1, // Association writer basic
  31. "school-premium" => 3, // Association writer full
  32. "artist-premium" => 3, // Association writer full
  33. "manager" => 3, // Association writer full
  34. ];
  35. /**
  36. * The time in seconds during which the user's data in DB won't be re-updated after the last successful update
  37. * Set it to 0 to disable the delay
  38. */
  39. CONST USER_UPDATE_DELAY = 300;
  40. /**
  41. * 0 - Authentification failed, no more services will be called...
  42. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-service-chain
  43. *
  44. * @var int
  45. */
  46. const STATUS_AUTHENTICATION_FAILURE = 0;
  47. /**
  48. * 100 - OK, but call next services...
  49. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-service-chain
  50. *
  51. * @var int
  52. */
  53. const STATUS_AUTHENTICATION_CONTINUE = 100;
  54. /**
  55. * 200 - authenticated and no more checking needed
  56. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-service-chain
  57. *
  58. * @var int
  59. */
  60. const STATUS_AUTHENTICATION_SUCCESS = 200;
  61. /**
  62. * Guzzle Client
  63. *
  64. * @see http://docs.guzzlephp.org/en/stable/
  65. * @var Client
  66. */
  67. private $client;
  68. /**
  69. * Guzzle Cookie Jar
  70. *
  71. * @var CookieJar
  72. */
  73. private $jar;
  74. /**
  75. * @var \TYPO3\CMS\Core\Database\ConnectionPool
  76. */
  77. private $connectionPool;
  78. public function injectConnectionPool(ConnectionPool $connectionPool)
  79. {
  80. $this->connectionPool = $connectionPool;
  81. }
  82. /**
  83. * OtAuthenticationService constructor.
  84. */
  85. public function __construct() {
  86. $this->jar = new CookieJar;
  87. $this->client = new Client(['base_uri' => self::DOMAIN, 'cookies' => $this->jar]);
  88. $this->connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
  89. }
  90. /**
  91. * This function returns the user record back to the AbstractUserAuthentication.
  92. * It does not mean that user is authenticated, it only means that user is found.
  93. * /!\ The 'getUser' method is required by the Typo3 authentification system
  94. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
  95. *
  96. * @return array|bool User record or false (content of fe_users/be_users as appropriate for the current mode)
  97. */
  98. public function getUser()
  99. {
  100. // Does the user already have a session on the Opentalent API?
  101. $username = $this->getAuthenticatedUsername();
  102. if ($username != null && $this->authInfo['loginType'] == 'FE' && $this->login['status'] === 'logout') {
  103. // This is a logout request
  104. $this->logout();
  105. return false;
  106. }
  107. if ($username != null && $this->login['status'] === 'login' && $this->login['uname'] != $username) {
  108. // The user trying to log in is not the one authenticated on the Opentalent API
  109. // We let the TYPO3 auth service handle it
  110. return false;
  111. } else if ($username == null && $this->login['status'] != 'login') {
  112. // The user has no current session on Opentalent.fr and this is not a login request
  113. return false;
  114. } else if ($this->login['status'] === 'login' && $this->login['uname'] && $this->login['uident']) {
  115. // This is a login request
  116. $username = $this->login['uname'];
  117. $password = $this->login['uident'];
  118. // Send a login request for the user to the Opentalent Api, and return the data
  119. // of the matching user, or false if le login failed
  120. $logged = $this->logUser($username, $password);
  121. if (!$logged) {
  122. return false;
  123. }
  124. }
  125. // Request the latest data for the user and write it in the Typo3 DB
  126. // * The shouldUserBeUpdated() method checks if the user was already
  127. // generated in the last minutes, to avoid unecessary operations *
  128. if ($this->shouldUserBeUpdated($username)) {
  129. $wasUpdated = $this->createOrUpdateUser();
  130. if (!$wasUpdated) {
  131. // An error happened during the update of the user's data
  132. // since its data may have changed (credentials, rights, rôles...)
  133. // we can't allow him to connect.
  134. return false;
  135. }
  136. }
  137. // No need to check Pid for those users
  138. $this->authInfo['db_user']['checkPidList'] = '';
  139. $this->authInfo['db_user']['check_pid_clause'] = '';
  140. // Fetch the typo3 user from the database
  141. return $this->fetchUserRecord($username, '', $this->authInfo['db_user']);
  142. }
  143. /**
  144. * Returns the name of the user currently authenticated on the API side, or null if no user is logged in
  145. *
  146. * @return string|null
  147. * @throws GuzzleException
  148. */
  149. protected function getAuthenticatedUsername() {
  150. $this->fillCookieJar();
  151. try {
  152. $response = $this->client->request('GET', self::ISAUTH_URI, ['cookies' => $this->jar]);
  153. if ($response->getStatusCode() != 200) {
  154. return null;
  155. }
  156. return json_decode((string)$response->getBody());
  157. } catch (RequestException $e) {
  158. return null;
  159. }
  160. }
  161. /**
  162. * Update the guzzle cookie jar with the current session's ones
  163. */
  164. private function fillCookieJar() {
  165. foreach (['BEARER', 'SFSESSID'] as $cookieName) {
  166. if (array_key_exists($cookieName, $_COOKIE) &&
  167. $this->jar->getCookieByName($cookieName) == null) {
  168. $cookie = new SetCookie();
  169. $cookie->setName($cookieName);
  170. $cookie->setValue($_COOKIE[$cookieName]);
  171. $cookie->setDomain(self::COOKIE_DOMAIN);
  172. $this->jar->setCookie($cookie);
  173. }
  174. }
  175. }
  176. /**
  177. * Submit a login request to the API
  178. *
  179. * @param string $username
  180. * @param string $password
  181. * @return bool Returns true if the api accepted the login request
  182. * @throws GuzzleException
  183. */
  184. protected function logUser($username, $password) {
  185. try {
  186. $response = $this->client->request(
  187. 'POST',
  188. self::LOGIN_URI,
  189. ['form_params' => ['_username' => $username, '_password' => $password]]
  190. );
  191. if ($response->getStatusCode() != 200) {
  192. return false;
  193. }
  194. // The API accepted the login request
  195. // Set the cookies returned by the Api (SESSID and BEARER)
  196. $this->setCookiesFromApiResponse($response);
  197. return true;
  198. } catch (RequestException $e) {
  199. return false;
  200. }
  201. }
  202. /**
  203. * Get the cookies from the API response and set them
  204. *
  205. * @param $response
  206. */
  207. private function setCookiesFromApiResponse($response) {
  208. foreach ($response->getHeader('Set-Cookie') as $cookieStr) {
  209. $cookie = SetCookie::fromString($cookieStr);
  210. $name = $cookie->getName();
  211. $value = $cookie->getValue();
  212. $expires = $cookie->getExpires();
  213. $path = $cookie->getPath();
  214. $domain = self::COOKIE_DOMAIN;
  215. $secure = $cookie->getSecure();
  216. $httpOnly = $cookie->getHttpOnly();
  217. setcookie($name, $value, $expires, $path, $domain, $secure, $httpOnly);
  218. }
  219. }
  220. /**
  221. * Compare the last update date for the user to the GENERATION_DELAY delay
  222. * and return wether the user's data may be created/updated in the Typo3 DB
  223. *
  224. * @param string $username
  225. * @return bool
  226. */
  227. protected function shouldUserBeUpdated($username) {
  228. $cnn = $this->connectionPool->getConnectionForTable('fe_users');
  229. $q = $cnn->select(['tx_opentalent_generationDate'], 'fe_users', ['username' => $username]);
  230. $strGenDate = $q->fetch(3)[0];
  231. $genDate = DateTime::createFromFormat("Y-m-d H:i:s", $strGenDate);
  232. if ($genDate == null) {
  233. return true;
  234. }
  235. $now = new DateTime();
  236. $diff = $now->getTimestamp() - $genDate->getTimestamp();
  237. return ($diff > self::USER_UPDATE_DELAY);
  238. }
  239. /**
  240. * Create or update the Frontend-user record in the typo3 database (table 'fe_users')
  241. * and the Backend-user (table 'be_users', only if is admin)
  242. * with the data fetched from the Api
  243. *
  244. * @return bool
  245. */
  246. protected function createOrUpdateUser() {
  247. // Get user's data from the API
  248. $userApiData = $this->getUserData();
  249. if (empty($userApiData)) {
  250. // An error happened, and even if the user was logged, we can not continue
  251. // (user's data and rights could have changed)
  252. return false;
  253. }
  254. $connection = $this->connectionPool->getConnectionForTable('fe_users');
  255. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  256. $randomStr = (new Random)->generateRandomHexString(20);
  257. // Front-end user
  258. $fe_row = [
  259. 'username' => $userApiData['username'],
  260. 'password' => $randomStr,
  261. 'name' => $userApiData['name'],
  262. 'first_name' => $userApiData['first_name'],
  263. 'description' => '[Warning: auto-generated record, do not modify] FE User',
  264. 'usergroup' => 21,
  265. 'deleted' => 0,
  266. 'tx_opentalent_opentalentId' => $userApiData['id'],
  267. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  268. ];
  269. // TODO: log a warning if a user with the same opentalentId exists (the user might have changed of username)
  270. $q = $connection->select(
  271. ['uid', 'tx_opentalent_opentalentId'],
  272. 'fe_users',
  273. ['username' => $userApiData['username']]
  274. );
  275. $row = $q->fetch(3);
  276. $uid = $row[0];
  277. $tx_opentalent_opentalentId = $row[1];
  278. if (!$uid) {
  279. // No existing user: create
  280. $connection->insert('fe_users', $fe_row);
  281. } else {
  282. // User exists: update
  283. if (!$tx_opentalent_opentalentId > 0) {
  284. $this->writeLogMessage('WARNING: FE user ' . $userApiData['username'] . ' has been replaced by an auto-generated version.');
  285. }
  286. $connection->update('fe_users', $fe_row, ['uid' => $uid]);
  287. }
  288. // Back-end user: only if admin
  289. foreach ($userApiData['accesses'] as $access) {
  290. if ($access['admin_access'] == 'true') {
  291. // get the site root of the user
  292. $q = $connection->select(
  293. ['uid'],
  294. 'pages',
  295. ['tx_opentalent_structure_id' => $access['organizationId'], 'is_siteroot' => 1]
  296. );
  297. $rootUid = $q->fetch(3)[0];
  298. if (!$rootUid) {
  299. $this->writeLogMessage('ERROR: Unable to find the root page for user ' . $userApiData['username']);
  300. }
  301. // get the filemounts uids
  302. $q = $connection->createQueryBuilder();
  303. $q->select('uid')
  304. ->from('sys_filemounts')
  305. ->where("path LIKE '%user_upload/" . $access['organizationId'] . "/%'");
  306. $res = $q->execute();
  307. $rows = $res->fetchAll(3) ?: [];
  308. $files = [];
  309. foreach ($rows as $row) {
  310. $files[] = $row[0];
  311. }
  312. $be_row = [
  313. 'username' => $userApiData['username'],
  314. 'password' => $randomStr,
  315. 'description' => '[Warning: auto-generated record, do not modify] BE Admin for ' . $access['subDomain'] . ' (id: ' . $access['id'] . ')',
  316. 'deleted' => 0,
  317. 'lang' => 'fr',
  318. 'usergroup' => isset(self::PRODUCT_MAPPING[$access['product']]) ? self::PRODUCT_MAPPING[$access['product']] : 1,
  319. 'db_mountpoints' => $rootUid,
  320. 'file_mountPoints' => join(',', $files),
  321. 'options' => 2,
  322. 'file_permissions' => 'readFolder,writeFolder,addFolder,renameFolder,moveFolder,deleteFolder,readFile,writeFile,addFile,renameFile,replaceFile,moveFile,copyFile,deleteFile',
  323. 'tx_opentalent_opentalentId' => $userApiData['id'],
  324. 'tx_opentalent_organizationId' => $access['organizationId'],
  325. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  326. ];
  327. $q = $connection->select(
  328. ['uid'],
  329. 'be_users',
  330. ['username' => $userApiData['username']]
  331. );
  332. $row = $q->fetch(3);
  333. $uid = $row[0];
  334. $tx_opentalent_opentalentId = $row[1];
  335. if (!$uid) {
  336. // No existing user: create
  337. $connection->insert('be_users', $be_row);
  338. } else {
  339. // User exists: update
  340. if (!$tx_opentalent_opentalentId > 0) {
  341. $this->writeLogMessage('WARNING: BE user ' . $userApiData['username'] . ' has been replaced by an auto-generated version.');
  342. }
  343. $connection->update('be_users', $be_row, ['uid' => $uid]);
  344. }
  345. }
  346. }
  347. return true;
  348. }
  349. /**
  350. * Get the data for the current authenticated user from the API
  351. *
  352. * @return array
  353. */
  354. protected function getUserData() {
  355. $this->fillCookieJar();
  356. try {
  357. $response = $this->client->request('GET', self::GET_USER_DATA_URI, ['cookies' => $this->jar]);
  358. } catch (RequestException $e) {
  359. return [];
  360. } catch (GuzzleException $e) {
  361. return [];
  362. }
  363. return json_decode($response->getBody(), true);
  364. }
  365. /**
  366. * Authenticates user using Opentalent auth service.
  367. * /!\ The 'authUser' method is required by the Typo3 authentification system
  368. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
  369. *
  370. * @param array $user Data of user.
  371. * @return int Code that shows if user is really authenticated.
  372. * @throws GuzzleException
  373. */
  374. public function authUser(array $user)
  375. {
  376. if ($user['username'] == $this->getAuthenticatedUsername()) {
  377. // Tha API just validated this user's auth
  378. return self::STATUS_AUTHENTICATION_SUCCESS;
  379. } else if ($this->authInfo['loginType'] === 'FE') {
  380. return self::STATUS_AUTHENTICATION_FAILURE;
  381. } else if (isset($user['tx_opentalent_opentalentId']) and $user['tx_opentalent_opentalentId'] != null) {
  382. // This is a user from the Opentalent DB, and the API refused its auth
  383. // (For performance only, since the password stored in the Typo3 is a random string,
  384. // the auth will be refused by the other services anyway)
  385. return self::STATUS_AUTHENTICATION_FAILURE;
  386. }
  387. // This may be a user using another auth system
  388. return self::STATUS_AUTHENTICATION_CONTINUE;
  389. }
  390. /**
  391. * Send a logout request to the API, remove the sessions cookies then logout
  392. * /!\ Frontend only
  393. */
  394. public function logout() {
  395. try {
  396. $response = $this->client->request(
  397. 'GET',
  398. self::LOGOUT_URI
  399. );
  400. if ($response->getStatusCode() != 200) {
  401. return false;
  402. }
  403. // The API accepted the logout request
  404. // Unset the session cookies (SESSID and BEARER)
  405. if (isset($_COOKIE['BEARER'])) {
  406. unset($_COOKIE['BEARER']);
  407. $this->unset_cookie('BEARER');
  408. }
  409. if (isset($_COOKIE['SFSESSID'])) {
  410. unset($_COOKIE['SFSESSID']);
  411. $this->unset_cookie('SFSESSID');
  412. }
  413. $this->pObj->logoff();
  414. return true;
  415. } catch (RequestException $e) {
  416. return false;
  417. } catch (GuzzleException $e) {
  418. return false;
  419. }
  420. }
  421. /**
  422. * Unset a cookie by reducing its expiration date
  423. *
  424. * @param string $name
  425. * @return bool
  426. */
  427. protected function unset_cookie(string $name) {
  428. $res = setcookie($name, '', time() - 1, '/', self::COOKIE_DOMAIN);
  429. if (!$res) {
  430. $this->writeLogMessage('Error while unsetting ' . $name . ' cookie');
  431. }
  432. return $res;
  433. }
  434. /**
  435. * Writes log message. Destination log depends on the current system mode.
  436. * For FE the function writes to the admin panel log. For BE messages are
  437. * sent to the system log. If developer log is enabled, messages are also
  438. * sent there.
  439. *
  440. * This function accepts variable number of arguments and can format
  441. * parameters. The syntax is the same as for sprintf()
  442. *
  443. * @param string $message Message to output
  444. * @param array<int, mixed> $params
  445. * @see \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog()
  446. */
  447. public function writeLogMessage($message, ...$params)
  448. {
  449. if (!empty($params)) {
  450. $message = vsprintf($message, $params);
  451. }
  452. if (TYPO3_MODE === 'BE') {
  453. GeneralUtility::sysLog($message, 'ot_connect');
  454. } else {
  455. /** @var TimeTracker $timeTracker */
  456. $timeTracker = GeneralUtility::makeInstance(TimeTracker::class);
  457. $timeTracker->setTSlogMessage($message);
  458. }
  459. }
  460. }