-
Notifications
You must be signed in to change notification settings - Fork 784
/
Copy pathCheckClientCredentialsForAnyScope.php
105 lines (91 loc) · 2.79 KB
/
CheckClientCredentialsForAnyScope.php
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
<?php
namespace Laravel\Passport\Http\Middleware;
use Closure;
use Zend\Diactoros\StreamFactory;
use Zend\Diactoros\ResponseFactory;
use Laravel\Passport\TokenRepository;
use Zend\Diactoros\UploadedFileFactory;
use League\OAuth2\Server\ResourceServer;
use Zend\Diactoros\ServerRequestFactory;
use Illuminate\Auth\AuthenticationException;
use Laravel\Passport\Exceptions\MissingScopeException;
use League\OAuth2\Server\Exception\OAuthServerException;
use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory;
class CheckClientCredentialsForAnyScope
{
/**
* The Resource Server instance.
*
* @var \League\OAuth2\Server\ResourceServer
*/
private $server;
/**
* Token Repository.
*
* @var \Laravel\Passport\TokenRepository
*/
protected $repository;
/**
* Create a new middleware instance.
*
* @param \League\OAuth2\Server\ResourceServer $server
* @param \Laravel\Passport\TokenRepository $repository
* @return void
*/
public function __construct(ResourceServer $server, TokenRepository $repository)
{
$this->server = $server;
$this->repository = $repository;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param mixed ...$scopes
* @return mixed
* @throws \Illuminate\Auth\AuthenticationException|\Laravel\Passport\Exceptions\MissingScopeException
*/
public function handle($request, Closure $next, ...$scopes)
{
$psr = (new PsrHttpFactory(
new ServerRequestFactory,
new StreamFactory,
new UploadedFileFactory,
new ResponseFactory
))->createRequest($request);
try {
$psr = $this->server->validateAuthenticatedRequest($psr);
} catch (OAuthServerException $e) {
throw new AuthenticationException;
}
if ($this->validate($psr, $scopes)) {
return $next($request);
}
throw new MissingScopeException($scopes);
}
/**
* Validate the scopes and token on the incoming request.
*
* @param \Psr\Http\Message\ServerRequestInterface $psr
* @param array $scopes
* @return bool
* @throws \Illuminate\Auth\AuthenticationException
*/
protected function validate($psr, $scopes)
{
$token = $this->repository->find($psr->getAttribute('oauth_access_token_id'));
if (! $token || $token->client->firstParty()) {
throw new AuthenticationException;
}
if (in_array('*', $token->scopes)) {
return true;
}
foreach ($scopes as $scope) {
if ($token->can($scope)) {
return true;
}
}
return false;
}
}