Passed
Push — master ( 056b41...9402d9 )
by Andrew
21:25 queued 19:46
created

ImplicitGrant::completeAuthorizationRequest()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 53
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 5.0009

Importance

Changes 0
Metric Value
cc 5
eloc 33
c 0
b 0
f 0
nc 9
nop 1
dl 0
loc 53
ccs 29
cts 30
cp 0.9667
crap 5.0009
rs 9.0808

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
            $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
            if (!\is_string($redirectUri)) {
0 ignored issues
show
introduced by
The condition is_string($redirectUri) is always true.
Loading history...
133
                throw OAuthServerException::invalidRequest('redirect_uri');
134
            }
135
136 4
            $this->validateRedirectUri($redirectUri, $client, $request);
137
        } 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...
138
            || empty($client->getRedirectUri())) {
139
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
140
            throw OAuthServerException::invalidClient($request);
141
        } else {
142
            $redirectUri = \is_array($client->getRedirectUri())
143
                ? $client->getRedirectUri()[0]
144
                : $client->getRedirectUri();
145
        }
146
147 2
        $scopes = $this->validateScopes(
148 2
            $this->getQueryStringParameter('scope', $request, $this->defaultScope),
149
            $redirectUri
150
        );
151
152 2
        $stateParameter = $this->getQueryStringParameter('state', $request);
153
154 2
        if ($stateParameter !== null && !\is_string($stateParameter)) {
0 ignored issues
show
introduced by
The condition is_string($stateParameter) is always true.
Loading history...
155
            throw OAuthServerException::invalidRequest('state');
156
        }
157
158 2
        $authorizationRequest = new AuthorizationRequest();
159 2
        $authorizationRequest->setGrantTypeId($this->getIdentifier());
160 2
        $authorizationRequest->setClient($client);
161 2
        $authorizationRequest->setRedirectUri($redirectUri);
162
163 2
        if ($stateParameter !== null) {
164
            $authorizationRequest->setState($stateParameter);
165
        }
166
167 2
        $authorizationRequest->setScopes($scopes);
168
169 2
        return $authorizationRequest;
170
    }
171
172
    /**
173
     * {@inheritdoc}
174
     */
175 6
    public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
176
    {
177 6
        if ($authorizationRequest->getUser() instanceof UserEntityInterface === false) {
178 1
            throw new LogicException('An instance of UserEntityInterface should be set on the AuthorizationRequest');
179
        }
180
181 5
        $finalRedirectUri = ($authorizationRequest->getRedirectUri() === null)
182 5
            ? \is_array($authorizationRequest->getClient()->getRedirectUri())
183
                ? $authorizationRequest->getClient()->getRedirectUri()[0]
184 5
                : $authorizationRequest->getClient()->getRedirectUri()
185 5
            : $authorizationRequest->getRedirectUri();
186
187
        // The user approved the client, redirect them back with an access token
188 5
        if ($authorizationRequest->isAuthorizationApproved() === true) {
189
            // Finalize the requested scopes
190 4
            $finalizedScopes = $this->scopeRepository->finalizeScopes(
191 4
                $authorizationRequest->getScopes(),
192 4
                $this->getIdentifier(),
193 4
                $authorizationRequest->getClient(),
194 4
                $authorizationRequest->getUser()->getIdentifier()
195
            );
196
197 4
            $accessToken = $this->issueAccessToken(
198 4
                $this->accessTokenTTL,
199 4
                $authorizationRequest->getClient(),
200 4
                $authorizationRequest->getUser()->getIdentifier(),
201
                $finalizedScopes
202
            );
203
204 2
            $response = new RedirectResponse();
205 2
            $response->setRedirectUri(
206 2
                $this->makeRedirectUri(
207
                    $finalRedirectUri,
208
                    [
209 2
                        'access_token' => (string) $accessToken,
210 2
                        'token_type'   => 'Bearer',
211 2
                        'expires_in'   => $accessToken->getExpiryDateTime()->getTimestamp() - \time(),
212 2
                        'state'        => $authorizationRequest->getState(),
213
                    ],
214 2
                    $this->queryDelimiter
215
                )
216
            );
217
218 2
            return $response;
219
        }
220
221
        // The user denied the client, redirect them back with an error
222 1
        throw OAuthServerException::accessDenied(
223
            'The user denied the request',
224 1
            $this->makeRedirectUri(
225
                $finalRedirectUri,
226
                [
227 1
                    'state' => $authorizationRequest->getState(),
228
                ]
229
            )
230
        );
231
    }
232
}
233