OtAuthenticationService.php 19 KB

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