Skip to content

Commit

Permalink
refactor: provider authentication flow
Browse files Browse the repository at this point in the history
  • Loading branch information
vinceh121 committed Sep 30, 2024
1 parent b162f23 commit 81512be
Show file tree
Hide file tree
Showing 7 changed files with 98 additions and 78 deletions.
4 changes: 2 additions & 2 deletions src/Config/ConnectorProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace App\Config;

use App\Service\Connector\GandiProvider;
use App\Service\Connector\NamecheapConnector;
use App\Service\Connector\NamecheapProvider;
use App\Service\Connector\OvhProvider;

enum ConnectorProvider: string
Expand All @@ -17,7 +17,7 @@ public function getConnectorProvider(): string
return match ($this) {
ConnectorProvider::OVH => OvhProvider::class,
ConnectorProvider::GANDI => GandiProvider::class,
ConnectorProvider::NAMECHEAP => NamecheapConnector::class,
ConnectorProvider::NAMECHEAP => NamecheapProvider::class,
};
}
}
13 changes: 8 additions & 5 deletions src/Controller/ConnectorController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Attribute\Route;
Expand All @@ -20,7 +22,9 @@ class ConnectorController extends AbstractController
public function __construct(
private readonly SerializerInterface $serializer,
private readonly EntityManagerInterface $em,
private readonly LoggerInterface $logger
private readonly LoggerInterface $logger,
#[Autowire(service: 'service_container')]
private ContainerInterface $locator
) {
}

Expand Down Expand Up @@ -71,10 +75,9 @@ public function createConnector(Request $request, HttpClientInterface $client):
throw new BadRequestHttpException('Provider not found');
}

/** @var AbstractProvider $connectorProviderClass */
$connectorProviderClass = $provider->getConnectorProvider();

$authData = $connectorProviderClass::verifyAuthData($connector->getAuthData(), $client);
/** @var AbstractProvider $providerClient */
$providerClient = $this->locator->get($provider->getConnectorProvider());
$authData = $providerClient->verifyAuthData($connector->getAuthData());
$connector->setAuthData($authData);

