-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathAuthorizationMiddleware.php
More file actions
189 lines (169 loc) · 6.79 KB
/
AuthorizationMiddleware.php
File metadata and controls
189 lines (169 loc) · 6.79 KB
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
189
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 1.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Authorization\Middleware;
use ArrayAccess;
use Authentication\IdentityInterface as AuthenIdentityInterface;
use Authorization\AuthorizationServiceInterface;
use Authorization\AuthorizationServiceProviderInterface;
use Authorization\Exception\AuthorizationRequiredException;
use Authorization\Exception\Exception;
use Authorization\Identity;
use Authorization\IdentityDecorator;
use Authorization\IdentityInterface;
use Authorization\Middleware\UnauthorizedHandler\UnauthorizedHandlerTrait;
use Cake\Core\InstanceConfigTrait;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use RuntimeException;
/**
* Authorization Middleware.
*
* Injects the authorization service and decorated identity objects into the request object as attributes.
*/
class AuthorizationMiddleware implements MiddlewareInterface
{
use InstanceConfigTrait;
use UnauthorizedHandlerTrait;
/**
* Default config.
*
* - `identityDecorator` Identity decorator class name or a callable.
* Defaults to IdentityDecorator
* - `identityAttribute` Attribute name the identity is stored under.
* Defaults to 'identity'
* - `requireAuthorizationCheck` When true the middleware will raise an exception
* if no authorization checks were done. This aids in ensuring that all actions
* check authorization. It is intended as a development aid and not to be relied upon
* in production. Defaults to `true`.
*
* @var array
*/
protected array $_defaultConfig = [
'identityDecorator' => null,
'identityAttribute' => 'identity',
'requireAuthorizationCheck' => true,
'unauthorizedHandler' => 'Authorization.Exception',
];
/**
* Authorization service or application instance.
*
* @var \Authorization\AuthorizationServiceInterface|\Authorization\AuthorizationServiceProviderInterface
*/
protected AuthorizationServiceInterface|AuthorizationServiceProviderInterface $subject;
/**
* Constructor.
*
* @param \Authorization\AuthorizationServiceInterface|\Authorization\AuthorizationServiceProviderInterface $subject Authorization service or provider instance.
* @param array $config Config array.
* @throws \InvalidArgumentException
*/
public function __construct(
AuthorizationServiceInterface|AuthorizationServiceProviderInterface $subject,
array $config = []
) {
if ($this->_defaultConfig['identityDecorator'] === null) {
$this->_defaultConfig['identityDecorator'] = interface_exists(AuthenIdentityInterface::class)
? Identity::class
: IdentityDecorator::class;
}
$this->subject = $subject;
$this->setConfig($config);
}
/**
* Callable implementation for the middleware stack.
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
* @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler.
* @return \Psr\Http\Message\ResponseInterface A response.
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$service = $this->getAuthorizationService($request);
$request = $request->withAttribute('authorization', $service);
$attribute = $this->getConfig('identityAttribute');
$identity = $request->getAttribute($attribute);
if ($identity !== null) {
$identity = $this->buildIdentity($service, $identity);
$request = $request->withAttribute($attribute, $identity);
}
try {
$response = $handler->handle($request);
if ($this->getConfig('requireAuthorizationCheck') && !$service->authorizationChecked()) {
throw new AuthorizationRequiredException(['url' => $request->getRequestTarget()]);
}
} catch (Exception $exception) {
$response = $this->handleException(
$exception,
$request,
$this->getConfig('unauthorizedHandler')
);
}
return $response;
}
/**
* Returns AuthorizationServiceInterface instance.
*
* @param \Psr\Http\Message\ServerRequestInterface $request Server request.
* @return \Authorization\AuthorizationServiceInterface
* @throws \RuntimeException When authorization method has not been defined.
*/
protected function getAuthorizationService(
ServerRequestInterface $request
): AuthorizationServiceInterface {
$service = $this->subject;
if ($this->subject instanceof AuthorizationServiceProviderInterface) {
$service = $this->subject->getAuthorizationService($request);
}
if (!$service instanceof AuthorizationServiceInterface) {
throw new RuntimeException(sprintf(
'Invalid service returned from the provider. `%s` does not implement `%s`.',
get_debug_type($service),
AuthorizationServiceInterface::class
));
}
return $service;
}
/**
* Builds the identity object.
*
* @param \Authorization\AuthorizationServiceInterface $service Authorization service.
* @param \ArrayAccess|array $identity Identity data
* @return \Authorization\IdentityInterface
*/
protected function buildIdentity(
AuthorizationServiceInterface $service,
ArrayAccess|array $identity
): IdentityInterface {
$class = $this->getConfig('identityDecorator');
if (is_callable($class)) {
$identity = $class($service, $identity);
} else {
if (!$identity instanceof IdentityInterface) {
$identity = new $class($service, $identity);
}
}
if (!$identity instanceof IdentityInterface) {
throw new RuntimeException(sprintf(
'Invalid identity returned by decorator. `%s` does not implement `%s`.',
get_debug_type($identity),
IdentityInterface::class
));
}
return $identity;
}
}