OtAuthenticationService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 = 'http://api.opentalent.fr/app.php';
  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 userShouldBeRegenerated() 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. if ($_SERVER['SERVER_ADDR'] == '127.0.0.1') {
  201. $domain = $_SERVER['SERVER_NAME'];
  202. } else {
  203. $domain = $cookie->getDomain();
  204. }
  205. $secure = $cookie->getSecure();
  206. $httpOnly = $cookie->getHttpOnly();
  207. setcookie($name, $value, $expires, $path, $domain, $secure, $httpOnly);
  208. }
  209. }
  210. /**
  211. * Compare the last update date for the user to the GENERATION_DELAY delay
  212. * and return wether the user's data may be created/updated in the Typo3 DB
  213. *
  214. * @param string $username
  215. * @return bool
  216. */
  217. protected function shouldUserBeUpdated($username) {
  218. $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('fe_users');
  219. $q = $connection->select(['tx_otconnect_generationDate'], 'fe_users', ['username' => $username]);
  220. $strGenDate = $q->fetch(3)[0];
  221. $genDate = \DateTime::createFromFormat("Y-m-d H:i:s", $strGenDate);
  222. if ($genDate == null) {
  223. return true;
  224. }
  225. $now = new \DateTime();
  226. $diff = $now->getTimestamp() - $genDate->getTimestamp();
  227. return ($diff > self::USER_UPDATE_DELAY);
  228. }
  229. /**
  230. * Create or update the Frontend-user record in the typo3 database (table 'fe_users')
  231. * and the Backend-user (table 'be_users', only if is admin)
  232. * with the data fetched from the Api
  233. *
  234. * @return bool
  235. */
  236. protected function createOrUpdateUser() {
  237. // Get user's data from the API
  238. $userApiData = $this->getUserData();
  239. if (empty($userApiData)) {
  240. // An error happened, and even if the user was logged, we can not continue
  241. // (user's data and rights could have changed)
  242. return false;
  243. }
  244. $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('fe_users');
  245. // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
  246. $randomStr = (new \TYPO3\CMS\Core\Crypto\Random)->generateRandomHexString(10);
  247. // Front-end user
  248. $fe_row = [
  249. 'username' => $userApiData['username'],
  250. 'password' => $randomStr,
  251. 'name' => $userApiData['name'],
  252. 'first_name' => $userApiData['first_name'],
  253. 'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] FE User',
  254. 'tx_otconnect_opentalentId' => $userApiData['id'],
  255. 'tx_otconnect_generationDate' => date('Y/m/d H:i:s')
  256. ];
  257. // TODO: log a warning if a user with the same opentalentId exists (the user might have changed of username)
  258. $q = $connection->select(['uid'], 'fe_users', ['tx_otconnect_opentalentId' => $userApiData['id']]);
  259. $uid = $q->fetch(3)[0];
  260. if (!$uid) {
  261. // No existing user: create
  262. $connection->insert('fe_users', $fe_row);
  263. } else {
  264. // User exists: update
  265. $connection->update('fe_users', $fe_row, ['uid' => $uid]);
  266. }
  267. // Back-end user: only if admin
  268. foreach ($userApiData['accesses'] as $access) {
  269. //<<<<< for testing purpose TODO: remove
  270. $access['admin_access'] = 'true';
  271. // >>>>>
  272. if ($access['admin_access'] == 'true') {
  273. $be_row = [
  274. 'username' => $userApiData['username'],
  275. 'password' => $randomStr,
  276. 'description' => '[ATTENTION: enregistrement auto-généré, ne pas modifier directement] BE Admin for ' . $access['subDomain'] . ' (id: ' . $access['id'] . ')',
  277. // 'avatar' => $userApiData['profile']['avatar'],
  278. 'lang' => 'fr',
  279. 'usergroup' => isset(self::PRODUCT_MAPPING[$access['product']]) ? self::PRODUCT_MAPPING[$access['product']] : 1,
  280. 'tx_otconnect_opentalentId' => $userApiData['id'],
  281. 'tx_otconnect_organizationId' => $access['organizationId'],
  282. 'tx_otconnect_generationDate' => date('Y/m/d H:i:s')
  283. ];
  284. $q = $connection->select(['uid'], 'be_users', ['tx_otconnect_opentalentId' => $userApiData['id']]);
  285. $uid = $q->fetch(3)[0];
  286. if (!$uid) {
  287. // No existing user: create
  288. $connection->insert('be_users', $be_row);
  289. } else {
  290. // User exists: update
  291. $connection->update('be_users', $be_row, ['uid' => $uid]);
  292. }
  293. }
  294. }
  295. return true;
  296. }
  297. /**
  298. * Get the data for the current authenticated user from the API
  299. *
  300. * @return array
  301. */
  302. protected function getUserData() {
  303. $this->fillCookieJar();
  304. try {
  305. $response = $this->client->request('GET', self::GET_USER_DATA_URI, ['cookies' => $this->jar]);
  306. } catch (RequestException $e) {
  307. return [];
  308. }
  309. return json_decode($response->getBody(), true);
  310. }
  311. /**
  312. * Authenticates user using Opentalent auth service.
  313. * /!\ The 'authUser' method is required by the Typo3 authentification system
  314. * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
  315. *
  316. * @param array $user Data of user.
  317. * @return int Code that shows if user is really authenticated.
  318. */
  319. public function authUser(array $user)
  320. {
  321. if ($user['username'] == $this->getAuthenticatedUsername()) {
  322. // Tha API just validated this user's auth
  323. return self::STATUS_AUTHENTICATION_SUCCESS;
  324. } else if ($this->authInfo['loginType'] === 'FE') {
  325. return self::STATUS_AUTHENTICATION_FAILURE;
  326. } else if (isset($user['tx_otconnect_opentalentId']) and $user['tx_otconnect_opentalentId'] != null) {
  327. // This is a user from the Opentalent DB, and the API refused its auth
  328. // (For performance only, since the password stored in the Typo3 is a random string,
  329. // the auth will be refused by the other services anyway)
  330. return self::STATUS_AUTHENTICATION_FAILURE;
  331. }
  332. // This may be a user using another auth system
  333. return self::STATUS_AUTHENTICATION_CONTINUE;
  334. }
  335. /**
  336. * Send a logout request to the API, remove the sessions cookies then logout
  337. * /!\ Frontend only
  338. */
  339. public function logout() {
  340. try {
  341. $response = $this->client->request(
  342. 'GET',
  343. self::LOGOUT_URI
  344. );
  345. if ($response->getStatusCode() != 200) {
  346. return false;
  347. }
  348. // The API accepted the logout request
  349. // Unset the session cookies (SESSID and BEARER)
  350. if (isset($_COOKIE['BEARER'])) {
  351. unset($_COOKIE['BEARER']);
  352. setcookie('BEARER', null, -1, '/');
  353. }
  354. if (isset($_COOKIE['SFSESSID'])) {
  355. setcookie('SFSESSID', null, -1, '/');
  356. unset($_COOKIE['SFSESSID']);
  357. }
  358. $this->pObj->logoff();
  359. return true;
  360. } catch (RequestException $e) {
  361. return false;
  362. }
  363. }
  364. /**
  365. * Writes log message. Destination log depends on the current system mode.
  366. * For FE the function writes to the admin panel log. For BE messages are
  367. * sent to the system log. If developer log is enabled, messages are also
  368. * sent there.
  369. *
  370. * This function accepts variable number of arguments and can format
  371. * parameters. The syntax is the same as for sprintf()
  372. *
  373. * @param string $message Message to output
  374. * @param array<int, mixed> $params
  375. * @see \TYPO3\CMS\Core\Utility\GeneralUtility::sysLog()
  376. */
  377. public function writeLogMessage($message, ...$params)
  378. {
  379. if (!empty($params)) {
  380. $message = vsprintf($message, $params);
  381. }
  382. if (TYPO3_MODE === 'BE') {
  383. GeneralUtility::sysLog($message, 'ot_connect');
  384. } else {
  385. /** @var TimeTracker $timeTracker */
  386. $timeTracker = GeneralUtility::makeInstance(TimeTracker::class);
  387. $timeTracker->setTSlogMessage($message);
  388. }
  389. }
  390. }