Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"guzzlehttp/guzzle": "^7.6",
"guzzlehttp/promises": "^1.5 || ^2.0",
"guzzlehttp/psr7": "^2.0",
"psr/clock": "^1.0",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.1 || ^2.0"
},
Expand Down
16 changes: 16 additions & 0 deletions src/Helpers/SystemClock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace Saloon\Helpers;

use DateTimeImmutable;
use Psr\Clock\ClockInterface;

class SystemClock implements ClockInterface
{
public function now(): DateTimeImmutable
{
return new DateTimeImmutable();
}
}
5 changes: 4 additions & 1 deletion src/Http/Auth/AccessTokenAuthenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
namespace Saloon\Http\Auth;

use DateTimeImmutable;
use Psr\Clock\ClockInterface;
use Saloon\Helpers\SystemClock;
use Saloon\Http\PendingRequest;
use Saloon\Contracts\OAuthAuthenticator;

Expand All @@ -17,6 +19,7 @@ public function __construct(
public readonly string $accessToken,
public readonly ?string $refreshToken = null,
public readonly ?DateTimeImmutable $expiresAt = null,
private readonly ?ClockInterface $clock = null,
) {
//
}
Expand All @@ -38,7 +41,7 @@ public function hasExpired(): bool
return false;
}

return $this->expiresAt->getTimestamp() <= (new DateTimeImmutable)->getTimestamp();
return $this->expiresAt->getTimestamp() <= ($this->clock ?? new SystemClock())->now()->getTimestamp();
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Http/BaseResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class BaseResource
/**
* Constructor
*/
public function __construct(readonly protected Connector $connector)
public function __construct(protected readonly Connector $connector)
{
//
}
Expand Down
5 changes: 3 additions & 2 deletions src/Traits/OAuth2/AuthorizationCodeGrant.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
trait AuthorizationCodeGrant
{
use HasOAuthConfig;
use HasClock;

/**
* The state generated by the getAuthorizationUrl method.
Expand Down Expand Up @@ -158,7 +159,7 @@ protected function createOAuthAuthenticatorFromResponse(Response $response, ?str
$expiresAt = null;

if (isset($responseData->expires_in) && is_numeric($responseData->expires_in)) {
$expiresAt = (new DateTimeImmutable)->add(
$expiresAt = $this->getClock()->now()->add(
DateInterval::createFromDateString((int)$responseData->expires_in . ' seconds')
);
}
Expand All @@ -171,7 +172,7 @@ protected function createOAuthAuthenticatorFromResponse(Response $response, ?str
*/
protected function createOAuthAuthenticator(string $accessToken, ?string $refreshToken = null, ?DateTimeImmutable $expiresAt = null): OAuthAuthenticator
{
return new AccessTokenAuthenticator($accessToken, $refreshToken, $expiresAt);
return new AccessTokenAuthenticator($accessToken, $refreshToken, $expiresAt, $this->getClock());
}

/**
Expand Down
5 changes: 3 additions & 2 deletions src/Traits/OAuth2/ClientCredentialsGrant.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
trait ClientCredentialsGrant
{
use HasOAuthConfig;
use HasClock;

/**
* Get the access token
Expand Down Expand Up @@ -62,7 +63,7 @@ protected function createOAuthAuthenticatorFromResponse(Response $response): OAu
$expiresAt = null;

if (isset($responseData->expires_in) && is_numeric($responseData->expires_in)) {
$expiresAt = (new DateTimeImmutable)->add(
$expiresAt = $this->getClock()->now()->add(
DateInterval::createFromDateString((int)$responseData->expires_in . ' seconds')
);
}
Expand All @@ -75,7 +76,7 @@ protected function createOAuthAuthenticatorFromResponse(Response $response): OAu
*/
protected function createOAuthAuthenticator(string $accessToken, ?DateTimeImmutable $expiresAt = null): OAuthAuthenticator
{
return new AccessTokenAuthenticator($accessToken, null, $expiresAt);
return new AccessTokenAuthenticator($accessToken, null, $expiresAt, $this->getClock());
}

/**
Expand Down
21 changes: 21 additions & 0 deletions src/Traits/OAuth2/HasClock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace Saloon\Traits\OAuth2;

use Psr\Clock\ClockInterface;
use Saloon\Helpers\SystemClock;

/**
* @phpstan-ignore trait.unused
*/
trait HasClock
{
protected ?ClockInterface $clock = null;

protected function getClock(): ClockInterface
{
return $this->clock ??= new SystemClock();
}
}
29 changes: 18 additions & 11 deletions tests/Feature/Oauth2/AuthCodeFlowConnectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

use Saloon\Http\Request;
use Saloon\Http\Response;
use Saloon\Tests\Helpers\Date;
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;
use Saloon\Tests\Helpers\FrozenClock;
use Saloon\Http\OAuth2\GetUserRequest;
use Saloon\Exceptions\InvalidStateException;
use Saloon\Http\OAuth2\GetAccessTokenRequest;
Expand Down Expand Up @@ -97,7 +97,8 @@
MockResponse::make(['access_token' => 'access', 'refresh_token' => 'refresh', 'expires_in' => 3600], 200),
]);

