Skip to content

Commit

Permalink
* **Fix** fix logger were always disabled.
Browse files Browse the repository at this point in the history
* **Fix** fix client_secret was not correctly saved.
* **Improvement** logs have been added when retrieving refresh token and currency rates.
  • Loading branch information
bruno-blackbird committed Mar 2, 2022
1 parent 1ad5981 commit 63936b5
Show file tree
Hide file tree
Showing 8 changed files with 298 additions and 257 deletions.
12 changes: 8 additions & 4 deletions Logger/Logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,12 @@ class Logger extends \Monolog\Logger
*/
protected $scopeConfig;

public function __construct($name, array $handlers = [], array $processors = [], ScopeConfigInterface $scopeConfig)
{
public function __construct(
$name,
ScopeConfigInterface $scopeConfig,
array $handlers = [],
array $processors = []
) {
$this->scopeConfig = $scopeConfig;
parent::__construct($name, $handlers, $processors);
}
Expand All @@ -54,8 +58,8 @@ public function debug($message, array $context = [])
*/
protected function isLoggingActive()
{
return $this->scopeConfig->getValue(
'transiteo_activation/duties/debug_mode',
return (bool)$this->scopeConfig->getValue(
'transiteo_settings/duties/debug_mode',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}
Expand Down
10 changes: 7 additions & 3 deletions Logger/QueueLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,12 @@ class QueueLogger extends \Monolog\Logger
*/
protected $scopeConfig;

public function __construct($name, array $handlers = [], array $processors = [], ScopeConfigInterface $scopeConfig)
{
public function __construct(
$name,
ScopeConfigInterface $scopeConfig,
array $handlers = [],
array $processors = []
) {
$this->scopeConfig = $scopeConfig;
parent::__construct($name, $handlers, $processors);
}
Expand All @@ -55,7 +59,7 @@ public function debug($message, array $context = [])
protected function isLoggingActive()
{
return $this->scopeConfig->getValue(
'transiteo_activation/duties/debug_mode',
'transiteo_settings/duties/debug_mode',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
}
Expand Down
128 changes: 65 additions & 63 deletions Model/TransiteoApiService.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,12 @@
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7\ResponseFactory;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\FlagManager;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\Webapi\Rest\Request;
use Transiteo\LandedCost\Controller\Cookie;
use Transiteo\LandedCost\Logger\Logger;

/**
* Class TransiteoApiService
*/
class TransiteoApiService
Expand All @@ -43,8 +39,8 @@ class TransiteoApiService
public const API_REQUEST_URI = 'https://api.transiteo.io/';

/**
* API AUTH request URL
*/
* API AUTH request URL
*/
public const API_AUTH_REQUEST_URI = 'https://auth.transiteo.io/';

/**
Expand Down Expand Up @@ -114,49 +110,16 @@ public function __construct(
}

/**
* Get Id Token to use for auth in next requests
* @return string
*/
protected function getIdTokenFromApi()
public function getIdToken():string
{
$clientId = $this->config->getTransiteoClientId();
$refreshToken = $this->config->getTransiteoRefreshToken();

$response = $this->doRequest(
self::API_AUTH_REQUEST_URI . "oauth2/token",
[
'headers' => [
'Content-type' => 'application/x-www-form-urlencoded',
],
'form_params' => [
'grant_type' => 'refresh_token',
'client_id' => $clientId,
'refresh_token' => $refreshToken
],
'http_errors' => false
],
Request::HTTP_METHOD_POST
);

$status = $response->getStatusCode(); // 200 status code
$responseBody = $response->getBody();
$responseContent = $responseBody->getContents(); // here you will have the API response in JSON format

if ($status == 200) {
$responseArray = $this->serializer->unserialize($responseContent);

$this->idToken = $responseArray['id_token'];
//$this->cookie->set(self::COOKIE_NAME, $this->idToken, 3500);
$this->flagManager->saveFlag(self::ID_TOKEN_FLAG_NAME, $this->idToken);
$accessToken = $responseArray['access_token'];
$this->flagManager->saveFlag(self::ACCESS_TOKEN_FLAG_NAME, $accessToken);
$expires_in = $responseArray['expires_in'];
$this->flagManager->saveFlag(self::TOKEN_EXPIRES_IN_FLAG_NAME, $expires_in);
$token_type = $responseArray['token_type'];
$this->flagManager->saveFlag(self::TOKEN_TYPE_FLAG_NAME, $token_type);
$date = new \DateTime();
$this->flagManager->saveFlag(self::TOKEN_RECEIVED_TIMESTAMP, $date->getTimestamp());
$idTokenStored = $this->flagManager->getFlagData(self::ID_TOKEN_FLAG_NAME);
if (($this->idToken === null && $idTokenStored === null) || $this->hasTokenExpired()) {
$this->refreshIdToken();
} elseif ($this->idToken === null && $idTokenStored !== null) {
$this->idToken = $idTokenStored;
}

return $this->idToken;
}

Expand All @@ -165,7 +128,7 @@ protected function getIdTokenFromApi()
*
* @return bool
*/
protected function hasTokenExpired()
protected function hasTokenExpired(): bool
{
$tokenTimestamp = $this->flagManager->getFlagData(self::TOKEN_RECEIVED_TIMESTAMP);
if ($tokenTimestamp !== null) {
Expand All @@ -179,9 +142,62 @@ protected function hasTokenExpired()
/**
* Refresh the Id Token
*/
public function refreshIdToken()
public function refreshIdToken(): string
{
$this->idToken = $this->getIdTokenFromApi();
return $this->idToken;
}

/**
* Get Id Token to use for auth in next requests
*/
protected function getIdTokenFromApi(): string
{
$this->idToken = $this->getIdTokenFromApi();
$clientId = $this->config->getTransiteoClientId();
$refreshToken = $this->config->getTransiteoRefreshToken();

$request = [
'headers' => [
'Content-type' => 'application/x-www-form-urlencoded',
],
'form_params' => [
'grant_type' => 'refresh_token',
'client_id' => $clientId,
'refresh_token' => $refreshToken
],
'http_errors' => false
];

$this->logger->debug("Getting new refresh token");
$this->logger->debug(\json_encode($request));

$response = $this->doRequest(
self::API_AUTH_REQUEST_URI . "oauth2/token",
$request,
Request::HTTP_METHOD_POST
);

$status = $response->getStatusCode(); // 200 status code
$responseBody = $response->getBody();
$responseContent = $responseBody->getContents(); // here you will have the API response in JSON format
$this->logger->debug($responseContent);

if ($status === 200 && $responseContent !== "") {
$responseArray = $this->serializer->unserialize($responseContent);

$this->idToken = $responseArray['id_token'];
$this->flagManager->saveFlag(self::ID_TOKEN_FLAG_NAME, $this->idToken);
$accessToken = $responseArray['access_token'];
$this->flagManager->saveFlag(self::ACCESS_TOKEN_FLAG_NAME, $accessToken);
$expires_in = $responseArray['expires_in'];
$this->flagManager->saveFlag(self::TOKEN_EXPIRES_IN_FLAG_NAME, $expires_in);
$token_type = $responseArray['token_type'];
$this->flagManager->saveFlag(self::TOKEN_TYPE_FLAG_NAME, $token_type);
$date = new \DateTime();
$this->flagManager->saveFlag(self::TOKEN_RECEIVED_TIMESTAMP, $date->getTimestamp());
}

return (string) $this->idToken;
}

/**
Expand Down Expand Up @@ -217,20 +233,6 @@ public function doRequest(
return $response;
}

/**
* @return mixed
*/
public function getIdToken()
{
$idTokenStored = $this->flagManager->getFlagData(self::ID_TOKEN_FLAG_NAME);
if (($this->idToken === null && $idTokenStored === null) || $this->hasTokenExpired()) {
$this->refreshIdToken();
} elseif ($this->idToken === null && $idTokenStored !== null) {
$this->idToken = $idTokenStored;
}
return $this->idToken;
}

/**
* @return Logger
*/
Expand Down
3 changes: 3 additions & 0 deletions Service/CurrencyRate.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ public function __construct(
*/
public function getCurrencyRate($currencyFrom, $currencyTo, $timeout, $amount = 1):string
{
$this->transiteoApiService->getLogger()->debug("Getting Currency rate");

$response = $this->transiteoApiService->doRequest(
TransiteoApiService::API_REQUEST_URI . "v1/data/currency?amount=1&toCurrency=" . $currencyTo . "&fromCurrency=" . $currencyFrom,
[
Expand All @@ -60,6 +62,7 @@ public function getCurrencyRate($currencyFrom, $currencyTo, $timeout, $amount =

$responseBody = $response->getBody();
$responseContent = $responseBody->getContents();
$this->transiteoApiService->getLogger()->debug($responseContent);

if ($status == "401") {
$responseArray = \json_decode($responseContent);
Expand Down
Loading

0 comments on commit 63936b5

Please sign in to comment.