Completed
Pull Request — master (#987)
by
unknown
04:24
created

ImplicitGrant::validateAuthorizationRequest()   B

Complexity

Conditions 9
Paths 9

Size

Total Lines 58

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
dl 0
loc 58
ccs 0
cts 47
cp 0
rs 7.3608
c 0
b 0
f 0
cc 9
nc 9
nop 1
crap 90

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