Passed
Pull Request — master (#1110)
by Andrew
02:29
created

ImplicitGrant::completeAuthorizationRequest()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 53
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 33
CRAP Score 5.0006

Importance

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