|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace OAuthServer\Middleware; |
| 4 | + |
| 5 | +use Psr\Http\Message\ResponseInterface; |
| 6 | +use League\OAuth2\Server\ResourceServer; |
| 7 | +use Psr\Http\Server\MiddlewareInterface; |
| 8 | +use OAuthServer\Middleware\ValidateScopeTrait; |
| 9 | +use OAuthServer\Repositories\ClientRepository; |
| 10 | +use OAuthServer\Exception\AuthenticationException; |
| 11 | +use Psr\Http\Message\ServerRequestInterface as Request; |
| 12 | +use Psr\Http\Server\RequestHandlerInterface as Handler; |
| 13 | +use League\OAuth2\Server\Exception\OAuthServerException; |
| 14 | + |
| 15 | +class ClientMiddleware implements MiddlewareInterface |
| 16 | +{ |
| 17 | + use ValidateScopeTrait; |
| 18 | + |
| 19 | + protected $repository; |
| 20 | + protected $server; |
| 21 | + protected $client; |
| 22 | + |
| 23 | + public function __construct(ClientRepository $repository, ResourceServer $server) |
| 24 | + { |
| 25 | + $this->repository = $repository; |
| 26 | + $this->server = $server; |
| 27 | + } |
| 28 | + |
| 29 | + public function process(Request $request, Handler $handler): ResponseInterface |
| 30 | + { |
| 31 | + try { |
| 32 | + $request = $this->server->validateAuthenticatedRequest($request); |
| 33 | + } catch (OAuthServerException $exception) { |
| 34 | + throw new AuthenticationException("Unauthorize: {$exception->getMessage()}"); |
| 35 | + } catch (\Exception $exception) { |
| 36 | + throw new AuthenticationException("Unauthorize: {$exception->getMessage()}"); |
| 37 | + } |
| 38 | + |
| 39 | + $dispatched = $request->getAttribute(\Hyperf\HttpServer\Router\Dispatched::class); |
| 40 | + $scopes = $dispatched->handler->options['scopes']?? []; |
| 41 | + |
| 42 | + $this->validate($request, $scopes); |
| 43 | + |
| 44 | + $request = $request->withAttribute('client', $this->client); |
| 45 | + |
| 46 | + return $handler->handle($request); |
| 47 | + } |
| 48 | + |
| 49 | + protected function validate($request, $scopes) |
| 50 | + { |
| 51 | + $client = $this->repository->findActive($request->getAttribute('oauth_client_id')); |
| 52 | + |
| 53 | + if (is_null($client)) { |
| 54 | + throw new AuthenticationException("Unauthorize."); |
| 55 | + } |
| 56 | + |
| 57 | + $this->client = $client; |
| 58 | + |
| 59 | + $tokenScope = $request->getAttribute('oauth_scopes')?? []; |
| 60 | + |
| 61 | + $this->validateScopes($tokenScope, $scopes); |
| 62 | + } |
| 63 | +} |
0 commit comments