File size: 6,270 Bytes
cf14c12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | <?php
declare(strict_types=1);
namespace User\Infrastructure\SSO;
use Easy\Container\Attributes\Inject;
use Easy\Http\Message\RequestMethod;
use Easy\Http\Message\StatusCode;
use InvalidArgumentException;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Http\Message\UriInterface;
use RuntimeException;
use Shared\Infrastructure\CommandBus\Dispatcher;
use Shared\Infrastructure\CommandBus\Exception\NoHandlerFoundException;
use User\Application\Commands\CreateUserCommand;
use User\Application\Commands\ReadUserCommand;
use User\Domain\Entities\UserEntity;
use User\Domain\Exceptions\UserNotFoundException;
use User\Domain\ValueObjects\Email;
use User\Infrastructure\SSO\Exceptions\InvalidCodeException;
class IdentityProviderHelper
{
public function __construct(
private Dispatcher $dispatcher,
private ClientInterface $client,
private UriFactoryInterface $uriFactory,
private RequestFactoryInterface $factory,
#[Inject('option.site.domain')]
private string $domain = 'localhost',
#[Inject('option.site.is_secure')]
private bool $isSecure = true,
) {
}
/**
* Generates the authentication URL for the specified identity provider.
*
* @param string $provider The identity provider name.
* @param string $authUrl The authentication URL.
* @param string $clientId The client ID.
* @param string $scope The requested scope.
* @return UriInterface The generated authentication URL.
* @throws InvalidArgumentException If the input parameters are invalid.
*/
public function generateAuthUrl(
string $provider,
string $authUrl,
string $clientId,
string $scope,
): UriInterface {
$uri = $this->uriFactory->createUri($authUrl);
$query = http_build_query([
'client_id' => $clientId,
'redirect_uri' => $this->generateRedirectUri($provider),
'response_type' => 'code',
'scope' => $scope,
]);
return $uri->withQuery($query);
}
/**
* Exchanges the authorization code for an access token from the identity
* provider.
*
* @param string $provider The name of the identity provider.
* @param string $tokenUrl The URL to exchange the code for an access token.
* @param string $clientId The client ID for the application.
* @param string $clientSecret The client secret for the application.
* @param string $code The authorization code received from the identity
* provider.
* @param RequestMethod $method The HTTP request method to use for the token
* exchange (default: POST).
* @return string The access token obtained from the identity provider.
* @throws InvalidArgumentException If the input parameters are invalid.
* @throws ClientExceptionInterface If there is an error sending the HTTP
* request.
* @throws InvalidCodeException If the authorization code is invalid.
* @throws RuntimeException If there is an error during the token exchange
* process.
*/
public function exchangeCode(
string $provider,
string $tokenUrl,
string $clientId,
string $clientSecret,
string $code,
RequestMethod $method = RequestMethod::POST,
): string {
$req = $this->factory->createRequest(
$method->value,
$tokenUrl
);
$uri = $req->getUri()->withQuery(http_build_query([
'client_id' => $clientId,
'client_secret' => $clientSecret,
'code' => $code,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->generateRedirectUri($provider),
]));
$req = $req->withUri($uri);
$res = $this->client->sendRequest(
$req->withHeader('Accept', 'application/json')
);
if ($res->getStatusCode() !== StatusCode::OK->value) {
throw new InvalidCodeException($code);
}
$data = json_decode($res->getBody()->getContents());
if (!isset($data->access_token)) {
throw new InvalidCodeException($code);
}
return $data->access_token;
}
/**
* Find or create a user based on the provided email, first name, and last
* name.
*
* @param string $email The email of the user.
* @param string $firstName The first name of the user.
* @param string $lastName The last name of the user.
* @param array $params Additional parameters for the command.
* @return UserEntity The found or created user entity.
* @throws NoHandlerFoundException If no handler is found for the command.
*/
public function findOrCreateUser(
string $email,
string $firstName,
string $lastName,
array $params = []
): UserEntity {
try {
$cmd = new ReadUserCommand(new Email($email));
$user = $this->dispatcher->dispatch($cmd);
return $user;
} catch (UserNotFoundException) {
// Do nothing here, we'll create a new user
}
$cmd = new CreateUserCommand(
$email,
$firstName,
$lastName
);
if (isset($params['ip']) && is_string($params['ip'])) {
$cmd->setIp($params['ip']);
}
if (isset($params['country_code']) && is_string($params['country_code'])) {
$cmd->setCountryCode($params['country_code']);
}
if (isset($params['city_name']) && is_string($params['city_name'])) {
$cmd->setCityName($params['city_name']);
}
return $this->dispatcher->dispatch($cmd);
}
/**
* Generates the redirect URI for the specified identity provider.
*
* @param string $provider The identity provider.
* @return string The generated redirect URI.
*/
private function generateRedirectUri(string $provider): string
{
return ($this->isSecure ? 'https' : 'http')
. '://' . $this->domain
. '/auth/' . $provider;
}
}
|