$connector = new OAuth2Connector;
$frozenClock = FrozenClock::fromString('2024-01-01T12:00:00+00:00');
$connector = new OAuth2Connector($frozenClock);

$connector->withMockClient($mockClient);

Expand All @@ -107,6 +108,7 @@
expect($authenticator->getAccessToken())->toEqual('access');
expect($authenticator->getRefreshToken())->toEqual('refresh');
expect($authenticator->getExpiresAt())->toBeInstanceOf(DateTimeImmutable::class);
expect($authenticator->getExpiresAt()->getTimestamp() - $frozenClock->now()->getTimestamp())->toEqual(3600);
});

test('you can tap into the access token request and modify it', function () {
Expand Down Expand Up @@ -151,7 +153,7 @@
$connector = new OAuth2Connector;

$state = 'secret';
$url = $connector->getAuthorizationUrl(['scope-1', 'scope-2'], $state);
$connector->getAuthorizationUrl(['scope-1', 'scope-2'], $state);

$connector->getAccessToken('code', 'invalid', $state);
})->throws(InvalidStateException::class, 'Invalid state.');
Expand All @@ -161,18 +163,20 @@
MockResponse::make(['access_token' => 'access-new', 'refresh_token' => 'refresh-new', 'expires_in' => 3600]),
]);

$connector = new OAuth2Connector;
$frozenClock = FrozenClock::fromString('2024-01-01T12:00:00+00:00');
$connector = new OAuth2Connector($frozenClock);

$connector->withMockClient($mockClient);

$authenticator = new AccessTokenAuthenticator('access', 'refresh', Date::now()->addSeconds(3600)->toDateTime());
$authenticator = new AccessTokenAuthenticator('access', 'refresh', $frozenClock->addSeconds(3600), $frozenClock);

$newAuthenticator = $connector->refreshAccessToken($authenticator);

expect($newAuthenticator)->toBeInstanceOf(AccessTokenAuthenticator::class);
expect($newAuthenticator->getAccessToken())->toEqual('access-new');
expect($newAuthenticator->getRefreshToken())->toEqual('refresh-new');
expect($newAuthenticator->getExpiresAt())->toBeInstanceOf(DateTimeImmutable::class);
expect($newAuthenticator->getExpiresAt()->getTimestamp() - $frozenClock->now()->getTimestamp())->toEqual(3600);
});

