| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571 |
- <?php
- namespace Opentalent\OtConnect\Service;
- use DateTime;
- use GuzzleHttp\Cookie\CookieJar;
- use GuzzleHttp\Cookie\SetCookie;
- use GuzzleHttp\Exception\GuzzleException;
- use GuzzleHttp\Exception\RequestException;
- use Opentalent\OtCore\Exception\ApiRequestException;
- use Opentalent\OtCore\Logging\OtLogger;
- use Opentalent\OtCore\Service\OpentalentApiService;
- use Opentalent\OtCore\Service\OpentalentEnvService;
- use Opentalent\OtCore\Utility\NavigationUtils;
- use Opentalent\OtCore\Utility\UrlUtils;
- use TYPO3\CMS\Core\Crypto\Random;
- use TYPO3\CMS\Core\Database\ConnectionPool;
- use TYPO3\CMS\Core\Database\Query\QueryHelper;
- use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
- use TYPO3\CMS\Core\TimeTracker\TimeTracker;
- use TYPO3\CMS\Core\Utility\GeneralUtility;
- use \TYPO3\CMS\Core\Authentication\AbstractAuthenticationService;
- /**
- * Authentication service based on the Opentalent API.
- * See the README for more
- */
- class OtAuthenticationService extends AbstractAuthenticationService
- {
- CONST LOGIN_URI = 'api/login_check';
- CONST GET_USER_DATA_URI = 'api/user/datafortypo3';
- CONST ISAUTH_URI = 'api/user/isauthenticated';
- CONST LOGOUT_URI = 'logout';
- CONST GROUP_FE_ALL_UID = 18076;
- CONST GROUP_ADMIN_STANDARD_UID = 1;
- CONST GROUP_ADMIN_PREMIUM_UID = 3;
- // Cookies' domain needs to be the same that the api's cookies, or guzzle will ignore them.
- CONST COOKIE_DOMAIN = 'opentalent.fr';
- CONST PRODUCT_MAPPING = [
- "school-standard" => 1, // Association writer basic
- "artist-standard" => 1, // Association writer basic
- "school-premium" => 3, // Association writer full
- "artist-premium" => 3, // Association writer full
- "manager" => 3, // Association writer full
- ];
- /**
- * The time in seconds during which the user's data in DB won't be re-updated after the last successful update
- * Set it to 0 to disable the delay
- */
- CONST USER_UPDATE_DELAY = 300;
- /**
- * 0 - Authentification failed, no more services will be called...
- * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-service-chain
- *
- * @var int
- */
- const STATUS_AUTHENTICATION_FAILURE = 0;
- /**
- * 100 - OK, but call next services...
- * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-service-chain
- *
- * @var int
- */
- const STATUS_AUTHENTICATION_CONTINUE = 100;
- /**
- * 200 - authenticated and no more checking needed
- * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-service-chain
- *
- * @var int
- */
- const STATUS_AUTHENTICATION_SUCCESS = 200;
- /**
- * @var object
- */
- private object $apiService;
- /**
- * Guzzle Cookie Jar
- *
- * @var CookieJar
- */
- private CookieJar $jar;
- /**
- * @var \TYPO3\CMS\Core\Database\ConnectionPool
- */
- private $connectionPool;
- public function injectConnectionPool(ConnectionPool $connectionPool)
- {
- $this->connectionPool = $connectionPool;
- }
- /**
- * OtAuthenticationService constructor.
- */
- public function __construct() {
- $this->jar = new CookieJar;
- $this->apiService = GeneralUtility::makeInstance(OpentalentApiService::class, null, null, $this->jar);
- $this->connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
- }
- /**
- * This function returns the user record back to the AbstractUserAuthentication.
- * It does not mean that user is authenticated, it only means that user is found.
- * /!\ The 'getUser' method is required by the Typo3 authentification system
- * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
- *
- * @return array|bool User record or false (content of fe_users/be_users as appropriate for the current mode)
- * @throws GuzzleException
- */
- public function getUser()
- {
- // Does the user already have a session on the Opentalent API?
- $username = $this->getAuthenticatedUsername();
- $isBackend = $this->authInfo['loginType'] === 'BE';
- if ($username != null && !$isBackend && $this->login['status'] === 'logout') {
- // This is a logout request
- $this->logout();
- return false;
- }
- if ($username != null && $this->login['status'] === 'login' && $this->login['uname'] != $username) {
- // The user trying to log in is not the one authenticated on the Opentalent API
- // We let the TYPO3 auth service handle it
- return false;
- } else if ($username == null && $this->login['status'] != 'login') {
- // The user has no current session on Opentalent.fr and this is not a login request
- return false;
- } else if ($this->login['status'] === 'login' && $this->login['uname'] && $this->login['uident']) {
- // This is a login request
- $username = $this->login['uname'];
- $password = $this->login['uident'];
- // Send a login request for the user to the Opentalent Api, and return the data
- // of the matching user, or false if le login failed
- $logged = $this->logUser($username, $password);
- if (!$logged) {
- return false;
- }
- }
- /// At this point, username should be set
- if ($username === null) {
- return false;
- }
- // Request the latest data for the user and write it in the Typo3 DB
- // * The shouldUserBeUpdated() method checks if the user was already
- // generated in the last minutes, to avoid unnecessary operations *
- if ($this->shouldUserBeUpdated($username, $isBackend)) {
- $wasUpdated = $this->createOrUpdateUser($isBackend);
- if (!$wasUpdated) {
- // An error happened during the update of the user's data
- // since its data may have changed (credentials, rights, rôles...)
- // we can't allow him to connect.
- return false;
- }
- }
- // No need to check Pid for those users
- $this->authInfo['db_user']['checkPidList'] = '';
- $this->authInfo['db_user']['check_pid_clause'] = '';
- // Fetch the typo3 user from the database
- return $this->fetchUserRecord($username, '', $this->authInfo['db_user']);
- }
- /**
- * Returns the name of the user currently authenticated on the API side, or null if no user is logged in
- *
- * @return string|null
- * @throws GuzzleException
- */
- protected function getAuthenticatedUsername(): ?string
- {
- $this->fillCookieJar();
- try {
- if (!$this->jar->getCookieByName('BEARER')) {
- // Missing cookie : No need to ask API
- return null;
- }
- $response = $this->apiService->get(self::ISAUTH_URI, [], ['cookies' => $this->jar]);
- if ($response->getStatusCode() != 200) {
- return null;
- }
- return json_decode((string)$response->getBody());
- } catch (ApiRequestException $e) {
- return null;
- }
- }
- /**
- * Update the guzzle cookie jar with the current session's ones
- */
- private function fillCookieJar() {
- foreach (['BEARER', 'SFSESSID', 'AccessId'] as $cookieName) {
- if (array_key_exists($cookieName, $_COOKIE)) {
- $cookie = new SetCookie();
- $cookie->setName($cookieName);
- $cookie->setValue($_COOKIE[$cookieName]);
- $cookie->setDomain(self::COOKIE_DOMAIN);
- $this->jar->setCookie($cookie);
- }
- }
- }
- /**
- * Submit a login request to the API
- *
- * @param string $username
- * @param string $password
- * @return bool Returns true if the api accepted the login request
- * @throws GuzzleException
- */
- protected function logUser(string $username, string $password): bool
- {
- try {
- $response = $this->apiService->request(
- 'POST',
- self::LOGIN_URI,
- [],
- ['form_params' => ['_username' => $username, '_password' => $password]]
- );
- if ($response->getStatusCode() != 200) {
- return false;
- }
- $data = json_decode((string)$response->getBody(), true);
- # Redirect the user if the password needs to be changed
- if (isset($data['type']) && $data['type'] === 'change_password') {
- $redirectTo = UrlUtils::join(
- OpentalentEnvService::get('ADMIN_BASE_URL'), "/#/account/", $data['organization'], "/secure/password/", $data['token']
- );
- NavigationUtils::redirect($redirectTo);
- }
- // The API accepted the login request
- // Set the cookies returned by the Api (SESSID and BEARER)
- $this->setCookiesFromApiResponse($response);
- return true;
- } catch (ApiRequestException $e) {
- return false;
- }
- }
- /**
- * Get the cookies from the API response and set them
- *
- * @param $response
- */
- private function setCookiesFromApiResponse($response) {
- foreach ($response->getHeader('Set-Cookie') as $cookieStr) {
- $cookie = SetCookie::fromString($cookieStr);
- $name = $cookie->getName();
- $value = $cookie->getValue();
- $expires = $cookie->getExpires() ?? 0;
- $path = $cookie->getPath();
- $secure = $cookie->getSecure();
- $httpOnly = $cookie->getHttpOnly();
- $_COOKIE[$name] = $value;
- setcookie($name, $value, $expires, $path, self::COOKIE_DOMAIN, $secure, $httpOnly);
- setcookie($name, $value, $expires, $path, '.' . self::COOKIE_DOMAIN, $secure, $httpOnly);
- if (!preg_match('/(.*\.)?opentalent\.fr/', $_SERVER['HTTP_HOST'])) {
- setcookie($name, $value, $expires, $path, $_SERVER['HTTP_HOST'], $secure, $httpOnly);
- }
- }
- }
- /**
- * Compare the last update date for the user to the GENERATION_DELAY delay
- * and return wether the user's data may be created/updated in the Typo3 DB
- *
- * @param string $username
- * @return bool
- */
- protected function shouldUserBeUpdated(string $username, bool $isBackend = false): bool
- {
- $table = $isBackend ? 'be_users' : 'fe_users';
- $cnn = $this->connectionPool->getConnectionForTable($table);
- $q = $cnn->select(['tx_opentalent_generationDate'], $table, ['username' => $username]);
- $strGenDate = $q->fetch(3)[0] ?? '1970-01-01 00:00:00';
- $genDate = DateTime::createFromFormat("Y-m-d H:i:s", $strGenDate);
- if ($genDate == null) {
- return true;
- }
- $now = new DateTime();
- $diff = $now->getTimestamp() - $genDate->getTimestamp();
- return ($diff > self::USER_UPDATE_DELAY);
- }
- /**
- * Create or update the Frontend-user record in the typo3 database (table 'fe_users')
- * with the data fetched from the Api
- *
- * @return bool
- */
- protected function createOrUpdateUser(bool $isBackend = false): bool
- {
- $table = $isBackend ? 'be_users' : 'fe_users';
- $group_table = $isBackend ? 'be_groups' : 'fe_groups';
- $prefix = $isBackend ? 'BE' : 'FE';
- // Get user's data from the API
- $userApiData = $this->getUserData();
- if (empty($userApiData)) {
- // An error happened, and even if the user was logged, we can not continue
- // (user's data and rights could have changed)
- return false;
- }
- $connection = $this->connectionPool->getConnectionForTable($table);
- // Since we don't want to store the password in the TYPO3 DB, we store a random string instead
- $randomStr = (new Random)->generateRandomHexString(30);
- // Front-end user
- $user_row = [
- 'username' => $userApiData['username'],
- 'password' => $randomStr,
- 'description' => "[Warning: auto-generated record, do not modify] $prefix User",
- 'deleted' => 0,
- 'tx_opentalent_opentalentId' => $userApiData['id'],
- 'tx_opentalent_generationDate' => date('Y/m/d H:i:s')
- ];
- if ($isBackend) {
- $user_row['lang'] = 'fr';
- $user_row['options'] = "3";
- $user_row['TSconfig'] = "options.uploadFieldsInTopOfEB = 1";
- } else {
- $user_row['name'] = $userApiData['name'];
- $user_row['first_name'] = $userApiData['first_name'];
- }
- $groupsUid = [];
- if (!$isBackend) {
- $groupsUid[] = self::GROUP_FE_ALL_UID;
- }
- // Loop over the accesses of the user to list the matching organization groups
- if ($userApiData['accesses']) {
- foreach ($userApiData['accesses'] as $accessData) {
- if ($isBackend && !$accessData['isEditor'] && !$accessData['admin_access']) {
- continue;
- }
- if ($isBackend && $accessData['admin_access']) {
- $adminGroupUid = $accessData['product'] === 'artist_premium' ?
- self::GROUP_ADMIN_PREMIUM_UID :
- self::GROUP_ADMIN_STANDARD_UID;
- if (!in_array($adminGroupUid, $groupsUid)) {
- $groupsUid[] = $adminGroupUid;
- }
- }
- $organizationId = $accessData['organizationId'];
- // get the group for this organization
- $groupUid = $connection->fetchOne(
- "select g.uid
- from typo3.$group_table g
- inner join (select uid, ot_website_uid from typo3.pages where is_siteroot) p
- on g." . ($isBackend ? 'db_mountpoints' : 'pid') . " = p.uid
- inner join typo3.ot_websites w on p.ot_website_uid = w.uid
- where w.organization_id=:organizationId;",
- ['organizationId' => $organizationId]
- );
- if ($groupUid) {
- $groupsUid[] = $groupUid;
- } else {
- OtLogger::warning("Warning: no " . strtolower($prefix) . "_group found for organization " . $organizationId);
- }
- }
- }
- if ($isBackend && empty($groupsUid)) {
- throw new \Exception("No BE_group found for user " . $userApiData['username']);
- }
- $user_row['usergroup'] = join(',', $groupsUid);
- // TODO: log a warning if a user with the same opentalentId exists (the user might have changed of username)
- $q = $connection->select(
- ['uid', 'tx_opentalent_opentalentId'],
- $table,
- ['username' => $userApiData['username']]
- );
- $row = $q->fetch(3);
- $uid = $row[0] ?? null;
- $tx_opentalent_opentalentId = $row[1] ?? null;
- if (!$uid) {
- // No existing user: create
- $connection->insert($table, $user_row);
- } else {
- // User exists: update
- if (!$tx_opentalent_opentalentId > 0) {
- OtLogger::warning(
- "WARNING: $prefix user " . $userApiData['username'] .
- ' has been replaced by an auto-generated version.'
- );
- }
- $connection->update($table, $user_row, ['uid' => $uid]);
- }
- return true;
- }
- /**
- * Get the data for the current authenticated user from the API
- *
- * @return array
- */
- protected function getUserData(): ?array
- {
- $this->fillCookieJar();
- try {
- $response = $this->apiService->request('GET', self::GET_USER_DATA_URI, [], ['cookies' => $this->jar]);
- } catch (ApiRequestException $e) {
- return [];
- }
- return json_decode($response->getBody(), true);
- }
- /**
- * Authenticates user using Opentalent auth service.
- * /!\ The 'authUser' method is required by the Typo3 authentification system
- * @see https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Authentication/Index.html#the-auth-services-api
- *
- * @param array $user Data of user.
- * @return int Code that shows if user is really authenticated.
- * @throws GuzzleException
- */
- public function authUser(array $user): int
- {
- if ($user['username'] == $this->getAuthenticatedUsername()) {
- // Tha API just validated this user's auth
- return self::STATUS_AUTHENTICATION_SUCCESS;
- } else if ($this->authInfo['loginType'] === 'FE') {
- return self::STATUS_AUTHENTICATION_FAILURE;
- } else if (isset($user['tx_opentalent_opentalentId']) and $user['tx_opentalent_opentalentId'] != null) {
- // This is a user from the Opentalent DB, and the API refused its auth
- // (For performance only, since the password stored in the Typo3 is a random string,
- // the auth will be refused by the other services anyway)
- return self::STATUS_AUTHENTICATION_FAILURE;
- }
- // This may be a user using another auth system
- return self::STATUS_AUTHENTICATION_CONTINUE;
- }
- /**
- * Send a logout request to the API, remove the sessions cookies then logout
- * /!\ Frontend only
- */
- public function logout(): bool
- {
- try {
- $response = $this->apiService->request(
- 'GET',
- self::LOGOUT_URI
- );
- if ($response->getStatusCode() != 200) {
- return false;
- }
- // The API accepted the logout request
- // Unset the session cookies (SESSID and BEARER)
- if (isset($_COOKIE['BEARER'])) {
- unset($_COOKIE['BEARER']);
- $this->unset_cookie('BEARER');
- }
- if (isset($_COOKIE['SFSESSID'])) {
- unset($_COOKIE['SFSESSID']);
- $this->unset_cookie('SFSESSID');
- }
- $this->pObj->logoff();
- return true;
- } catch (RequestException $e) {
- return false;
- } catch (GuzzleException $e) {
- return false;
- }
- }
- /**
- * Unset a cookie by reducing its expiration date
- *
- * @param string $name
- */
- protected function unset_cookie(string $name)
- {
- setcookie($name, '', 1, '/', $_SERVER['HTTP_HOST']); // for custom domains (not in .opentalent.fr)
- setcookie($name, '', 1, '/', self::COOKIE_DOMAIN); // for opentalent.fr subdomains
- }
- /**
- * Get a user from DB by username
- *
- * @param string $username User name
- * @param string $extraWhere Additional WHERE clause: " AND ...
- * @param array|string $dbUserSetup User db table definition, or empty string for $this->db_user
- * @return mixed User array or FALSE
- */
- public function fetchUserRecordTemp($username, $extraWhere = '', $dbUserSetup = '')
- {
- $dbUser = is_array($dbUserSetup) ? $dbUserSetup : $this->db_user;
- $user = false;
- if ($username || $extraWhere) {
- $query = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($dbUser['table']);
- $query->getRestrictions()->removeAll()
- ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
- $constraints = array_filter([
- QueryHelper::stripLogicalOperatorPrefix($dbUser['check_pid_clause']),
- QueryHelper::stripLogicalOperatorPrefix($dbUser['enable_clause']),
- QueryHelper::stripLogicalOperatorPrefix($extraWhere),
- ]);
- if (!empty($username)) {
- array_unshift(
- $constraints,
- $query->expr()->eq(
- $dbUser['username_column'],
- $query->createNamedParameter($username, \PDO::PARAM_STR)
- )
- );
- }
- $user = $query->select('*')
- ->from($dbUser['table'])
- ->where(...$constraints)
- ->execute()
- ->fetch();
- }
- return $user;
- }
- }
|