OtAuthenticationService.php 16 KB

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