Skip to content

Commit

Permalink
Remove http event handle, better authentication exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
keithbrink committed Oct 8, 2021
1 parent cd8ac07 commit a69c59f
Show file tree
Hide file tree
Showing 13 changed files with 189 additions and 216 deletions.
1 change: 1 addition & 0 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
'no_trailing_whitespace_in_comment' => true,
'no_unreachable_default_argument_value' => true,
'no_useless_return' => true,
'no_unused_imports' => true,
'no_whitespace_before_comma_in_array' => true,
'no_whitespace_in_blank_line' => true,
'normalize_index_brace' => true,
Expand Down
2 changes: 1 addition & 1 deletion src/AmznSPAConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function __construct(
) {
$this->validateStringEnum($marketplace_id, MarketplacesList::allIdentifiers());

$this->http = new Factory(new HttpEventHandler);
$this->http = new Factory;
$this->tokens = new AuthTokensDTO(
refresh_token: $lwa_refresh_token,
access_token: $lwa_access_token,
Expand Down
33 changes: 19 additions & 14 deletions src/AmznSPAHttp.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Illuminate\Support\Arr;
use Jasara\AmznSPA\Constants\JasaraNotes;
use Jasara\AmznSPA\DataTransferObjects\Schemas\MetadataSchema;
use Jasara\AmznSPA\Exceptions\AuthenticationException;
use Psr\Http\Message\RequestInterface;

class AmznSPAHttp
Expand Down Expand Up @@ -99,6 +100,10 @@ private function call(string $method, string $url, array $data = [], bool $grant

return $this->handleResponse($response, $method, $url);
} catch (RequestException $e) {
if ($e->getCode() === 401) {
throw new AuthenticationException($e->response);
}

try {
if ($this->shouldReturnErrorResponse($e)) {
return $this->handleResponse($e->response, $method, $url);
Expand All @@ -112,10 +117,10 @@ private function call(string $method, string $url, array $data = [], bool $grant
}

return $this->call($method, $url, $data, $grantless);
} catch (\Exception $e) {
$this->logException($e, $method, $url);
} catch (\Exception $e) { // @codeCoverageIgnore
$this->logException($e, $method, $url); // @codeCoverageIgnore

throw $e;
throw $e; // @codeCoverageIgnore
}
}

Expand Down Expand Up @@ -145,7 +150,7 @@ private function refreshTokens(): void

private function refreshGrantlessToken()
{
$scope = 'sellingpartnerapi::' . $this->grantless_resource;
$scope = 'sellingpartnerapi::'.$this->grantless_resource;

$amzn = new AmznSPA($this->config);
$token = $amzn->lwa->getGrantlessAccessToken($scope);
Expand All @@ -161,7 +166,7 @@ private function setupHttp(Factory $http, bool $grantless = false): void
]);

$this->http->beforeSending(function (Request $request) {
$this->config->getLogger()->debug('[AmznSPA] Pre-Request ' . $request->method() . ' ' . $request->url(), [
$this->config->getLogger()->debug('[AmznSPA] Pre-Request '.$request->method().' '.$request->url(), [
'unsigned_request_headers' => $this->cleanData($request->headers()),
'request_data' => $this->cleanData($request->data()),
]);
Expand All @@ -174,16 +179,16 @@ private function setupHttp(Factory $http, bool $grantless = false): void

private function getToken(bool $grantless = false): string
{
if (!$grantless) {
if (! $grantless) {
$tokens = $this->config->getTokens();
if (!$tokens->access_token || ($tokens->expires_at && $tokens->expires_at->subMinutes(5)->isPast())) {
if (! $tokens->access_token || ($tokens->expires_at && $tokens->expires_at->subMinutes(5)->isPast())) {
$this->refreshTokens();
}

return $this->config->getTokens()->access_token;
} else {
$grantless_token = $this->config->getGrantlessToken();
if (!$grantless_token->access_token || ($grantless_token->expires_at && $grantless_token->expires_at->subMinutes(5)->isPast())) {
if (! $grantless_token->access_token || ($grantless_token->expires_at && $grantless_token->expires_at->subMinutes(5)->isPast())) {
$this->refreshGrantlessToken();
}

Expand Down Expand Up @@ -224,14 +229,14 @@ private function signRequest(string $aws_region): void

private function handleRequestException(RequestException $e, bool $grantless)
{
if (!$this->shouldRefreshToken($e->response->json())) {
if (! $this->shouldRefreshToken($e->response->json())) {
throw $e;
}
if (!$this->shouldRetry()) {
if (! $this->shouldRetry()) {
throw $e;
}

if (!$grantless) {
if (! $grantless) {
$this->refreshTokens();
} else {
$this->refreshGrantlessToken();
Expand All @@ -244,7 +249,7 @@ public function shouldReturnErrorResponse(RequestException $e): bool
return false;
}

if (!Arr::get($e->response->json(), 'errors')) {
if (! Arr::get($e->response->json(), 'errors')) {
return false;
}

Expand All @@ -255,7 +260,7 @@ private function logException(Exception $e, $method, $url)
{
$request_headers = $this->request ? $this->cleanData($this->request->headers()) : null;

$this->config->getLogger()->error('[AmznSPA] Response Error ' . strtoupper($method) . ' ' . $url . ' -- ' . $e->getMessage(), [
$this->config->getLogger()->error('[AmznSPA] Response Error '.strtoupper($method).' '.$url.' -- '.$e->getMessage(), [
'unsigned_request_headers' => $request_headers,
'request_data' => $this->request ? $this->cleanData($this->request->data()) : null,
'response_headers' => isset($e->response) ? $e->response->headers() : null,
Expand Down Expand Up @@ -293,7 +298,7 @@ private function getMetadata(Response $response): MetadataSchema

private function handleResponse(Response $response, string $method, string $url): array
{
$this->config->getLogger()->debug('[AmznSPA] Response ' . strtoupper($method) . ' ' . $url, [
$this->config->getLogger()->debug('[AmznSPA] Response '.strtoupper($method).' '.$url, [
'response_headers' => $response->headers(),
'response_data' => $this->cleanData($response->json()),
]);
Expand Down
27 changes: 27 additions & 0 deletions src/Exceptions/AuthenticationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,33 @@

namespace Jasara\AmznSPA\Exceptions;

use Illuminate\Http\Client\Response;
use Illuminate\Support\Arr;

class AuthenticationException extends AmznSPAException
{
public function __construct(Response $response = null)
{
$message = $response ? $this->getMessageFromResponse($response) : '';
parent::__construct($message);
}

private function getMessageFromResponse(Response $response): string
{
$message = '';

$data = $response->json();

if (array_key_exists('error', $data)) {
$message .= 'Error: '.$data['error'];
}
if (array_key_exists('error_description', $data)) {
$message .= 'Description: '.$data['error_description'];
}
if ($errors_message = Arr::get($data, 'errors.0.message')) {
$message = $errors_message;
}

return $message;
}
}
54 changes: 0 additions & 54 deletions src/HttpEventHandler.php

This file was deleted.

29 changes: 26 additions & 3 deletions src/Resources/LwaResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,21 @@

use Closure;
use Illuminate\Http\Client\Factory;
use Illuminate\Http\Client\Response;
use Jasara\AmznSPA\Constants\Marketplace;
use Jasara\AmznSPA\Contracts\ResourceContract;
use Jasara\AmznSPA\DataTransferObjects\ApplicationKeysDTO;
use Jasara\AmznSPA\DataTransferObjects\AuthTokensDTO;
use Jasara\AmznSPA\DataTransferObjects\GrantlessTokenDTO;
use Jasara\AmznSPA\Exceptions\AmznSPAException;
use Jasara\AmznSPA\Exceptions\AuthenticationException;
use Jasara\AmznSPA\Traits\ValidatesParameters;

class LwaResource implements ResourceContract
{
use ValidatesParameters;

const ENDPOINT = 'https://api.amazon.com/auth/o2/token';
public const ENDPOINT = 'https://api.amazon.com/auth/o2/token';

public function __construct(
private Factory $http,
Expand All @@ -32,10 +34,10 @@ public function getAuthUrl(?string $state = null): string
$redirect_url = $this->redirect_url;

$params = http_build_query(compact('redirect_url', 'state'));
$url = $this->getBaseUrlFromMarketplace() . '/apps/authorize/consent';
$url = $this->getBaseUrlFromMarketplace().'/apps/authorize/consent';

if ($params) {
$url .= '?' . $params;
$url .= '?'.$params;
}

return $url;
Expand Down Expand Up @@ -77,6 +79,10 @@ private function callGetTokens(string $spapi_oauth_code): AuthTokensDTO
'client_secret' => $this->application_keys->lwa_client_secret,
]);

if ($response->failed()) {
$this->handleError($response);
}

$tokens = $this->formatTokenResponse($response->json());

$this->storeLwaTokens($tokens);
Expand All @@ -93,6 +99,10 @@ public function getAccessTokenFromRefreshToken(string $refresh_token): AuthToken
'client_secret' => $this->application_keys->lwa_client_secret,
]);

if ($response->failed()) {
$this->handleError($response);
}

$tokens = $this->formatTokenResponse($response->json());

$this->storeLwaTokens($tokens);
Expand All @@ -109,6 +119,10 @@ public function getGrantlessAccessToken(string $scope): GrantlessTokenDTO
'client_secret' => $this->application_keys->lwa_client_secret,
]);

if ($response->failed()) {
$this->handleError($response);
}

return $this->formatGrantlessTokenResponse($response->json());
}

Expand Down Expand Up @@ -150,4 +164,13 @@ private function getBaseUrlFromMarketplace(): string
{
return $this->marketplace->getBaseUrl();
}

private function handleError(Response $response)
{
if ($response->status() === 401) {
throw new AuthenticationException($response);
}

return $response->throw();
}
}
47 changes: 0 additions & 47 deletions src/SimpleDispatcher.php

This file was deleted.

7 changes: 3 additions & 4 deletions tests/Setup/SetupAmznSPAConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
use Illuminate\Support\Str;
use Jasara\AmznSPA\AmznSPAConfig;
use Jasara\AmznSPA\Constants\MarketplacesList;
use Jasara\AmznSPA\HttpEventHandler;

trait SetupAmznSPAConfig
{
Expand All @@ -15,7 +14,7 @@ public function setupMinimalConfig(string $marketplace_id = null, Factory $http
$config = new AmznSPAConfig(
marketplace_id: $marketplace_id ?: MarketplacesList::allIdentifiers()[rand(0, 15)],
application_id: Str::random(),
redirect_url: Str::random() . '.com',
redirect_url: Str::random().'.com',
lwa_refresh_token: Str::random(),
lwa_access_token: Str::random(),
grantless_access_token: Str::random(),
Expand Down Expand Up @@ -59,7 +58,7 @@ public function setupConfigWithFakeHttp(string $stub, int $status_code = 200): a

public function fakeHttpStub(string $stub, int $status_code = 200): Factory
{
$http = new Factory(new HttpEventHandler);
$http = new Factory;
$http->fake([
'*' => $http->response($this->loadHttpStub($stub), $status_code, [
'x-amzn-RequestId' => Str::random(),
Expand All @@ -71,7 +70,7 @@ public function fakeHttpStub(string $stub, int $status_code = 200): Factory

public function loadHttpStub(string $stub): array
{
$stub_filepath = __DIR__ . '/../stubs/' . $stub . '.json';
$stub_filepath = __DIR__.'/../stubs/'.$stub.'.json';

return json_decode(file_get_contents($stub_filepath), true);
}
Expand Down
Loading

0 comments on commit a69c59f

Please sign in to comment.