OtAuthenticationService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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 $client;
  68. /**
  69. * Guzzle Cookie Jar
  70. *
  71. * @var CookieJar
  72. */
  73. private CookieJar $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. * @throws GuzzleException
  98. */
  99. public function getUser()
  100. {
  101. // Does the user already have a session on the Opentalent API?
  102. $username = $this->getAuthenticatedUsername();
  103. if ($username != null && $this->authInfo['loginType'] == 'FE' && $this->login['status'] === 'logout') {
  104. // This is a logout request
  105. $this->logout();
  106. return false;
  107. }
  108. if ($username != null && $this->login['status'] === 'login' && $this->login['uname'] != $username) {
  109. // The user trying to log in is not the one authenticated on the Opentalent API
  110. // We let the TYPO3 auth service handle it
  111. return false;
  112. } else if ($username == null && $this->login['status'] != 'login') {
  113. // The user has no current session on Opentalent.fr and this is not a login request
  114. return false;
  115. } else if ($this->login['status'] === 'login' && $this->login['uname'] && $this->login['uident']) {
  116. // This is a login request
  117. $username = $this->login['uname'];
  118. $password = $this->login['uident'];
  119. // Send a login request for the user to the Opentalent Api, and return the data
  120. // of the matching user, or false if le login failed
  121. $logged = $this->logUser($username, $password);
  122. if (!$logged) {
  123. return false;
  124. }
  125. }
  126. // Request the latest data for the user and write it in the Typo3 DB
  127. // * The shouldUserBeUpdated() method checks if the user was already
  128. // generated in the last minutes, to avoid unnecessary operations *
  129. if ($this->shouldUserBeUpdated($username)) {
  130. $wasUpdated = $this->createOrUpdateUser();
  131. if (!$wasUpdated) {
  132. // An error happened during the update of the user's data
  133. // since its data may have changed (credentials, rights, rôles...)
  134. // we can't allow him to connect.
  135. return false;
  136. }
  137. }
  138. // No need to check Pid for those users
  139. $this->authInfo['db_user']['checkPidList'] = '';
  140. $this->authInfo['db_user']['check_pid_clause'] = '';
  141. // Fetch the typo3 user from the database
  142. return $this->fetchUserRecord($username, '', $this->authInfo['db_user']);
  143. }
  144. /**
  145. * Returns the name of the user currently authenticated on the API side, or null if no user is logged in
  146. *
  147. * @return string|null
  148. * @throws GuzzleException
  149. */
  150. protected function getAuthenticatedUsername(): ?string
  151. {
  152. $this->fillCookieJar();
  153. try {
  154. $response = $this->client->request('GET', self::ISAUTH_URI, ['cookies' => $this->jar]);
  155. if ($response->getStatusCode() != 200) {
  156. return null;
  157. }
  158. return json_decode((string)$response->getBody());
  159. } catch (RequestException $e) {
  160. return null;
  161. }
  162. }
  163. /**
  164. * Update the guzzle cookie jar with the current session's ones
  165. */
  166. private function fillCookieJar() {
  167. foreach (['BEARER', 'SFSESSID'] as $cookieName) {
  168. if (array_key_exists($cookieName, $_COOKIE) &&
  169. $this->jar->getCookieByName($cookieName) == null) {
  170. $cookie = new SetCookie();
  171. $cookie->setName($cookieName);
  172. $cookie->setValue($_COOKIE[$cookieName]);
  173. $cookie->setDomain(self::COOKIE_DOMAIN);
  174. $this->jar->setCookie($cookie);
  175. }
  176. }
  177. }
  178. /**
  179. * Submit a login request to the API
  180. *
  181. * @param string $username
  182. * @param string $password
  183. * @return bool Returns true if the api accepted the login request
  184. * @throws GuzzleException
  185. */
  186. protected function logUser(string $username, string $password): bool
  187. {
  188. try {
  189. $response = $this->client->request(
  190. 'POST',
  191. self::LOGIN_URI,
  192. ['form_params' => ['_username' => $username, '_password' => $password]]
  193. );
  194. if ($response->getStatusCode() != 200) {
  195. return false;
  196. }
  197. // The API accepted the login request
  198. // Set the cookies returned by the Api (SESSID and BEARER)
  199. $this->setCookiesFromApiResponse($response);
  200. return true;
  201. } catch (RequestException $e) {
  202. return false;
  203. }
  204. }
  205. /**
  206. * Get the cookies from the API response and set them
  207. *
  208. * @param $response
  209. */
  210. private function setCookiesFromApiResponse($response) {
  211. foreach ($response->getHeader('Set-Cookie') as $cookieStr) {
  212. $cookie = SetCookie::fromString($cookieStr);
  213. $name = $cookie->getName();
  214. $value = $cookie->getValue();
  215. $expires = $cookie->getExpires();
  216. $path = $cookie->getPath();
  217. $domain = self::COOKIE_DOMAIN;
  218. $secure = $cookie->getSecure();
  219. $httpOnly = $cookie->getHttpOnly();
  220. setcookie($name, $value, $expires, $path, $domain, $secure, $httpOnly);
  221. }
  222. }
  223. /**
  224. * Compare the last update date for the user to the GENERATION_DELAY delay
  225. * and return wether the user's data may be created/updated in the Typo3 DB
  226. *
  227. * @param string $username
  228. * @return bool
  229. */
  230. protected function shouldUserBeUpdated(string $username): bool
  231. {
  232. $cnn = $this->connectionPool->getConnectionForTable('fe_users');
  233. $q = $cnn->select(['tx_opentalent_generationDate'], 'fe_users', ['username' => $username]);
  234. $strGenDate = $q->fetch(3)[0];
  235. $genDate = DateTime::createFromFormat("Y-m-d H:i:s", $strGenDate);
  236. if ($genDate == null) {
  237. return true;
  238. }
  239. $now = new DateTime();
  240. $diff = $now->getTimestamp() - $genDate->getTimestamp();
  241. return ($diff > self::USER_UPDATE_DELAY);
  242. }
  243. /**
  244. * Create or update the Frontend-user record in the typo3 database (table 'fe_users')
  245. * with the data fetched from the Api
  246. *
  247. * @return bool
  248. */
  249. protected function createOrUpdateUser(): bool
  250. {
  251. // Get user's data from the API
  252. $userApiData = $this->getUserData();
  253. if (empty($userApiData)) {
  254. // An error happened, and even if the user was logged, we can not continue
  255. // (user's data and rights could have changed)
  256. return false;
  257. }
  258. $connection = $this->connectionPool->getConnectionForTable('fe_users');
  259. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  260. $randomStr = (new Random)->generateRandomHexString(20);
  261. // Front-end user
  262. $fe_row = [
  263. 'username' => $userApiData['username'],
  264. 'password' => $randomStr,
  265. 'name' => $userApiData['name'],
  266. 'first_name' => $userApiData['first_name'],
  267. 'description' => '[Warning: auto-generated record, do not modify] FE User',
  268. 'usergroup' => 21,
  269. 'deleted' => 0,
  270. 'tx_opentalent_opentalentId' => $userApiData['id'],
  271. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  272. ];
  273. // TODO: log a warning if a user with the same opentalentId exists (the user might have changed of username)
  274. $q = $connection->select(
  275. ['uid', 'tx_opentalent_opentalentId'],
  276. 'fe_users',
  277. ['username' => $userApiData['username']]
  278. );
  279. $row = $q->fetch(3);
  280. $uid = $row[0];
  281. $tx_opentalent_opentalentId = $row[1];
  282. if (!$uid) {
  283. // No existing user: create
  284. $connection->insert('fe_users', $fe_row);
  285. } else {
  286. // User exists: update
  287. if (!$tx_opentalent_opentalentId > 0) {
  288. $this->writeLogMessage('WARNING: FE user ' . $userApiData['username'] . ' has been replaced by an auto-generated version.');
  289. }
  290. $connection->update('fe_users', $fe_row, ['uid' => $uid]);
  291. }
  292. return true;
  293. }
  294. /**
  295. * Get the data for the current authenticated user from the API
  296. *
  297. * @return array
  298. */
  299. protected function getUserData(): array
  300. {
  301. $this->fillCookieJar();
  302. try {
  303. $response = $this->client->request('GET', self::GET_USER_DATA_URI, ['cookies' => $this->jar]);
  304. } catch (RequestException $e) {
  305. return [];
  306. } catch (GuzzleException $e) {
  307. return [];
  308. }
  309. return json_decode($response->getBody(), true);
  310. }
  311. /**
  312. * Authenticates user using Opentalent auth service.
  313. * /!\ The 'authUser' method is required by the Typo3 authentification system
  314. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
  315. *
  316. * @param array $user Data of user.
  317. * @return int Code that shows if user is really authenticated.
  318. * @throws GuzzleException
  319. */
  320. public function authUser(array $user): int
  321. {
  322. if ($user['username'] == $this->getAuthenticatedUsername()) {
  323. // Tha API just validated this user's auth
  324. return self::STATUS_AUTHENTICATION_SUCCESS;
  325. } else if ($this->authInfo['loginType'] === 'FE') {
  326. return self::STATUS_AUTHENTICATION_FAILURE;
  327. } else if (isset($user['tx_opentalent_opentalentId']) and $user['tx_opentalent_opentalentId'] != null) {
  328. // This is a user from the Opentalent DB, and the API refused its auth
  329. // (For performance only, since the password stored in the Typo3 is a random string,
  330. // the auth will be refused by the other services anyway)
  331. return self::STATUS_AUTHENTICATION_FAILURE;
  332. }
  333. // This may be a user using another auth system
  334. return self::STATUS_AUTHENTICATION_CONTINUE;
  335. }
  336. /**
  337. * Send a logout request to the API, remove the sessions cookies then logout
  338. * /!\ Frontend only
  339. */
  340. public function logout(): bool
  341. {
  342. try {
  343. $response = $this->client->request(
  344. 'GET',
  345. self::LOGOUT_URI
  346. );
  347. if ($response->getStatusCode() != 200) {
  348. return false;
  349. }
  350. // The API accepted the logout request
  351. // Unset the session cookies (SESSID and BEARER)
  352. if (isset($_COOKIE['BEARER'])) {
  353. unset($_COOKIE['BEARER']);
  354. $this->unset_cookie('BEARER');
  355. }
  356. if (isset($_COOKIE['SFSESSID'])) {
  357. unset($_COOKIE['SFSESSID']);
  358. $this->unset_cookie('SFSESSID');
  359. }
  360. $this->pObj->logoff();
  361. return true;
  362. } catch (RequestException $e) {
  363. return false;
  364. } catch (GuzzleException $e) {
  365. return false;
  366. }
  367. }
  368. /**
  369. * Unset a cookie by reducing its expiration date
  370. *
  371. * @param string $name
  372. * @return bool
  373. */
  374. protected function unset_cookie(string $name): bool
  375. {
  376. $res = setcookie($name, '', time() - 1, '/', self::COOKIE_DOMAIN);
  377. if (!$res) {
  378. $this->writeLogMessage('Error while unsetting ' . $name . ' cookie');
  379. }
  380. return $res;
  381. }
  382. /**
  383. * Writes log message. Destination log depends on the current system mode.
  384. * For FE the function writes to the admin panel log. For BE messages are
  385. * sent to the system log. If developer log is enabled, messages are also
  386. * sent there.
  387. *
  388. * This function accepts variable number of arguments and can format
  389. * parameters. The syntax is the same as for sprintf()
  390. *
  391. * @param string $message Message to output
  392. * @param array<int, mixed> $params
  393. * @see \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog()
  394. */
  395. public function writeLogMessage($message, ...$params)
  396. {
  397. if (!empty($params)) {
  398. $message = vsprintf($message, $params);
  399. }
  400. if (TYPO3_MODE === 'BE') {
  401. GeneralUtility::sysLog($message, 'ot_connect');
  402. } else {
  403. /** @var TimeTracker $timeTracker */
  404. $timeTracker = GeneralUtility::makeInstance(TimeTracker::class);
  405. $timeTracker->setTSlogMessage($message);
  406. }
  407. }
  408. }