Completed
Pull Request — master (#923)
by Andrew
02:54 queued 29s
created

ImplicitGrant::validateAuthorizationRequest()   B

Complexity

Conditions 9
Paths 9

Size

Total Lines 58

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 9.8185

Importance

Changes 0
Metric Value
dl 0
loc 58
ccs 29
cts 37
cp 0.7838
rs 7.3608
c 0
b 0
f 0
cc 9
nc 9
nop 1
crap 9.8185

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