OtAuthenticationService.php 18 KB

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