OtAuthenticationService.php 19 KB

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