Completed
Pull Request — master (#924)
by
unknown
02:27
created

ImplicitGrant   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 211
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 8

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 23
lcom 2
cbo 8
dl 0
loc 211
ccs 0
cts 130
cp 0
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A setRefreshTokenTTL() 0 4 1
A setRefreshTokenRepository() 0 4 1
A canRespondToAccessTokenRequest() 0 4 1
A getIdentifier() 0 4 1
A respondToAccessTokenRequest() 0 7 1
A canRespondToAuthorizationRequest() 0 8 3
B validateAuthorizationRequest() 0 65 9
B completeAuthorizationRequest() 0 49 5
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
    public function __construct(\DateInterval $accessTokenTTL, $queryDelimiter = '#')
39
    {
40
        $this->accessTokenTTL = $accessTokenTTL;
41
        $this->queryDelimiter = $queryDelimiter;
42
    }
43
44
    /**
45
     * @param \DateInterval $refreshTokenTTL
46
     *
47
     * @throw \LogicException
48
     */
49
    public function setRefreshTokenTTL(\DateInterval $refreshTokenTTL)
50
    {
51
        throw new \LogicException('The Implicit Grant does not return refresh tokens');
52
    }
53
54
    /**
55
     * @param RefreshTokenRepositoryInterface $refreshTokenRepository
56
     *
57
     * @throw \LogicException
58
     */
59
    public function setRefreshTokenRepository(RefreshTokenRepositoryInterface $refreshTokenRepository)
60
    {
61
        throw new \LogicException('The Implicit Grant does not return refresh tokens');
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function canRespondToAccessTokenRequest(ServerRequestInterface $request)
68
    {
69
        return false;
70
    }
71
72
    /**
73
     * Return the grant identifier that can be used in matching up requests.
74
     *
75
     * @return string
76
     */
77
    public function getIdentifier()
78
    {
79
        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
    public function respondToAccessTokenRequest(
92
        ServerRequestInterface $request,
93
        ResponseTypeInterface $responseType,
94
        \DateInterval $accessTokenTTL
95
    ) {
96
        throw new \LogicException('This grant does not used this method');
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102
    public function canRespondToAuthorizationRequest(ServerRequestInterface $request)
103
    {
104
        return (
105
            isset($request->getQueryParams()['response_type'])
106
            && $request->getQueryParams()['response_type'] === 'token'
107
            && isset($request->getQueryParams()['client_id'])
108
        );
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114
    public function validateAuthorizationRequest(ServerRequestInterface $request)
115
    {
116
        $clientId = $this->getQueryStringParameter(
117
            'client_id',
118
            $request,
119
            $this->getServerParameter('PHP_AUTH_USER', $request)
120
        );
121
122
        if (is_null($clientId)) {
123
            throw OAuthServerException::invalidRequest('client_id');
124
        }
125
126
        $client = $this->clientRepository->getClientEntity(
127
            $clientId,
128
            $this->getIdentifier(),
129
            null,
130
            false
131
        );
132
133
        if ($client instanceof ClientEntityInterface === false) {
134
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
135
            throw OAuthServerException::invalidClient();
136
        }
137
138
        $redirectUri = $this->getQueryStringParameter('redirect_uri', $request);
139
140
        if ($redirectUri !== null) {
141
            $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
        $scopes = $this->validateScopes(
153
            $this->getQueryStringParameter('scope', $request, $this->defaultScope),
154
            $redirectUri
155
        );
156
157
        // Finalize the requested scopes
158
        $finalizedScopes = $this->scopeRepository->finalizeScopes(
159
            $scopes,
160
            $this->getIdentifier(),
161
            $client
162
        );
163
164
        $stateParameter = $this->getQueryStringParameter('state', $request);
165
166
        $authorizationRequest = new AuthorizationRequest();
167
        $authorizationRequest->setGrantTypeId($this->getIdentifier());
168
        $authorizationRequest->setClient($client);
169
        $authorizationRequest->setRedirectUri($redirectUri);
170
171
        if ($stateParameter !== null) {
172
            $authorizationRequest->setState($stateParameter);
173
        }
174
175
        $authorizationRequest->setScopes($finalizedScopes);
176
177
        return $authorizationRequest;
178
    }
179
180
    /**
181
     * {@inheritdoc}
182
     */
183
    public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
184
    {
185
        if ($authorizationRequest->getUser() instanceof UserEntityInterface === false) {
186
            throw new \LogicException('An instance of UserEntityInterface should be set on the AuthorizationRequest');
187
        }
188
189
        $finalRedirectUri = ($authorizationRequest->getRedirectUri() === null)
190
            ? is_array($authorizationRequest->getClient()->getRedirectUri())
191
                ? $authorizationRequest->getClient()->getRedirectUri()[0]
192
                : $authorizationRequest->getClient()->getRedirectUri()
193
            : $authorizationRequest->getRedirectUri();
194
195
        // The user approved the client, redirect them back with an access token
196
        if ($authorizationRequest->isAuthorizationApproved() === true) {
197
            $accessToken = $this->issueAccessToken(
198
                $this->accessTokenTTL,
199
                $authorizationRequest->getClient(),
200
                $authorizationRequest->getUser()->getIdentifier(),
201
                $authorizationRequest->getScopes()
202
            );
203
204
            $response = new RedirectResponse();
205
            $response->setRedirectUri(
206
                $this->makeRedirectUri(
207
                    $finalRedirectUri,
208
                    [
209
                        'access_token' => (string) $accessToken->convertToJWT($this->privateKey),
210
                        'token_type'   => 'Bearer',
211
                        'expires_in'   => $accessToken->getExpiryDateTime()->getTimestamp() - (new \DateTime())->getTimestamp(),
212
                        'state'        => $authorizationRequest->getState(),
213
                    ],
214
                    $this->queryDelimiter
215
                )
216
            );
217
218
            return $response;
219
        }
220
221
        // The user denied the client, redirect them back with an error
222
        throw OAuthServerException::accessDenied(
223
            'The user denied the request',
224
            $this->makeRedirectUri(
225
                $finalRedirectUri,
226
                [
227
                    'state' => $authorizationRequest->getState(),
228
                ]
229
            )
230
        );
231
    }
232
}
233