Passed
Pull Request — master (#1122)
by Andrew
04:11 queued 31s
created

ImplicitGrant::completeAuthorizationRequest()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 64
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 40
CRAP Score 6.0005

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 40
c 1
b 0
f 0
nc 13
nop 1
dl 0
loc 64
ccs 40
cts 41
cp 0.9756
crap 6.0005
rs 8.6577

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