Completed
Push — master ( 7810d2...aebd05 )
by Alexandre
02:43
created

AuthorizationEndpoint   B

Complexity

Total Complexity 48

Size/Duplication

Total Lines 287
Duplicated Lines 0 %

Test Coverage

Coverage 58.65%

Importance

Changes 0
Metric Value
dl 0
loc 287
ccs 78
cts 133
cp 0.5865
rs 8.4864
c 0
b 0
f 0
wmc 48

3 Methods

Rating   Name   Duplication   Size   Complexity  
C checkClientRedirectUri() 0 52 15
C handle() 0 63 9
D verify() 0 126 24

How to fix   Complexity   

Complex Class

Complex classes like AuthorizationEndpoint often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AuthorizationEndpoint, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Alexandre
5
 * Date: 07/01/2018
6
 * Time: 13:57
7
 */
8
9
namespace OAuth2\Endpoints;
10
11
12
use GuzzleHttp\Psr7\Response;
13
use GuzzleHttp\Psr7\Uri;
14
use OAuth2\Config;
15
use OAuth2\EndpointMessages\Authorization\AuthorizationRequest;
16
use OAuth2\EndpointMessages\Authorization\AuthorizationResponse;
17
use OAuth2\EndpointMessages\Authorization\ErrorResponse;
18
use OAuth2\Exceptions\OAuthException;
19
use OAuth2\ResponseTypes\ResponseTypeInterface;
20
use OAuth2\Roles\ClientInterface;
21
use OAuth2\Roles\Clients\RegisteredClient;
22
use OAuth2\Roles\ResourceOwnerInterface;
23
use OAuth2\Storages\ClientStorageInterface;
24
use Psr\Http\Message\ResponseInterface;
25
use Psr\Http\Message\ServerRequestInterface;
26
use Psr\Http\Message\UriInterface;
27
28
class AuthorizationEndpoint extends AbstractEndpoint
29
{
30
    /**
31
     * https://github.com/authbucket/oauth2-php/blob/master/src/GrantType/AuthorizationCodeGrantTypeHandler.php
32
     *
33
     *
34
     * @param ServerRequestInterface $request
35
     * @param ResourceOwnerInterface $resourceOwner
36
     * @param bool|null $authorizationDecision
37
     * @param array|null $scopeRestrictedByResourceOwner
38
     * @return ResponseInterface
39
     * @throws \Exception
40
     */
41 4
    function handle(ServerRequestInterface $request, ResourceOwnerInterface $resourceOwner, bool $authorizationDecision,
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
42
                    ?array $scopeRestrictedByResourceOwner = null): ResponseInterface
43
    {
44
        /**
45
         * @var RegisteredClient $client
46
         */
47 4
        $result = $this->verify($request);
48 4
        if ($result instanceof Response) {
49 1
            return $result;
50
        }
51
52
        /**
53
         * @var RegisteredClient $client
54
         * @var array $responseTypes
55
         * @var Uri $redirectUri
56
         * @var array|null $scope
57
         * @var string|null $responseMode
58
         * @var bool $isInsecure
59
         */
60 3
        extract($result);
61
62 3
        $authorizationRequest = AuthorizationRequest::createFromServerRequest($request);
63
64
        try {
65
66 3
            if (!$authorizationDecision) {
67
                throw new OAuthException('access_denied',
68
                    'The resource owner server denied the request',
69
                    'https://tools.ietf.org/html/rfc6749#section-4.1.1');
70
            }
71
72 3
            $scope = $scopeRestrictedByResourceOwner ? $scopeRestrictedByResourceOwner : $scope;
73 3
            $data = [];
74
75
            /**
76
             * @var ResponseTypeInterface $responseType
77
             * @var Uri $redirectUri
78
             */
79 3
            foreach ($responseTypes as $responseType) {
80 3
                $result = $responseType->handle($request, $resourceOwner, $client, $scope);
81
82 3
                $data = array_merge($data, $result);
83
            }
84
        } catch (OAuthException $e) {
85
            return new ErrorResponse($redirectUri, $e->getError(),
86
                $e->getErrorDescription(),
87
                $e->getErrorUri(),
88
                $authorizationRequest->getState());
89
        }
90
91 3
        if ($authorizationRequest->getState()) {
92
            $data['state'] = $authorizationRequest->getState();
93
        }
94
95 3
        if ($responseMode == ResponseTypeInterface::RESPONSE_MODE_QUERY) {
96 2
            foreach ($data as $k => $v) {
97 2
                $redirectUri = Uri::withQueryValue($redirectUri, $k, $v);
98
            }
99
        } else {
100 1
            $redirectUri = $redirectUri->withFragment(http_build_query($data));
101
        }
102
103 3
        return new AuthorizationResponse($redirectUri);
104
    }
105
106
    /**
107
     * Renvoie une réponse si une erreur survient, null sinon,  le client et la redirect_uri sont des parametres int/out
108
     * @param ServerRequestInterface $request
109
     * @return Response|array
110
     * @throws \Exception
111
     */
112 4
    public function verify(ServerRequestInterface $request)
113
    {
114 4
        $authorizationRequest = AuthorizationRequest::createFromServerRequest($request);
115
116 4
        if (!$authorizationRequest->getResponseType()) {
117
            return new Response(400, [], json_encode([
118
                'error' => 'invalid_request',
119
                'error_description' => 'Missing a required parameter : response_type',
120
                'error_uri' => 'https://tools.ietf.org/html/rfc6749#section-4.1',
121
            ]));
122
        }
123
124 4
        if (!$authorizationRequest->getClientId()) {
125
            return new Response(400, [], json_encode([
126
                'error' => 'invalid_request',
127
                'error_description' => 'Missing a required parameter : client_id',
128
                'error_uri' => 'https://tools.ietf.org/html/rfc6749#section-4.1',
129
            ]));
130
        }
131
132
        /**
133
         * @var ClientStorageInterface $clientStorage
134
         */
135 4
        $clientStorage = $this->server->getStorageRepository()->getStorage('client');
136
137 4
        $client = $clientStorage->get($authorizationRequest->getClientId());
138 4
        if (!$client) {
139
            return new Response(400, [], json_encode([
140
                'error' => 'invalid_request',
141
                'error_description' => 'Invalid parameter : client_id',
142
                'error_uri' => 'https://tools.ietf.org/html/rfc6749#section-4.1',
143
            ]));
144
        }
145 4
        if (!$client instanceof RegisteredClient) {
0 ignored issues
show
introduced by
The condition ! $client instanceof OAu...lients\RegisteredClient can never be true.
Loading history...
146
            return new Response(400, [], json_encode([
147
                'error' => 'invalid_request',
148
                'error_description' => 'Client type is not supported',
149
                'error_uri' => 'https://tools.ietf.org/html/rfc6749#section-4.1',
150
            ]));
151
        }
152
153
        try {
154 4
            $redirectUri = $this->checkClientRedirectUri($client, $authorizationRequest->getRedirectUri());
155
        } catch (\Exception $e) {
156
            return new Response(400, [], json_encode([
157
                'error' => 'invalid_request',
158
                'error_description' => $e->getMessage(),
159
                'error_uri' => 'https://tools.ietf.org/html/rfc6749#section-4.1',
160
            ]));
161
        }
162
163
        try {
164 4
            if (!$authorizationRequest->getResponseType()) {
165
                throw new OAuthException('invalid_request',
166
                    'Missing a required parameter : response_type',
167
                    'https://tools.ietf.org/html/rfc6749#section-4.1'
168
                );
169
            }
170
171 4
            if ($this->server->getConfigurationRepository()->getConfig(Config::ENFORCE_STATE) &&
172 4
                !$authorizationRequest->getState()) {
173
                throw new OAuthException('invalid_request',
174
                    'Missing a required parameter : state',
175
                    'https://tools.ietf.org/html/rfc6749#section-4.1'
176
                );
177
            }
178
179 4
            $enforceTls = $this->server->getConfigurationRepository()->getConfig(Config::ENFORCE_TLS);
180 4
            $responseMode = ResponseTypeInterface::RESPONSE_MODE_QUERY;
181 4
            $isImplicit = false;
182 4
            $isInsecure = false;
183 4
            $responseTypes = [];
184 4
            foreach (explode(' ', $authorizationRequest->getResponseType()) as $responseTypeName) {
185 4
                $responseType = $this->server->getResponseTypeRepository()->getResponseType($responseTypeName);
186 4
                if (!$responseType) {
187 1
                    throw new OAuthException('unsupported_response_type',
188 1
                        'Invalid response_type parameter',
189 1
                        'https://tools.ietf.org/html/rfc6749#section-3.1.1');
190
                }
191
192 3
                if (($enforceTls == true && !$redirectUri->getScheme() != 'https') ||
193 3
                    (is_null($enforceTls) && $responseType->requireTLS() && !$redirectUri->getScheme() != 'https')) {
194 3
                    if (is_null($enforceTls) && !$client->isTLSSupported()) {
195 3
                        $isInsecure = true;
196
                    } else {
197
                        throw new OAuthException('access_denied',
198
                            'Require the use of TLS for the redirect URI',
199
                            'https://tools.ietf.org/html/rfc6749#section-3.1.2.1');
200
                    }
201
                }
202
203 3
                $responseType->verifyRequest($request);
204 3
                $responseTypes[] = $responseType;
205
206 3
                if ($responseType->getDefaultResponseMode() == ResponseTypeInterface::RESPONSE_MODE_FRAGMENT) {
207 1
                    $responseMode = $responseType->getDefaultResponseMode();
208
                }
209
210 3
                if ($responseType->isImplicit()) {
211 3
                    $isImplicit = true;
212
                }
213
            }
214
215 3
            if ($isImplicit && !$client->isImplicitAllowed()) {
216
                throw new OAuthException('unsupported_response_type',
217
                    'Client is not allowed to use implicit grant',
218
                    'https://tools.ietf.org/html/rfc6749#section-3.1.1');
219
            }
220
221 3
            $scopePolicyManager = $this->server->getScopePolicyManager();
222
223 3
            $scope = $scopePolicyManager->getScopeArray($client, $authorizationRequest->getScope());
224 3
            if (!$scopePolicyManager->checkScope($client, $scope)) {
225
                $supportedScopes = implode(', ', $scopePolicyManager->getSupportedScopes($client));
226
                throw new OAuthException('invalid_scope',
227
                    'Some of requested scopes are not supported. Scope supported : ' . $supportedScopes,
228 3
                    'https://tools.ietf.org/html/rfc6749#section-4.1');
229
            }
230
231 1
        } catch (OAuthException $e) {
232 1
            return new ErrorResponse($redirectUri,
233 1
                $e->getError(), $e->getErrorDescription(), $e->getErrorUri(),
234 1
                $authorizationRequest->getState());
235
        }
236
237 3
        return compact('client', 'responseTypes', 'redirectUri', 'scope', 'responseMode', 'isInsecure');
238
    }
239
240
    /**
241
     * @see https://tools.ietf.org/html/rfc6749#section-3.1.2.3
242
     *
243
     * Dynamic Configuration
244
     *
245
     *     If multiple redirection URIs have been registered, if only part of
246
     * the redirection URI has been registered, or if no redirection URI has
247
     * been registered, the client MUST include a redirection URI with the
248
     * authorization request using the "redirect_uri" request parameter.
249
     *
250
     * When a redirection URI is included in an authorization request, the
251
     * authorization server MUST compare and match the value received
252
     * against at least one of the registered redirection URIs (or URI
253
     * components) as defined in [RFC3986] Section 6, if any redirection
254
     * URIs were registered.  If the client registration included the full
255
     * redirection URI, the authorization server MUST compare the two URIs
256
     * using simple string comparison as defined in [RFC3986] Section 6.2.1
257
     *
258
     * @param ClientInterface|RegisteredClient $client
259
     * @param null|string $redirectUri
260
     * @return UriInterface
261
     * @throws \Exception
262
     */
263 4
    private function checkClientRedirectUri(ClientInterface $client, ?string $redirectUri) : UriInterface
264
    {
265 4
        if (!$redirectUri) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $redirectUri of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
266
            if ($this->server->getConfigurationRepository()->getConfig(Config::ENFORCE_REDIRECT_URI)) {
267
                throw new \Exception('A redirect URI must be supplied');
268
            }
269
            if (empty($client->getRedirectUris())) {
270
                throw new \Exception('No redirect URI was supplied or stored');
271
            }
272
            if (count($client->getRedirectUris()) > 1) {
273
                throw new \Exception('A redirect URI must be supplied when multiple redirect URIs are registered');
274
            }
275
            $redirectUri = new Uri($client->getRedirectUris()[0]);
276
        } else {
277 4
            $redirectUri = new Uri($redirectUri);
278 4
            if ($redirectUri->getFragment()) {
279
                throw new \Exception('The redirect URI must not contain a fragment');
280
            }
281 4
            if (empty($client->getRedirectUris())) {
282
                if ($client->requireRedirectUri()) {
283
                    throw new \Exception('A redirect URI must be stored');
284
                } else {
285
                    return $redirectUri;
286
                }
287
            }
288 4
            $redirectUriWithoutQuery = Uri::composeComponents(
289 4
                $redirectUri->getScheme(), $redirectUri->getAuthority(), $redirectUri->getPath(), '', '');
290 4
            $match = false;
291 4
            foreach ($client->getRedirectUris() as $registeredUri) {
292 4
                $registeredUri = new Uri($registeredUri);
293 4
                if ($registeredUri->getQuery()) {
294
                    if ($registeredUri->__toString() === $redirectUri->__toString()) {
295
                        $match = true;
296
                        break;
297
                    }
298
                } else {
299 4
                    if ($this->server->getConfigurationRepository()->getConfig(Config::STRICT_REDIRECT_URI_COMPARISON)) {
300 4
                        if ($registeredUri->__toString() === $redirectUri->__toString()) {
301 4
                            $match = true;
302 4
                            break;
303
                        }
304
                    } else if ($registeredUri->__toString() === $redirectUriWithoutQuery) {
305
                        $match = true;
306
                        break;
307
                    }
308
                }
309
            }
310 4
            if (!$match) {
311
                throw new \Exception('The redirect URI provided is missing or does not match');
312
            }
313
        }
314 4
        return $redirectUri;
315
    }
316
}