$this->logger->info('User {username} authentication data with the {provider} provider has been validated.', [
Expand Down
3 changes: 0 additions & 3 deletions src/Controller/WatchListController.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class WatchListController extends AbstractController
{
Expand All @@ -50,7 +49,6 @@ public function __construct(
private readonly EntityManagerInterface $em,
private readonly WatchListRepository $watchListRepository,
private readonly LoggerInterface $logger,
private readonly HttpClientInterface $httpClient,
private readonly ChatNotificationService $chatNotificationService,
#[Autowire(service: 'service_container')]
private ContainerInterface $locator
Expand Down Expand Up @@ -184,7 +182,6 @@ private function verifyConnector(WatchList $watchList, ?Connector $connector): v
/** @var AbstractProvider $connectorProvider */
$connectorProvider = $this->locator->get($connectorProviderClass);

$connectorProvider::verifyAuthData($connector->getAuthData(), $this->httpClient); // We want to check if the tokens are OK
$connectorProvider->authenticate($connector->getAuthData());
$supported = $connectorProvider->isSupported(...$watchList->getDomains()->toArray());

Expand Down
26 changes: 23 additions & 3 deletions src/Service/Connector/AbstractProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,14 @@
use App\Entity\Domain;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
* The typical flow of a provider will go as follows:
*
* MyProvider $provider; // gotten from DI
* $provider->authenticate($authData);
* $provider->orderDomain($domain, $dryRun);
*/
abstract class AbstractProvider
{
protected array $authData;
Expand All @@ -16,7 +22,17 @@ public function __construct(
) {
}

abstract public static function verifyAuthData(array $authData, HttpClientInterface $client): array;
/**
* @param array $authData raw authentication data as supplied by the user
*
* @return array a cleaned up version of the authentication data
*/
abstract public function verifyAuthData(array $authData): array;

/**
* @throws \Exception when the registrar denies the authentication
*/
abstract public function assertAuthentication(): void; // TODO use dedicated exception type

abstract public function orderDomain(Domain $domain, bool $dryRun): void;

Expand Down Expand Up @@ -53,9 +69,13 @@ public function isSupported(Domain ...$domainList): bool
return true;
}

/**
* @throws \Exception
*/
public function authenticate(array $authData): void
{
$this->authData = $authData;
$this->authData = $this->verifyAuthData($authData);
$this->assertAuthentication();
}

abstract protected function getCachedTldList(): CacheItemInterface;
Expand Down
41 changes: 20 additions & 21 deletions src/Service/Connector/GandiProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,17 +43,15 @@ public function orderDomain(Domain $domain, bool $dryRun = false): void
throw new \InvalidArgumentException('Domain name cannot be null');
}

$authData = self::verifyAuthData($this->authData, $this->client);

$user = $this->client->request('GET', '/v5/organization/user-info', (new HttpOptions())
->setAuthBearer($authData['token'])
->setAuthBearer($this->authData['token'])
->setHeader('Accept', 'application/json')
->setBaseUri(self::BASE_URL)
->toArray()
)->toArray();

$httpOptions = (new HttpOptions())
->setAuthBearer($authData['token'])
->setAuthBearer($this->authData['token'])
->setHeader('Accept', 'application/json')
->setBaseUri(self::BASE_URL)
->setHeader('Dry-Run', $dryRun ? '1' : '0')
Expand All @@ -74,9 +72,9 @@ public function orderDomain(Domain $domain, bool $dryRun = false): void
'tld_period' => 'golive',
]);

if (array_key_exists('sharingId', $authData)) {
if (array_key_exists('sharingId', $this->authData)) {
$httpOptions->setQuery([
'sharing_id' => $authData['sharingId'],
'sharing_id' => $this->authData['sharingId'],
]);
}

Expand All @@ -91,7 +89,7 @@ public function orderDomain(Domain $domain, bool $dryRun = false): void
/**
* @throws TransportExceptionInterface
*/
public static function verifyAuthData(array $authData, HttpClientInterface $client): array
public function verifyAuthData(array $authData): array
{
$token = $authData['token'];

Expand All @@ -111,17 +109,6 @@ public static function verifyAuthData(array $authData, HttpClientInterface $clie
throw new HttpException(451, 'The user has not given explicit consent');
}

$response = $client->request('GET', '/v5/organization/user-info', (new HttpOptions())
->setAuthBearer($token)
->setHeader('Accept', 'application/json')
->setBaseUri(self::BASE_URL)
->toArray()
);

if (Response::HTTP_OK !== $response->getStatusCode()) {
throw new BadRequestHttpException('The status of these credentials is not valid');
}

$authDataReturned = [
'token' => $token,
'acceptConditions' => $acceptConditions,
Expand All @@ -136,6 +123,20 @@ public static function verifyAuthData(array $authData, HttpClientInterface $clie
return $authDataReturned;
}

public function assertAuthentication(): void
{
$response = $this->client->request('GET', '/v5/organization/user-info', (new HttpOptions())
->setAuthBearer($this->authData['token'])
->setHeader('Accept', 'application/json')
->setBaseUri(self::BASE_URL)
->toArray()
);

if (Response::HTTP_OK !== $response->getStatusCode()) {
throw new BadRequestHttpException('The status of these credentials is not valid');
}
}

/**
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
Expand All @@ -145,10 +146,8 @@ public static function verifyAuthData(array $authData, HttpClientInterface $clie
*/
protected function getSupportedTldList(): array
{
$authData = self::verifyAuthData($this->authData, $this->client);

$response = $this->client->request('GET', '/v5/domain/tlds', (new HttpOptions())
->setAuthBearer($authData['token'])
->setAuthBearer($this->authData['token'])
->setHeader('Accept', 'application/json')
->setBaseUri(self::BASE_URL)
->toArray())->toArray();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
use Symfony\Contracts\HttpClient\HttpClientInterface;

#[Autoconfigure(public: true)]
class NamecheapConnector extends AbstractProvider
class NamecheapProvider extends AbstractProvider
{
public const BASE_URL = 'https://api.namecheap.com/xml.response';

Expand Down Expand Up @@ -81,20 +81,21 @@ private function call(string $command, array $parameters = [], bool $dryRun = tr
return $data->CommandResponse;
}

public static function verifyAuthData(array $authData, HttpClientInterface $client): array
public function verifyAuthData(array $authData): array
{
// TODO call gettldlist to introspect authentication
// need to make verifyAuthData local to do this properly...

return [
'ApiUser' => $authData['ApiUser'],
'ApiKey' => $authData['ApiKey'],
'acceptConditions' => $authData['acceptConditions'],
'ownerLegalAge' => $authData['ownerLegalAge'],
'waiveRetractionPeriod' => $authData['waiveRetractionPeriod'],
];
}

public function assertAuthentication(): void
{
$this->call('namecheap.domains.gettldlist', [], false);
}

protected function getCachedTldList(): CacheItemInterface
{
return $this->cacheItemPool->getItem('app.provider.namecheap.supported-tld');
Expand Down
76 changes: 38 additions & 38 deletions src/Service/Connector/OvhProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
use Ovh\Api;
use Ovh\Exceptions\InvalidParameterException;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class OvhProvider extends AbstractProvider
{
Expand Down Expand Up @@ -41,8 +41,9 @@ class OvhProvider extends AbstractProvider
],
];

public function __construct(private HttpClientInterface $client)
public function __construct(CacheItemPoolInterface $cacheItemPool)
{
parent::__construct($cacheItemPool);
}

/**
Expand All @@ -61,21 +62,19 @@ public function orderDomain(Domain $domain, bool $dryRun = false): void
throw new \InvalidArgumentException('Domain name cannot be null');
}

$authData = self::verifyAuthData($this->authData, $this->client);

$acceptConditions = $authData['acceptConditions'];
$ownerLegalAge = $authData['ownerLegalAge'];
$waiveRetractationPeriod = $authData['waiveRetractationPeriod'];
$acceptConditions = $this->authData['acceptConditions'];
$ownerLegalAge = $this->authData['ownerLegalAge'];
$waiveRetractationPeriod = $this->authData['waiveRetractationPeriod'];

$conn = new Api(
$authData['appKey'],
$authData['appSecret'],
$authData['apiEndpoint'],
$authData['consumerKey']
$this->authData['appKey'],
$this->authData['appSecret'],
$this->authData['apiEndpoint'],
$this->authData['consumerKey']
);

$cart = $conn->post('/order/cart', [
'ovhSubsidiary' => $authData['ovhSubsidiary'],
'ovhSubsidiary' => $this->authData['ovhSubsidiary'],
'description' => 'Domain Watchdog',
]);
$cartId = $cart['cartId'];
Expand All @@ -85,8 +84,8 @@ public function orderDomain(Domain $domain, bool $dryRun = false): void
]);

$pricingModes = ['create-default'];
if ('create-default' !== $authData['pricingMode']) {
$pricingModes[] = $authData['pricingMode'];
if ('create-default' !== $this->authData['pricingMode']) {
$pricingModes[] = $this->authData['pricingMode'];
}

$offer = array_filter($offers, fn ($offer) => 'create' === $offer['action']
Expand Down Expand Up @@ -135,7 +134,7 @@ public function orderDomain(Domain $domain, bool $dryRun = false): void
/**
* @throws \Exception
*/
public static function verifyAuthData(array $authData, HttpClientInterface $client): array
public function verifyAuthData(array $authData): array
{
$appKey = $authData['appKey'];
$appSecret = $authData['appSecret'];
Expand Down Expand Up @@ -164,11 +163,26 @@ public static function verifyAuthData(array $authData, HttpClientInterface $clie
throw new HttpException(451, 'The user has not given explicit consent');
}

return [
'appKey' => $appKey,
'appSecret' => $appSecret,
'apiEndpoint' => $apiEndpoint,
'consumerKey' => $consumerKey,
'ovhSubsidiary' => $ovhSubsidiary,
'pricingMode' => $pricingMode,
'acceptConditions' => $acceptConditions,
'ownerLegalAge' => $ownerLegalAge,
'waiveRetractationPeriod' => $waiveRetractationPeriod,
];
}

public function assertAuthentication(): void
{
$conn = new Api(
$appKey,
$appSecret,
$apiEndpoint,
$consumerKey
$this->authData['appKey'],
$this->authData['appSecret'],
$this->authData['apiEndpoint'],
$this->authData['consumerKey'],
);

try {
Expand Down Expand Up @@ -201,18 +215,6 @@ public static function verifyAuthData(array $authData, HttpClientInterface $clie
throw new BadRequestHttpException('This Connector does not have enough permissions on the Provider API. Please recreate this Connector.');
}
}

return [
'appKey' => $appKey,
'appSecret' => $appSecret,
'apiEndpoint' => $apiEndpoint,
'consumerKey' => $consumerKey,
'ovhSubsidiary' => $ovhSubsidiary,
'pricingMode' => $pricingMode,
'acceptConditions' => $acceptConditions,
'ownerLegalAge' => $ownerLegalAge,
'waiveRetractationPeriod' => $waiveRetractationPeriod,
];
}

/**
Expand All @@ -222,17 +224,15 @@ public static function verifyAuthData(array $authData, HttpClientInterface $clie
*/
protected function getSupportedTldList(): array
{
$authData = self::verifyAuthData($this->authData, $this->client);

$conn = new Api(
$authData['appKey'],
$authData['appSecret'],
$authData['apiEndpoint'],
$authData['consumerKey']
$this->authData['appKey'],
$this->authData['appSecret'],
$this->authData['apiEndpoint'],
$this->authData['consumerKey']
);

return $conn->get('/domain/extensions', [
'ovhSubsidiary' => $authData['ovhSubsidiary'],
'ovhSubsidiary' => $this->authData['ovhSubsidiary'],
]);
}

Expand Down

0 comments on commit 81512be

Please sign in to comment.