OtAuthenticationService.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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\Service\OpentalentApiService;
  10. use TYPO3\CMS\Core\Crypto\Random;
  11. use TYPO3\CMS\Core\Database\ConnectionPool;
  12. use TYPO3\CMS\Core\TimeTracker\TimeTracker;
  13. use TYPO3\CMS\Core\Utility\GeneralUtility;
  14. use \TYPO3\CMS\Core\Authentication\AbstractAuthenticationService;
  15. /**
  16. * Authentication service based on the Opentalent API.
  17. * See the README for more
  18. */
  19. class OtAuthenticationService extends AbstractAuthenticationService
  20. {
  21. CONST LOGIN_URI = 'api/login_check';
  22. CONST GET_USER_DATA_URI = 'api/user/datafortypo3';
  23. CONST ISAUTH_URI = 'api/user/isauthenticated';
  24. CONST LOGOUT_URI = 'logout';
  25. CONST GROUP_FE_ALL_UID = 18076;
  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. * @var object
  63. */
  64. private object $apiService;
  65. /**
  66. * Guzzle Cookie Jar
  67. *
  68. * @var CookieJar
  69. */
  70. private CookieJar $jar;
  71. /**
  72. * @var \TYPO3\CMS\Core\Database\ConnectionPool
  73. */
  74. private $connectionPool;
  75. public function injectConnectionPool(ConnectionPool $connectionPool)
  76. {
  77. $this->connectionPool = $connectionPool;
  78. }
  79. /**
  80. * OtAuthenticationService constructor.
  81. */
  82. public function __construct() {
  83. $this->jar = new CookieJar;
  84. $this->apiService = GeneralUtility::makeInstance(OpentalentApiService::class, null, null, $this->jar);
  85. $this->connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
  86. }
  87. /**
  88. * This function returns the user record back to the AbstractUserAuthentication.
  89. * It does not mean that user is authenticated, it only means that user is found.
  90. * /!\ The 'getUser' method is required by the Typo3 authentification system
  91. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
  92. *
  93. * @return array|bool User record or false (content of fe_users/be_users as appropriate for the current mode)
  94. * @throws GuzzleException
  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. /// At this point, username should be set
  124. if ($username === null) {
  125. return false;
  126. }
  127. // Request the latest data for the user and write it in the Typo3 DB
  128. // * The shouldUserBeUpdated() method checks if the user was already
  129. // generated in the last minutes, to avoid unnecessary operations *
  130. if ($this->shouldUserBeUpdated($username)) {
  131. $wasUpdated = $this->createOrUpdateUser();
  132. if (!$wasUpdated) {
  133. // An error happened during the update of the user's data
  134. // since its data may have changed (credentials, rights, rôles...)
  135. // we can't allow him to connect.
  136. return false;
  137. }
  138. }
  139. // No need to check Pid for those users
  140. $this->authInfo['db_user']['checkPidList'] = '';
  141. $this->authInfo['db_user']['check_pid_clause'] = '';
  142. // Fetch the typo3 user from the database
  143. return $this->fetchUserRecord($username, '', $this->authInfo['db_user']);
  144. }
  145. /**
  146. * Returns the name of the user currently authenticated on the API side, or null if no user is logged in
  147. *
  148. * @return string|null
  149. * @throws GuzzleException
  150. */
  151. protected function getAuthenticatedUsername(): ?string
  152. {
  153. $this->fillCookieJar();
  154. try {
  155. $response = $this->apiService->get(self::ISAUTH_URI, [], ['cookies' => $this->jar]);
  156. if ($response->getStatusCode() != 200) {
  157. return null;
  158. }
  159. return json_decode((string)$response->getBody());
  160. } catch (ApiRequestException $e) {
  161. return null;
  162. }
  163. }
  164. /**
  165. * Update the guzzle cookie jar with the current session's ones
  166. */
  167. private function fillCookieJar() {
  168. foreach (['BEARER', 'SFSESSID', 'AccessId'] as $cookieName) {
  169. if (array_key_exists($cookieName, $_COOKIE)) {
  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->apiService->request(
  190. 'POST',
  191. self::LOGIN_URI,
  192. [],
  193. ['form_params' => ['_username' => $username, '_password' => $password]]
  194. );
  195. if ($response->getStatusCode() != 200) {
  196. return false;
  197. }
  198. // The API accepted the login request
  199. // Set the cookies returned by the Api (SESSID and BEARER)
  200. $this->setCookiesFromApiResponse($response);
  201. return true;
  202. } catch (ApiRequestException $e) {
  203. return false;
  204. }
  205. }
  206. /**
  207. * Get the cookies from the API response and set them
  208. *
  209. * @param $response
  210. */
  211. private function setCookiesFromApiResponse($response) {
  212. foreach ($response->getHeader('Set-Cookie') as $cookieStr) {
  213. $cookie = SetCookie::fromString($cookieStr);
  214. $name = $cookie->getName();
  215. $value = $cookie->getValue();
  216. $expires = $cookie->getExpires();
  217. $path = $cookie->getPath();
  218. $secure = $cookie->getSecure();
  219. $httpOnly = $cookie->getHttpOnly();
  220. $_COOKIE[$name] = $value;
  221. setcookie($name, $value, $expires, $path, self::COOKIE_DOMAIN, $secure, $httpOnly);
  222. setcookie($name, $value, $expires, $path, '.' . self::COOKIE_DOMAIN, $secure, $httpOnly);
  223. if (!preg_match('/(.*\.)?opentalent\.fr/', $_SERVER['HTTP_HOST'])) {
  224. setcookie($name, $value, $expires, $path, $_SERVER['HTTP_HOST'], $secure, $httpOnly);
  225. }
  226. }
  227. }
  228. /**
  229. * Compare the last update date for the user to the GENERATION_DELAY delay
  230. * and return wether the user's data may be created/updated in the Typo3 DB
  231. *
  232. * @param string $username
  233. * @return bool
  234. */
  235. protected function shouldUserBeUpdated(string $username): bool
  236. {
  237. $cnn = $this->connectionPool->getConnectionForTable('fe_users');
  238. $q = $cnn->select(['tx_opentalent_generationDate'], 'fe_users', ['username' => $username]);
  239. $strGenDate = $q->fetch(3)[0];
  240. $genDate = DateTime::createFromFormat("Y-m-d H:i:s", $strGenDate);
  241. if ($genDate == null) {
  242. return true;
  243. }
  244. $now = new DateTime();
  245. $diff = $now->getTimestamp() - $genDate->getTimestamp();
  246. return ($diff > self::USER_UPDATE_DELAY);
  247. }
  248. /**
  249. * Create or update the Frontend-user record in the typo3 database (table 'fe_users')
  250. * with the data fetched from the Api
  251. *
  252. * @return bool
  253. */
  254. protected function createOrUpdateUser(): bool
  255. {
  256. // Get user's data from the API
  257. $userApiData = $this->getUserData();
  258. if (empty($userApiData)) {
  259. // An error happened, and even if the user was logged, we can not continue
  260. // (user's data and rights could have changed)
  261. return false;
  262. }
  263. $connection = $this->connectionPool->getConnectionForTable('fe_users');
  264. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  265. $randomStr = (new Random)->generateRandomHexString(20);
  266. // Front-end user
  267. $fe_row = [
  268. 'username' => $userApiData['username'],
  269. 'password' => $randomStr,
  270. 'name' => $userApiData['name'],
  271. 'first_name' => $userApiData['first_name'],
  272. 'description' => '[Warning: auto-generated record, do not modify] FE User',
  273. 'deleted' => 0,
  274. 'tx_opentalent_opentalentId' => $userApiData['id'],
  275. 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
  276. ];
  277. $groupsUid = [self::GROUP_FE_ALL_UID];
  278. if ($userApiData['accesses']) {
  279. foreach ($userApiData['accesses'] as $accessData) {
  280. $organizationId = $accessData['organizationId'];
  281. // get the fe_group for this organization
  282. $groupUid = $connection->fetchOne(
  283. "select g.uid
  284. from typo3.fe_groups g
  285. inner join (select uid, ot_website_uid from typo3.pages where is_siteroot) p
  286. on g.pid = p.uid
  287. inner join typo3.ot_websites w on p.ot_website_uid = w.uid
  288. where w.organization_id=:organizationId;",
  289. ['organizationId' => $organizationId]
  290. );
  291. if ($groupUid) {
  292. $groupsUid[] = $groupUid;
  293. } else {
  294. $this->writeLogMessage("Warning: no fe_group found for organization " . $organizationId);
  295. }
  296. }
  297. }
  298. $fe_row['usergroup'] = join(',', $groupsUid);
  299. // TODO: log a warning if a user with the same opentalentId exists (the user might have changed of username)
  300. $q = $connection->select(
  301. ['uid', 'tx_opentalent_opentalentId'],
  302. 'fe_users',
  303. ['username' => $userApiData['username']]
  304. );
  305. $row = $q->fetch(3);
  306. $uid = $row[0];
  307. $tx_opentalent_opentalentId = $row[1];
  308. if (!$uid) {
  309. // No existing user: create
  310. $connection->insert('fe_users', $fe_row);
  311. } else {
  312. // User exists: update
  313. if (!$tx_opentalent_opentalentId > 0) {
  314. $this->writeLogMessage('WARNING: FE user ' . $userApiData['username'] . ' has been replaced by an auto-generated version.');
  315. }
  316. $connection->update('fe_users', $fe_row, ['uid' => $uid]);
  317. }
  318. return true;
  319. }
  320. /**
  321. * Get the data for the current authenticated user from the API
  322. *
  323. * @return array
  324. */
  325. protected function getUserData(): ?array
  326. {
  327. $this->fillCookieJar();
  328. try {
  329. $response = $this->apiService->request('GET', self::GET_USER_DATA_URI, [], ['cookies' => $this->jar]);
  330. } catch (ApiRequestException $e) {
  331. return [];
  332. }
  333. return json_decode($response->getBody(), true);
  334. }
  335. /**
  336. * Authenticates user using Opentalent auth service.
  337. * /!\ The 'authUser' method is required by the Typo3 authentification system
  338. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
  339. *
  340. * @param array $user Data of user.
  341. * @return int Code that shows if user is really authenticated.
  342. * @throws GuzzleException
  343. */
  344. public function authUser(array $user): int
  345. {
  346. if ($user['username'] == $this->getAuthenticatedUsername()) {
  347. // Tha API just validated this user's auth
  348. return self::STATUS_AUTHENTICATION_SUCCESS;
  349. } else if ($this->authInfo['loginType'] === 'FE') {
  350. return self::STATUS_AUTHENTICATION_FAILURE;
  351. } else if (isset($user['tx_opentalent_opentalentId']) and $user['tx_opentalent_opentalentId'] != null) {
  352. // This is a user from the Opentalent DB, and the API refused its auth
  353. // (For performance only, since the password stored in the Typo3 is a random string,
  354. // the auth will be refused by the other services anyway)
  355. return self::STATUS_AUTHENTICATION_FAILURE;
  356. }
  357. // This may be a user using another auth system
  358. return self::STATUS_AUTHENTICATION_CONTINUE;
  359. }
  360. /**
  361. * Send a logout request to the API, remove the sessions cookies then logout
  362. * /!\ Frontend only
  363. */
  364. public function logout(): bool
  365. {
  366. try {
  367. $response = $this->apiService->request(
  368. 'GET',
  369. self::LOGOUT_URI
  370. );
  371. if ($response->getStatusCode() != 200) {
  372. return false;
  373. }
  374. // The API accepted the logout request
  375. // Unset the session cookies (SESSID and BEARER)
  376. if (isset($_COOKIE['BEARER'])) {
  377. unset($_COOKIE['BEARER']);
  378. $this->unset_cookie('BEARER');
  379. }
  380. if (isset($_COOKIE['SFSESSID'])) {
  381. unset($_COOKIE['SFSESSID']);
  382. $this->unset_cookie('SFSESSID');
  383. }
  384. $this->pObj->logoff();
  385. return true;
  386. } catch (RequestException $e) {
  387. return false;
  388. } catch (GuzzleException $e) {
  389. return false;
  390. }
  391. }
  392. /**
  393. * Unset a cookie by reducing its expiration date
  394. *
  395. * @param string $name
  396. */
  397. protected function unset_cookie(string $name)
  398. {
  399. setcookie($name, '', 1, '/', $_SERVER['HTTP_HOST']); // for custom domains (not in .opentalent.fr)
  400. setcookie($name, '', 1, '/', self::COOKIE_DOMAIN); // for opentalent.fr subdomains
  401. }
  402. /**
  403. * Writes log message. Destination log depends on the current system mode.
  404. * For FE the function writes to the admin panel log. For BE messages are
  405. * sent to the system log. If developer log is enabled, messages are also
  406. * sent there.
  407. *
  408. * This function accepts variable number of arguments and can format
  409. * parameters. The syntax is the same as for sprintf()
  410. *
  411. * @param string $message Message to output
  412. * @param array<int, mixed> $params
  413. * @see \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog()
  414. */
  415. public function writeLogMessage($message, ...$params)
  416. {
  417. if (!empty($params)) {
  418. $message = vsprintf($message, $params);
  419. }
  420. if (TYPO3_MODE === 'BE') {
  421. GeneralUtility::sysLog($message, 'ot_connect');
  422. } else {
  423. /** @var TimeTracker $timeTracker */
  424. $timeTracker = GeneralUtility::makeInstance(TimeTracker::class);
  425. $timeTracker->setTSlogMessage($message);
  426. }
  427. }
  428. }