Merge branch 'feat/gandi-provider'

This commit is contained in:
Maël Gangloff 2024-08-07 01:15:14 +02:00
commit 6060a55b29
No known key found for this signature in database
GPG Key ID: 11FDC81C24A7F629
10 changed files with 260 additions and 47 deletions

View File

@ -90,11 +90,35 @@ export function ConnectorForm({form, onCreate}: { form: FormInstance, onCreate:
>
<Select options={ovhPricingMode} optionFilterProp="label"/>
</Form.Item>
</>
}
{
provider === ConnectorProvider.GANDI && <>
<Form.Item
label={t`Personal Access Token (PAT)`}
name={['authData', 'token']}
rules={[{required: true, message: t`Required`}]}>
<Input autoComplete='off'/>
</Form.Item>
<Form.Item
label={t`Organization sharing ID`}
name={['authData', 'sharingId']}
help={<Typography.Text
type='secondary'>{t`It indicates the organization that will pay for the ordered product`}</Typography.Text>}
required={false}>
<Input autoComplete='off' placeholder='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'/>
</Form.Item>
</>
}
{
provider !== undefined && <>
<Form.Item
valuePropName="checked"
label={t`API Terms of Service`}
name={['authData', 'acceptConditions']}
rules={[{required: true, message: t`Required`}]}
style={{marginTop: '3em'}}
>
<Checkbox
required={true}>
@ -124,7 +148,6 @@ export function ConnectorForm({form, onCreate}: { form: FormInstance, onCreate:
</>
}
<Form.Item style={{marginTop: 10}}>
<Space>
<Button type="primary" htmlType="submit">

View File

@ -1,7 +1,8 @@
import {request} from "./index";
export enum ConnectorProvider {
OVH = 'ovh'
OVH = 'ovh',
GANDI = 'gandi'
}
export type Connector = {

View File

@ -10,8 +10,14 @@ export const helpGetTokenLink = (provider?: string) => {
href="https://api.ovh.com/createToken/index.cgi?GET=/order/cart&GET=/order/cart/*&POST=/order/cart&POST=/order/cart/*&DELETE=/order/cart/*">
{t`Retrieve a set of tokens from your customer account on the Provider's website`}
</Typography.Link>
case ConnectorProvider.GANDI:
return <Typography.Link target='_blank' href="https://admin.gandi.net/organizations/account/pat">
{t`Retrieve a Personal Access Token from your customer account on the Provider's website`}
</Typography.Link>
default:
return <></>
}
}
@ -19,6 +25,8 @@ export const tosHyperlink = (provider?: string) => {
switch (provider) {
case ConnectorProvider.OVH:
return 'https://www.ovhcloud.com/fr/terms-and-conditions/contracts/'
case ConnectorProvider.GANDI:
return 'https://www.gandi.net/en/contracts/terms-of-service'
default:
return ''
}

View File

@ -3,10 +3,13 @@
namespace App\Config\Connector;
use App\Entity\Domain;
use Symfony\Contracts\HttpClient\HttpClientInterface;
interface ConnectorInterface
{
public static function verifyAuthData(array $authData): array;
public function __construct(array $authData, HttpClientInterface $client);
public function orderDomain(Domain $domain, bool $dryRun): void;
public static function verifyAuthData(array $authData, HttpClientInterface $client);
}

View File

@ -0,0 +1,133 @@
<?php
namespace App\Config\Connector;
use App\Entity\Domain;
use http\Exception\InvalidArgumentException;
use Symfony\Component\HttpClient\HttpOptions;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
readonly class GandiConnector implements ConnectorInterface
{
private const BASE_URL = 'https://api.gandi.net/v5';
public function __construct(private array $authData, private HttpClientInterface $client)
{
}
/**
* Order a domain name with the Gandi API.
*
* @throws \Exception
* @throws TransportExceptionInterface
* @throws DecodingExceptionInterface
*/
public function orderDomain(Domain $domain, bool $dryRun = false): void
{
if (!$domain->getDeleted()) {
throw new InvalidArgumentException('The domain name still appears in the WHOIS database');
}
$ldhName = $domain->getLdhName();
if (!$ldhName) {
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'])
->setHeader('Accept', 'application/json')
->setBaseUri(self::BASE_URL)
->toArray()
)->toArray();
$httpOptions = (new HttpOptions())
->setAuthBearer($authData['token'])
->setHeader('Accept', 'application/json')
->setBaseUri(self::BASE_URL)
->setHeader('Dry-Run', $dryRun ? '1' : '0')
->setJson([
'fqdn' => $ldhName,
'owner' => [
'email' => $user['email'],
'given' => $user['firstname'],
'family' => $user['lastname'],
'streetaddr' => $user['streetaddr'],
'zip' => $user['zip'],
'city' => $user['city'],
'state' => $user['state'],
'phone' => $user['phone'],
'country' => $user['country'],
'type' => 'individual',
],
'tld_period' => 'golive',
]);
if (array_key_exists('sharingId', $authData)) {
$httpOptions->setQuery([
'sharing_id' => $authData['sharingId'],
]);
}
$res = $this->client->request('POST', '/domain/domains', $httpOptions->toArray());
if ((!$dryRun && Response::HTTP_ACCEPTED !== $res->getStatusCode())
|| ($dryRun && Response::HTTP_OK !== $res->getStatusCode())) {
throw new \Exception($res->toArray()['message']);
}
}
/**
* @throws TransportExceptionInterface
*/
public static function verifyAuthData(array $authData, HttpClientInterface $client): array
{
$token = $authData['token'];
$acceptConditions = $authData['acceptConditions'];
$ownerLegalAge = $authData['ownerLegalAge'];
$waiveRetractationPeriod = $authData['waiveRetractationPeriod'];
if (!is_string($token) || empty($token)
|| (array_key_exists('sharingId', $authData) && !is_string($authData['sharingId']))
) {
throw new BadRequestHttpException('Bad authData schema');
}
if (true !== $acceptConditions
|| true !== $ownerLegalAge
|| true !== $waiveRetractationPeriod) {
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,
'ownerLegalAge' => $ownerLegalAge,
'waiveRetractationPeriod' => $waiveRetractationPeriod,
];
if (array_key_exists('sharingId', $authData)) {
$authDataReturned['sharingId'] = $authData['sharingId'];
}
return $authDataReturned;
}
}

View File

@ -5,6 +5,8 @@ namespace App\Config\Connector;
use App\Entity\Domain;
use Ovh\Api;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Contracts\HttpClient\HttpClientInterface;
readonly class OvhConnector implements ConnectorInterface
{
@ -30,7 +32,7 @@ readonly class OvhConnector implements ConnectorInterface
],
];
public function __construct(private array $authData)
public function __construct(private array $authData, private HttpClientInterface $client)
{
}
@ -39,8 +41,8 @@ readonly class OvhConnector implements ConnectorInterface
*
* @throws \Exception
*/
public function orderDomain(Domain $domain, bool $dryRun = false
): void {
public function orderDomain(Domain $domain, bool $dryRun = false): void
{
if (!$domain->getDeleted()) {
throw new \Exception('The domain name still appears in the WHOIS database');
}
@ -50,7 +52,7 @@ readonly class OvhConnector implements ConnectorInterface
throw new \Exception('Domain name cannot be null');
}
$authData = self::verifyAuthData($this->authData);
$authData = self::verifyAuthData($this->authData, $this->client);
$acceptConditions = $authData['acceptConditions'];
$ownerLegalAge = $authData['ownerLegalAge'];
@ -118,7 +120,7 @@ readonly class OvhConnector implements ConnectorInterface
/**
* @throws \Exception
*/
public static function verifyAuthData(array $authData): array
public static function verifyAuthData(array $authData, HttpClientInterface $client): array
{
$appKey = $authData['appKey'];
$appSecret = $authData['appSecret'];
@ -137,14 +139,16 @@ readonly class OvhConnector implements ConnectorInterface
|| !is_string($apiEndpoint) || empty($apiEndpoint)
|| !is_string($ovhSubsidiary) || empty($ovhSubsidiary)
|| !is_string($pricingMode) || empty($pricingMode)
|| true !== $acceptConditions
|| true !== $ownerLegalAge
|| true !== $waiveRetractationPeriod
) {
throw new BadRequestHttpException('Bad authData schema');
}
if (true !== $acceptConditions
|| true !== $ownerLegalAge
|| true !== $waiveRetractationPeriod) {
throw new HttpException(451, 'The user has not given explicit consent');
}
$conn = new Api(
$appKey,
$appSecret,

View File

@ -2,7 +2,19 @@
namespace App\Config;
use App\Config\Connector\GandiConnector;
use App\Config\Connector\OvhConnector;
enum ConnectorProvider: string
{
case OVH = 'ovh';
case GANDI = 'gandi';
public function getConnectorProvider(): string
{
return match ($this) {
ConnectorProvider::OVH => OvhConnector::class,
ConnectorProvider::GANDI => GandiConnector::class
};
}
}

View File

@ -2,8 +2,7 @@
namespace App\Controller;
use App\Config\Connector\OvhConnector;
use App\Config\ConnectorProvider;
use App\Config\Connector\ConnectorInterface;
use App\Entity\Connector;
use App\Entity\User;
use Doctrine\Common\Collections\Collection;
@ -11,9 +10,10 @@ use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class ConnectorController extends AbstractController
{
@ -43,6 +43,7 @@ class ConnectorController extends AbstractController
/**
* @throws \Exception
* @throws TransportExceptionInterface
*/
#[Route(
path: '/api/connectors',
@ -53,7 +54,7 @@ class ConnectorController extends AbstractController
],
methods: ['POST']
)]
public function createConnector(Request $request): Connector
public function createConnector(Request $request, HttpClientInterface $client): Connector
{
$connector = $this->serializer->deserialize($request->getContent(), Connector::class, 'json', ['groups' => 'connector:create']);
/** @var User $user */
@ -67,17 +68,21 @@ class ConnectorController extends AbstractController
'provider' => $provider->value,
]);
if (ConnectorProvider::OVH === $provider) {
$authData = OvhConnector::verifyAuthData($connector->getAuthData());
$connector->setAuthData($authData);
$this->logger->info('User {username} authentication data with the OVH provider has been validated.', [
'username' => $user->getUserIdentifier(),
]);
} else {
throw new BadRequestHttpException('Unknown provider');
if (null === $provider) {
throw new \Exception('Provider not found');
}
/** @var ConnectorInterface $connectorProviderClass */
$connectorProviderClass = $provider->getConnectorProvider();
$authData = $connectorProviderClass::verifyAuthData($connector->getAuthData(), $client);
$connector->setAuthData($authData);
$this->logger->info('User {username} authentication data with the {provider} provider has been validated.', [
'username' => $user->getUserIdentifier(),
'provider' => $provider->value,
]);
$this->logger->info('The new API connector requested by {username} has been successfully registered.', [
'username' => $user->getUserIdentifier(),
]);

View File

@ -2,8 +2,7 @@
namespace App\MessageHandler;
use App\Config\Connector\OvhConnector;
use App\Config\ConnectorProvider;
use App\Config\Connector\ConnectorInterface;
use App\Config\TriggerAction;
use App\Entity\Connector;
use App\Entity\Domain;
@ -22,6 +21,7 @@ use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Symfony\Contracts\HttpClient\HttpClientInterface;
#[AsMessageHandler]
final readonly class ProcessDomainTriggerHandler
@ -33,7 +33,8 @@ final readonly class ProcessDomainTriggerHandler
private WatchListRepository $watchListRepository,
private DomainRepository $domainRepository,
private KernelInterface $kernel,
private LoggerInterface $logger
private LoggerInterface $logger,
private HttpClientInterface $client
) {
}
@ -57,15 +58,19 @@ final readonly class ProcessDomainTriggerHandler
'provider' => $connector->getProvider()->value,
]);
try {
if (ConnectorProvider::OVH === $connector->getProvider()) {
$ovh = new OvhConnector($connector->getAuthData());
$isDebug = $this->kernel->isDebug();
$ovh->orderDomain($domain, $isDebug);
$this->sendEmailDomainOrdered($domain, $connector, $watchList->getUser());
} else {
throw new \Exception('Unknown provider');
$provider = $connector->getProvider();
if (null === $provider) {
throw new \Exception('Provider not found');
}
$connectorProviderClass = $provider->getConnectorProvider();
/** @var ConnectorInterface $connectorProvider */
$connectorProvider = new $connectorProviderClass($connector->getAuthData(), $this->client);
$connectorProvider->orderDomain($domain, $this->kernel->isDebug());
$this->sendEmailDomainOrdered($domain, $connector, $watchList->getUser());
} catch (\Throwable) {
$this->logger->warning('Unable to complete purchase. An error message is sent to user {username}.', [
'username' => $watchList->getUser()->getUserIdentifier(),

View File

@ -23,9 +23,10 @@ msgstr ""
#: assets/components/tracking/ConnectorForm.tsx:74
#: assets/components/tracking/ConnectorForm.tsx:81
#: assets/components/tracking/ConnectorForm.tsx:89
#: assets/components/tracking/ConnectorForm.tsx:97
#: assets/components/tracking/ConnectorForm.tsx:110
#: assets/components/tracking/ConnectorForm.tsx:119
#: assets/components/tracking/ConnectorForm.tsx:100
#: assets/components/tracking/ConnectorForm.tsx:120
#: assets/components/tracking/ConnectorForm.tsx:134
#: assets/components/tracking/ConnectorForm.tsx:143
#: assets/components/tracking/WatchlistForm.tsx:103
msgid "Required"
msgstr ""
@ -185,12 +186,12 @@ msgid ""
"that may be available soon."
msgstr ""
#: assets/components/tracking/ConnectorForm.tsx:131
#: assets/components/tracking/ConnectorForm.tsx:154
#: assets/components/tracking/WatchlistForm.tsx:186
msgid "Create"
msgstr ""
#: assets/components/tracking/ConnectorForm.tsx:134
#: assets/components/tracking/ConnectorForm.tsx:157
#: assets/components/tracking/WatchlistForm.tsx:189
msgid "Reset"
msgstr ""
@ -215,31 +216,43 @@ msgstr ""
msgid "OVH pricing mode"
msgstr ""
#: assets/components/tracking/ConnectorForm.tsx:95
#: assets/components/tracking/ConnectorForm.tsx:98
msgid "Personal Access Token (PAT)"
msgstr ""
#: assets/components/tracking/ConnectorForm.tsx:104
msgid "Organization sharing ID"
msgstr ""
#: assets/components/tracking/ConnectorForm.tsx:107
msgid "It indicates the organization that will pay for the ordered product"
msgstr ""
#: assets/components/tracking/ConnectorForm.tsx:118
msgid "API Terms of Service"
msgstr ""
#: assets/components/tracking/ConnectorForm.tsx:102
#: assets/components/tracking/ConnectorForm.tsx:126
msgid ""
"I certify that I have read and accepted the conditions of use of the "
"Provider API, accessible from this hyperlink"
msgstr ""
#: assets/components/tracking/ConnectorForm.tsx:108
#: assets/components/tracking/ConnectorForm.tsx:132
msgid "Legal age"
msgstr ""
#: assets/components/tracking/ConnectorForm.tsx:113
#: assets/components/tracking/ConnectorForm.tsx:137
msgid ""
"I certify on my honor that I am of the minimum age required to consent to "
"these conditions"
msgstr ""
#: assets/components/tracking/ConnectorForm.tsx:117
#: assets/components/tracking/ConnectorForm.tsx:141
msgid "Withdrawal period"
msgstr ""
#: assets/components/tracking/ConnectorForm.tsx:122
#: assets/components/tracking/ConnectorForm.tsx:146
msgid ""
"I expressly waive my right of withdrawal regarding the purchase of domain "
"names via the Provider's API"
@ -509,6 +522,12 @@ msgid ""
"website"
msgstr ""
#: assets/utils/providers/index.tsx:16
msgid ""
"Retrieve a Personal Access Token from your customer account on the "
"Provider's website"
msgstr ""
#: assets/utils/providers/ovh.tsx:5
msgid "Application key"
msgstr ""