| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Facile\OpenIDClient\Middleware; |
| 6 |
|
| 7 |
use Facile\OpenIDClient\Client\ClientInterface; |
| 8 |
use Facile\OpenIDClient\Exception\LogicException; |
| 9 |
use Facile\OpenIDClient\Service\AuthorizationService; |
| 10 |
use Facile\OpenIDClient\Session\AuthSessionInterface; |
| 11 |
use Facile\OpenIDClient\Token\TokenSetInterface; |
| 12 |
use Psr\Http\Message\ResponseInterface; |
| 13 |
use Psr\Http\Message\ServerRequestInterface; |
| 14 |
use Psr\Http\Server\MiddlewareInterface; |
| 15 |
use Psr\Http\Server\RequestHandlerInterface; |
| 16 |
use Override; |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
class CallbackMiddleware implements MiddlewareInterface |
| 22 |
{ |
| 23 |
private AuthorizationService $authorizationService; |
| 24 |
|
| 25 |
private ?string $redirectUri; |
| 26 |
|
| 27 |
private ?ClientInterface $client; |
| 28 |
|
| 29 |
private ?int $maxAge; |
| 30 |
|
| 31 |
public function __construct( |
| 32 |
AuthorizationService $authorizationService, |
| 33 |
?ClientInterface $client = null, |
| 34 |
?string $redirectUri = null, |
| 35 |
?int $maxAge = null |
| 36 |
) { |
| 37 |
$this->authorizationService = $authorizationService; |
| 38 |
$this->client = $client; |
| 39 |
$this->redirectUri = $redirectUri; |
| 40 |
$this->maxAge = $maxAge; |
| 41 |
} |
| 42 |
|
| 43 |
#[Override] |
| 44 |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
| 45 |
{ |
| 46 |
$client = $this->client ?? $request->getAttribute(ClientInterface::class); |
| 47 |
$authSession = $request->getAttribute(AuthSessionInterface::class); |
| 48 |
|
| 49 |
if (! $client instanceof ClientInterface) { |
| 50 |
throw new LogicException('No OpenID client provided'); |
| 51 |
} |
| 52 |
|
| 53 |
if (null !== $authSession && ! $authSession instanceof AuthSessionInterface) { |
| 54 |
throw new LogicException('Invalid auth session provided in attribute ' . AuthSessionInterface::class); |
| 55 |
} |
| 56 |
|
| 57 |
$params = $this->authorizationService->getCallbackParams($request, $client); |
| 58 |
$tokenSet = $this->authorizationService->callback( |
| 59 |
$client, |
| 60 |
$params, |
| 61 |
$this->redirectUri, |
| 62 |
$authSession, |
| 63 |
$this->maxAge |
| 64 |
); |
| 65 |
|
| 66 |
return $handler->handle($request->withAttribute(TokenSetInterface::class, $tokenSet)); |
| 67 |
} |
| 68 |
} |