OtAuthenticationService.php 17 KB

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