test('you can tap into the refresh token request', function () {
Expand All @@ -184,7 +188,7 @@

$connector->withMockClient($mockClient);

$authenticator = new AccessTokenAuthenticator('access', 'refresh', Date::now()->addSeconds(3600)->toDateTime());
$authenticator = new AccessTokenAuthenticator('access', 'refresh', FrozenClock::fromString('2024-01-01T12:00:00+00:00')->addSeconds(3600));

$newAuthenticator = $connector->refreshAccessToken($authenticator, requestModifier: function (Request $request) {
$request->query()->add('yee', 'haw');
Expand All @@ -209,7 +213,7 @@

$connector->withMockClient($mockClient);

$authenticator = new AccessTokenAuthenticator('access', null, Date::now()->addSeconds(3600)->toDateTime());
$authenticator = new AccessTokenAuthenticator('access', null, FrozenClock::fromString('2024-01-01T12:00:00+00:00')->addSeconds(3600));

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('The provided OAuthAuthenticator does not contain a refresh token.');
Expand All @@ -226,7 +230,7 @@

$connector->withMockClient($mockClient);

$authenticator = new AccessTokenAuthenticator('access', 'refresh', Date::now()->addSeconds(3600)->toDateTime());
$authenticator = new AccessTokenAuthenticator('access', 'refresh', FrozenClock::fromString('2024-01-01T12:00:00+00:00')->addSeconds(3600));

$response = $connector->refreshAccessToken($authenticator, true);

Expand All @@ -242,7 +246,7 @@
$connector = new OAuth2Connector;
$connector->withMockClient($mockClient);

$accessToken = new AccessTokenAuthenticator('access', 'refresh', Date::now()->addSeconds(3600)->toDateTime());
$accessToken = new AccessTokenAuthenticator('access', 'refresh', FrozenClock::fromString('2024-01-01T12:00:00+00:00')->addSeconds(3600));

$response = $connector->getUser($accessToken);

Expand All @@ -265,7 +269,7 @@
$connector = new OAuth2Connector;
$connector->withMockClient($mockClient);

$accessToken = new AccessTokenAuthenticator('access', 'refresh', Date::now()->addSeconds(3600)->toDateTime());
$accessToken = new AccessTokenAuthenticator('access', 'refresh', FrozenClock::fromString('2024-01-01T12:00:00+00:00')->addSeconds(3600));

$response = $connector->getUser($accessToken, function (Request $request) {
$request->query()->add('yee', 'haw');
Expand Down Expand Up @@ -305,7 +309,8 @@
GetUserRequest::class => MockResponse::make(['user' => 'Sam']),
]);

$connector = new OAuth2Connector;
$frozenClock = FrozenClock::fromString('2024-01-01T12:00:00+00:00');
$connector = new OAuth2Connector($frozenClock);
$requests = [];

$connector->oauthConfig()->setRequestModifier(function (Request $request) use (&$requests) {
Expand All @@ -326,6 +331,7 @@
expect($authenticator->getAccessToken())->toEqual('access');
expect($authenticator->getRefreshToken())->toEqual('refresh');
expect($authenticator->getExpiresAt())->toBeInstanceOf(DateTimeImmutable::class);
expect($authenticator->getExpiresAt()->getTimestamp() - $frozenClock->now()->getTimestamp())->toEqual(3600);
expect($mockClient->getLastPendingRequest()->query()->all())->toEqual(['request' => 'access']);

$newAuthenticator = $connector->refreshAccessToken($authenticator);
Expand All @@ -334,6 +340,7 @@
expect($newAuthenticator->getAccessToken())->toEqual('access-new');
expect($newAuthenticator->getRefreshToken())->toEqual('refresh-new');
expect($newAuthenticator->getExpiresAt())->toBeInstanceOf(DateTimeImmutable::class);
expect($authenticator->getExpiresAt()->getTimestamp() - $frozenClock->now()->getTimestamp())->toEqual(3600);
expect($mockClient->getLastPendingRequest()->query()->all())->toEqual(['request' => 'refresh']);

$response = $connector->getUser($newAuthenticator);
Expand Down
10 changes: 8 additions & 2 deletions tests/Feature/Oauth2/ClientCredentialsFlowConnectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Saloon\Http\Response;
use Saloon\Http\Faking\MockClient;
use Saloon\Http\Faking\MockResponse;
use Saloon\Tests\Helpers\FrozenClock;
use Saloon\Http\Auth\AccessTokenAuthenticator;
use Saloon\Exceptions\OAuthConfigValidationException;
use Saloon\Tests\Fixtures\Connectors\ClientCredentialsConnector;
Expand All @@ -19,7 +20,9 @@
MockResponse::make(['access_token' => 'access', 'expires_in' => 3600], 200),
]);

$connector = new ClientCredentialsConnector;

$frozenClock = FrozenClock::fromString('2024-01-01T12:00:00+00:00');
$connector = new ClientCredentialsConnector($frozenClock);
$connector->withMockClient($mockClient);

$authenticator = $connector->getAccessToken();
Expand All @@ -29,6 +32,7 @@
expect($authenticator->getRefreshToken())->toBeNull();
expect($authenticator->isRefreshable())->toBeFalse();
expect($authenticator->getExpiresAt())->toBeInstanceOf(DateTimeImmutable::class);
expect($authenticator->getExpiresAt()->getTimestamp() - $frozenClock->now()->getTimestamp())->toEqual(3600);

$mockClient->assertSentCount(1);

Expand Down Expand Up @@ -203,7 +207,8 @@
MockResponse::make(['access_token' => 'access', 'expires_in' => 3600], 200),
]);

$connector = new ClientCredentialsBasicAuthConnector;
$frozenClock = FrozenClock::fromString('2024-01-01T12:00:00+00:00');
$connector = new ClientCredentialsBasicAuthConnector($frozenClock);
$connector->withMockClient($mockClient);

$authenticator = $connector->getAccessToken();
Expand All @@ -213,6 +218,7 @@
expect($authenticator->getRefreshToken())->toBeNull();
expect($authenticator->isRefreshable())->toBeFalse();
expect($authenticator->getExpiresAt())->toBeInstanceOf(DateTimeImmutable::class);
expect($authenticator->getExpiresAt()->getTimestamp() - $frozenClock->now()->getTimestamp())->toEqual(3600);

$mockClient->assertSentCount(1);

Expand Down
8 changes: 4 additions & 4 deletions tests/Fixtures/Authenticators/CustomOAuthAuthenticator.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ class CustomOAuthAuthenticator extends AccessTokenAuthenticator
* Constructor
*/
public function __construct(
readonly public string $accessToken,
readonly public string $greeting,
readonly public ?string $refreshToken = null,
readonly public ?DateTimeImmutable $expiresAt = null,
public readonly string $accessToken,
public readonly string $greeting,
public readonly ?string $refreshToken = null,
public readonly ?DateTimeImmutable $expiresAt = null,
) {
//
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,20 @@
namespace Saloon\Tests\Fixtures\Connectors;

use Saloon\Http\Connector;
use Psr\Clock\ClockInterface;
use Saloon\Tests\Helpers\FrozenClock;
use Saloon\Helpers\OAuth2\OAuthConfig;
use Saloon\Traits\OAuth2\ClientCredentialsBasicAuthGrant;

class ClientCredentialsBasicAuthConnector extends Connector
{
use ClientCredentialsBasicAuthGrant;

public function __construct(?ClockInterface $clock = null)
{
$this->clock = $clock ?? FrozenClock::fromString('2024-01-01T12:00:00+00:00');
}

/**
* Define the base URL.
*/
Expand Down
7 changes: 7 additions & 0 deletions tests/Fixtures/Connectors/ClientCredentialsConnector.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,20 @@
namespace Saloon\Tests\Fixtures\Connectors;

use Saloon\Http\Connector;
use Psr\Clock\ClockInterface;
use Saloon\Tests\Helpers\FrozenClock;
use Saloon\Helpers\OAuth2\OAuthConfig;
use Saloon\Traits\OAuth2\ClientCredentialsGrant;

class ClientCredentialsConnector extends Connector
{
use ClientCredentialsGrant;

public function __construct(?ClockInterface $clock = null)
{
$this->clock = $clock ?? FrozenClock::fromString('2024-01-01T12:00:00+00:00');
}

/**
* Define the base URL.
*/
Expand Down
7 changes: 7 additions & 0 deletions tests/Fixtures/Connectors/OAuth2Connector.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,20 @@
namespace Saloon\Tests\Fixtures\Connectors;

use Saloon\Http\Connector;
use Psr\Clock\ClockInterface;
use Saloon\Tests\Helpers\FrozenClock;
use Saloon\Helpers\OAuth2\OAuthConfig;
use Saloon\Traits\OAuth2\AuthorizationCodeGrant;

class OAuth2Connector extends Connector
{
use AuthorizationCodeGrant;

public function __construct(?ClockInterface $clock = null)
{
$this->clock = $clock ?? FrozenClock::fromString('2024-01-01T12:00:00+00:00');
}

/**
* Define the base URL.
*/
Expand Down
2 changes: 1 addition & 1 deletion tests/Fixtures/Requests/QueryParameterRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class QueryParameterRequest extends Request
/**
* Constructor
*/
public function __construct(readonly public string $endpoint = '/user')
public function __construct(public readonly string $endpoint = '/user')
{
//
}
Expand Down
Loading