| 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\Exception\RuntimeException; |
| 10 |
use Facile\OpenIDClient\Service\UserInfoService; |
| 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 |
final class UserInfoMiddleware implements MiddlewareInterface |
| 22 |
{ |
| 23 |
public const USERINFO_ATTRIBUTE = self::class; |
| 24 |
|
| 25 |
private UserInfoService $userInfoService; |
| 26 |
|
| 27 |
private ?ClientInterface $client; |
| 28 |
|
| 29 |
public function __construct( |
| 30 |
UserInfoService $userInfoService, |
| 31 |
?ClientInterface $client = null |
| 32 |
) { |
| 33 |
$this->userInfoService = $userInfoService; |
| 34 |
$this->client = $client; |
| 35 |
} |
| 36 |
|
| 37 |
#[Override] |
| 38 |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
| 39 |
{ |
| 40 |
$tokenSet = $request->getAttribute(TokenSetInterface::class); |
| 41 |
$client = $this->client ?? $request->getAttribute(ClientInterface::class); |
| 42 |
|
| 43 |
if (! $client instanceof ClientInterface) { |
| 44 |
throw new LogicException('No OpenID client provided'); |
| 45 |
} |
| 46 |
|
| 47 |
if (! $tokenSet instanceof TokenSetInterface) { |
| 48 |
throw new RuntimeException('Unable to get token response attribute'); |
| 49 |
} |
| 50 |
|
| 51 |
$claims = $this->userInfoService->getUserInfo($client, $tokenSet); |
| 52 |
|
| 53 |
return $handler->handle($request->withAttribute(self::USERINFO_ATTRIBUTE, $claims)); |
| 54 |
} |
| 55 |
} |