Passed
Pull Request — master (#1408)
by
unknown
33:57
created

ImplicitGrant::completeAuthorizationRequest()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 63
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 42
CRAP Score 4.0002

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 36
c 2
b 0
f 0
nc 4
nop 1
dl 0
loc 63
ccs 42
cts 43
cp 0.9767
crap 4.0002
rs 9.344

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @author      Alex Bilbie <[email protected]>
5
 * @copyright   Copyright (c) Alex Bilbie
6
 * @license     http://mit-license.org/
7
 *
8
 * @link        https://github.com/thephpleague/oauth2-server
9
 */
10
11
declare(strict_types=1);
12
13
namespace League\OAuth2\Server\Grant;
14
15
use DateInterval;
16
use League\OAuth2\Server\Entities\UserEntityInterface;
17
use League\OAuth2\Server\Exception\OAuthServerException;
18
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
19
use League\OAuth2\Server\RequestEvent;
20
use League\OAuth2\Server\RequestTypes\AuthorizationRequestInterface;
21
use League\OAuth2\Server\ResponseTypes\RedirectResponse;
22
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
23
use LogicException;
24
use Psr\Http\Message\ServerRequestInterface;
25
26
use function count;
27
use function is_array;
28
use function is_null;
29
use function time;
30
31
class ImplicitGrant extends AbstractAuthorizeGrant
32
{
33 18
    public function __construct(private DateInterval $accessTokenTTL, private string $queryDelimiter = '#')
34
    {
35 18
    }
36
37
    /**
38
     * @throws LogicException
39
     */
40 1
    public function setRefreshTokenTTL(DateInterval $refreshTokenTTL): void
41
    {
42 1
        throw new LogicException('The Implicit Grant does not return refresh tokens');
43
    }
44
45
    /**
46
     * @throws LogicException
47
     */
48 1
    public function setRefreshTokenRepository(RefreshTokenRepositoryInterface $refreshTokenRepository): void
49
    {
50 1
        throw new LogicException('The Implicit Grant does not return refresh tokens');
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56 1
    public function canRespondToAccessTokenRequest(ServerRequestInterface $request): bool
57
    {
58 1
        return false;
59
    }
60
61
    /**
62
     * Return the grant identifier that can be used in matching up requests.
63
     */
64 7
    public function getIdentifier(): string
65
    {
66 7
        return 'implicit';
67
    }
68
69
    /**
70
     * Respond to an incoming request.
71
     */
72 1
    public function respondToAccessTokenRequest(
73
        ServerRequestInterface $request,
74
        ResponseTypeInterface $responseType,
75
        DateInterval $accessTokenTTL
76
    ): ResponseTypeInterface {
77 1
        throw new LogicException('This grant does not used this method');
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83 1
    public function canRespondToAuthorizationRequest(ServerRequestInterface $request): bool
84
    {
85 1
        return (
86 1
            isset($request->getQueryParams()['response_type'])
87 1
            && $request->getQueryParams()['response_type'] === 'token'
88 1
            && isset($request->getQueryParams()['client_id'])
89 1
        );
90
    }
91
92
    /**
93
     * {@inheritdoc}
94
     */
95 6
    public function validateAuthorizationRequest(ServerRequestInterface $request): AuthorizationRequestInterface
96
    {
97 6
        $clientId = $this->getQueryStringParameter(
98 6
            'client_id',
99 6
            $request,
100 6
            $this->getServerParameter('PHP_AUTH_USER', $request)
101 6
        );
102
103 6
        if (is_null($clientId)) {
104 1
            throw OAuthServerException::invalidRequest('client_id');
105
        }
106
107 5
        $client = $this->getClientEntityOrFail($clientId, $request);
108
109 4
        $redirectUri = $this->getQueryStringParameter('redirect_uri', $request);
110
111 4
        if ($redirectUri !== null) {
112 4
            $this->validateRedirectUri($redirectUri, $client, $request);
113
        } elseif (
114
            is_array($client->getRedirectUri()) && count($client->getRedirectUri()) !== 1
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (is_array($client->getRe...getRedirectUri() === '', Probably Intended Meaning: is_array($client->getRed...etRedirectUri() === '')
Loading history...
115
            || $client->getRedirectUri() === ''
116
        ) {
117
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
118
            throw OAuthServerException::invalidClient($request);
119
        } else {
120
            $redirectUri = is_array($client->getRedirectUri())
121
                ? $client->getRedirectUri()[0]
122
                : $client->getRedirectUri();
123
        }
124
125 2
        $scopes = $this->validateScopes(
126 2
            $this->getQueryStringParameter('scope', $request, $this->defaultScope),
127 2
            $redirectUri
128 2
        );
129
130 2
        $stateParameter = $this->getQueryStringParameter('state', $request);
131
132 2
        $authorizationRequest = $this->createAuthorizationRequest();
133 2
        $authorizationRequest->setGrantTypeId($this->getIdentifier());
134 2
        $authorizationRequest->setClient($client);
135 2
        $authorizationRequest->setRedirectUri($redirectUri);
136
137 2
        if ($stateParameter !== null) {
138
            $authorizationRequest->setState($stateParameter);
139
        }
140
141 2
        $authorizationRequest->setScopes($scopes);
142
143 2
        return $authorizationRequest;
144
    }
145
146
    /**
147
     * {@inheritdoc}
148
     */
149 6
    public function completeAuthorizationRequest(AuthorizationRequestInterface $authorizationRequest): ResponseTypeInterface
150
    {
151 6
        $finalRedirectUri = $authorizationRequest->getRedirectUri()
152 1
                          ?? $this->getClientRedirectUri($authorizationRequest);
153
154
        // The user approved the client, redirect them back with an access token
155 5
        if ($authorizationRequest->isAuthorizationApproved() === true) {
156
            if ($authorizationRequest->getUser() instanceof UserEntityInterface === false) {
157 5
                throw new LogicException('An instance of UserEntityInterface should be set on the AuthorizationRequest');
158
            }
159 5
160
            // Finalize the requested scopes
161
            $finalizedScopes = $this->scopeRepository->finalizeScopes(
162 5
                $authorizationRequest->getScopes(),
163
                $this->getIdentifier(),
164 4
                $authorizationRequest->getClient(),
165 4
                $authorizationRequest->getUser()->getIdentifier()
166 4
            );
167 4
168 4
            $accessToken = $this->issueAccessToken(
169 4
                $this->accessTokenTTL,
170
                $authorizationRequest->getClient(),
171 4
                $authorizationRequest->getUser()->getIdentifier(),
172 4
                $finalizedScopes
173 4
            );
174 4
175 4
            $response = new RedirectResponse();
176 4
            $response->setRedirectUri(
177
                $this->makeRedirectUri(
178 2
                    $finalRedirectUri,
179 2
                    [
180 2
                        'access_token' => $accessToken->toString(),
181 2
                        'token_type'   => 'Bearer',
182 2
                        'expires_in'   => $accessToken->getExpiryDateTime()->getTimestamp() - time(),
183 2
                        'state'        => $authorizationRequest->getState(),
184 2
                    ],
185 2
                    $this->queryDelimiter
186 2
                )
187 2
            );
188 2
189 2
            return $response;
190 2
        }
191
192 2
        // The user is not authenticated, redirect them back with an error
193
        if (is_null($authorizationRequest->getUser())) {
194
            throw OAuthServerException::accessDenied(
195
                'The user is not authenticated.',
196 1
                $this->makeRedirectUri(
197 1
                    $finalRedirectUri,
198 1
                    [
199 1
                        'state' => $authorizationRequest->getState(),
200 1
                    ]
201 1
                )
202 1
            );
203 1
        }
204 1
205
        // The user denied the client, redirect them back with an error
206
        throw OAuthServerException::accessDenied(
207
            'The user denied the request',
208
            $this->makeRedirectUri(
209
                $finalRedirectUri,
210
                [
211
                    'state' => $authorizationRequest->getState(),
212
                ]
213
            )
214
        );
215
    }
216
217
    /**
218
     * Get the client redirect URI if not set in the request.
219
     */
220
    private function getClientRedirectUri(AuthorizationRequestInterface $authorizationRequest): string
221
    {
222
        return is_array($authorizationRequest->getClient()->getRedirectUri())
223
            ? $authorizationRequest->getClient()->getRedirectUri()[0]
224
            : $authorizationRequest->getClient()->getRedirectUri();
225
    }
226
}
227