فهرست منبع

refactor ot auth service

Olivier Massot 4 سال پیش
والد
کامیت
28c90d741b

+ 18 - 26
ot_connect/Classes/Service/OtAuthenticationService.php

@@ -2,11 +2,12 @@
 namespace Opentalent\OtConnect\Service;
 
 use DateTime;
-use GuzzleHttp\Client;
 use GuzzleHttp\Cookie\CookieJar;
 use GuzzleHttp\Cookie\SetCookie;
 use GuzzleHttp\Exception\GuzzleException;
 use GuzzleHttp\Exception\RequestException;
+use Opentalent\OtCore\Exception\ApiRequestException;
+use Opentalent\OtCore\Service\OpentalentApiService;
 use TYPO3\CMS\Core\Crypto\Random;
 use TYPO3\CMS\Core\Database\ConnectionPool;
 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
@@ -19,16 +20,13 @@ use \TYPO3\CMS\Core\Authentication\AbstractAuthenticationService;
  */
 class OtAuthenticationService extends AbstractAuthenticationService
 {
-
-    CONST DOMAIN = 'https://api.opentalent.fr';
-    CONST API_URI = self::DOMAIN . '/api/';
-    CONST LOGIN_URI = self::API_URI . 'login_check';
-    CONST GET_USER_DATA_URI = self::API_URI . 'user/datafortypo3';
-    CONST ISAUTH_URI = self::API_URI . 'user/isauthenticated';
-    CONST LOGOUT_URI = self::API_URI . 'logout';
+    CONST LOGIN_URI = 'api/login_check';
+    CONST GET_USER_DATA_URI = 'api/user/datafortypo3';
+    CONST ISAUTH_URI = 'api/user/isauthenticated';
+    CONST LOGOUT_URI = 'api/logout';
     CONST GROUP_FE_ALL_UID = 18076;
 
-    // Cookies'domain needs to be the same that the api's cookies, or guzzle will ignore them.
+    // 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 = [
@@ -70,12 +68,9 @@ class OtAuthenticationService extends AbstractAuthenticationService
     const STATUS_AUTHENTICATION_SUCCESS = 200;
 
     /**
-     * Guzzle Client
-     *
-     * @see http://docs.guzzlephp.org/en/stable/
-     * @var Client
+     * @var object
      */
-    private Client $client;
+    private object $apiService;
 
     /**
      * Guzzle Cookie Jar
@@ -99,7 +94,7 @@ class OtAuthenticationService extends AbstractAuthenticationService
      */
     public function __construct() {
         $this->jar = new CookieJar;
-        $this->client = new Client(['base_uri' => self::DOMAIN, 'cookies' => $this->jar]);
+        $this->apiService = GeneralUtility::makeInstance(OpentalentApiService::class, null, null, $this->jar);
         $this->connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
     }
 
@@ -177,7 +172,7 @@ class OtAuthenticationService extends AbstractAuthenticationService
     {
         $this->fillCookieJar();
         try {
-            $response = $this->client->request('GET', self::ISAUTH_URI, ['cookies' => $this->jar]);
+            $response = $this->apiService->get(self::ISAUTH_URI, [], ['cookies' => $this->jar]);
 
             if ($response->getStatusCode() != 200) {
                 return null;
@@ -185,10 +180,9 @@ class OtAuthenticationService extends AbstractAuthenticationService
 
             return json_decode((string)$response->getBody());
 
-        } catch (RequestException $e) {
+        } catch (ApiRequestException $e) {
             return null;
         }
-
     }
 
     /**
@@ -221,7 +215,7 @@ class OtAuthenticationService extends AbstractAuthenticationService
     {
 
         try {
-            $response = $this->client->request(
+            $response = $this->apiService->request(
                 'POST',
                 self::LOGIN_URI,
                 ['form_params' => ['_username' => $username, '_password' => $password]]
@@ -237,7 +231,7 @@ class OtAuthenticationService extends AbstractAuthenticationService
             $this->setCookiesFromApiResponse($response);
             return true;
 
-        } catch (RequestException $e) {
+        } catch (ApiRequestException $e) {
             return false;
         }
     }
@@ -353,14 +347,12 @@ class OtAuthenticationService extends AbstractAuthenticationService
      *
      * @return array
      */
-    protected function getUserData(): array
+    protected function getUserData(): ?array
     {
         $this->fillCookieJar();
         try {
-            $response = $this->client->request('GET', self::GET_USER_DATA_URI, ['cookies' => $this->jar]);
-        } catch (RequestException $e) {
-            return [];
-        } catch (GuzzleException $e) {
+            $response = $this->apiService->request('GET', self::GET_USER_DATA_URI, [], ['cookies' => $this->jar]);
+        } catch (ApiRequestException $e) {
             return [];
         }
         return json_decode($response->getBody(), true);
@@ -401,7 +393,7 @@ class OtAuthenticationService extends AbstractAuthenticationService
     public function logout(): bool
     {
         try {
-            $response = $this->client->request(
+            $response = $this->apiService->request(
                 'GET',
                 self::LOGOUT_URI
             );

+ 1 - 0
ot_core/Classes/Domain/Repository/BaseApiRepository.php

@@ -80,6 +80,7 @@ abstract class BaseApiRepository implements LoggerAwareInterface
      */
     protected function getApiRecords(array $params = [], ?string $forceUri = null): ApiPagedCollection
     {
+        $params = array("_format" => "json") + $params;   // _format should be the first param to match unit-tests fixtures
         if(!isset($params['itemsPerPage'])) {
             $params['itemsPerPage'] = (string)self::DEFAULT_ITEMS_PER_PAGE;
         }

+ 36 - 21
ot_core/Classes/Service/OpentalentApiService.php

@@ -8,7 +8,6 @@ use Opentalent\OtCore\Exception\ApiRequestException;
 use Psr\Http\Message\ResponseInterface;
 use Psr\Log\LoggerAwareInterface;
 use Psr\Log\LoggerAwareTrait;
-use TYPO3\CMS\Core\Core\ApplicationContext;
 use TYPO3\CMS\Extbase\Object\ObjectManagerInterface;
 
 class OpentalentApiService implements LoggerAwareInterface
@@ -18,12 +17,12 @@ class OpentalentApiService implements LoggerAwareInterface
     const DEFAULT_BASE_URI = 'https://api.opentalent.fr';
     protected array $variants_uris = [
           "preprod.opentalent.fr" => "https://api.preprod.opentalent.fr",
-          "local.sub.opentalent.fr" => "http://nginx",
-          "typo3" => "http://nginx"
+          "local.sub.opentalent.fr" => "http://local.nginx.opentalent.fr",
+          "typo3" => "http://local.nginx.opentalent.fr"
     ];
 
-    protected Client $client;
-    protected ApplicationContext $context;
+    protected object $client;
+    protected object $context;
 
     /**
      * @param ObjectManagerInterface $objectManager
@@ -32,7 +31,8 @@ class OpentalentApiService implements LoggerAwareInterface
      */
     public function __construct(
         ?object $client = null,
-        ?object $context = null
+        ?object $context = null,
+        ?object $cookieJar = null
     ) {
         // Get the current context (prod, dev...)
         if ($context === null) {
@@ -42,14 +42,21 @@ class OpentalentApiService implements LoggerAwareInterface
         }
 
         if ($client === null) {
-            $this->client = new Client(['base_uri' => $this->getApiUri()]);
+            $args = ['base_uri' => $this->getApiUri()];
+            if ($cookieJar != null) {
+                $args['cookies'] = $cookieJar;
+            }
+            $this->client = new Client($args);
         } else {
             $this->client = $client;
         }
     }
 
+    public function getClient() {
+        return $this->client;
+    }
+
     /**
-     * [FOR TESTS ONLY]
      * @param Client $client
      */
     public function injectClient(Client $client) {
@@ -83,13 +90,20 @@ class OpentalentApiService implements LoggerAwareInterface
      * @param array $params
      * @return array
      * @throws ApiRequestException
+     * @throws \JsonException
      */
     public function getJsonDecoded(
         string $uri,
         array $params = []
     ): array
     {
-        return json_decode($this->getBody($uri, $params),true);
+        $body = $this->getBody($uri, $params);
+        $data = json_decode($body,true);
+        if ($data !== null) {
+            return json_decode($body,true);
+        } else {
+            throw new \JsonException('Response can not be decoded as json: ' . substr($body, 0, 300) . '...');
+        }
     }
 
     /**
@@ -120,44 +134,45 @@ class OpentalentApiService implements LoggerAwareInterface
      */
     public function get(
         string $uri,
-        array $params = []
+        array $params = [],
+        array $config = []
     ): ResponseInterface
     {
-        return $this->request('GET', $uri, $params);
+        return $this->request('GET', $uri, $params, $config);
     }
 
     /**
      * Send a request to the API and returns
      * the result as a Response object
      *
+     * @param string $httpMethod
      * @param string $uri
      * @param array $params
-     * @param string $httpMethod
+     * @param array $config
      * @return ResponseInterface
      * @throws ApiRequestException
      */
     public function request(
         string $httpMethod,
         string $uri,
-        array $params = []
+        array $params = [],
+        array $config = []
     ): ?ResponseInterface
     {
         $parsedUrl = parse_url($uri);
+        $params += ($parsedUrl['query'] ?? []);
 
-        $uri = rtrim($uri, '/') . '?_format=json';
-
-        if ($parsedUrl['query']) {
-            $uri = $uri . '&' . $parsedUrl['query'];
-        }
-        if ($params) {
-            $uri .= '&' . http_build_query($params);
+        $path = http_build_query($params);
+        $uri = rtrim($uri, '/');
+        if ($path) {
+            $uri .= '?' . $path;
         }
 
         try {
             if ($this->context->isDevelopment()) {
                 $this->logger->info('API Call: ' . $uri);
             }
-            return $this->client->request($httpMethod, $uri);
+            return $this->client->request($httpMethod, $uri, $config);
         } catch (GuzzleException $e) {
             throw ApiRequestException::from_exception($e);
         }