Completed
Pull Request — master (#817)
by
unknown
01:55
created

ImplicitGrant::canRespondToAccessTokenRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
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
        if (is_null($clientId)) {
122
            throw OAuthServerException::invalidRequest('client_id');
123
        }
124
125
        $client = $this->clientRepository->getClientEntity(
126
            $clientId,
127
            $this->getIdentifier(),
128
            null,
129
            false
130
        );
131
132
        if ($client instanceof ClientEntityInterface === false) {
133
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
134
            throw OAuthServerException::invalidClient();
135
        }
136
137
        $redirectUri = $this->getQueryStringParameter('redirect_uri', $request);
138
        if ($redirectUri !== null) {
139
            if (
140
                is_string($client->getRedirectUri())
141
                && (strcmp($client->getRedirectUri(), $redirectUri) !== 0)
142
            ) {
143
                $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
144
                throw OAuthServerException::invalidClient();
145
            } elseif (
146
                is_array($client->getRedirectUri())
147
                && in_array($redirectUri, $client->getRedirectUri(), true) === false
148
            ) {
149
                $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
150
                throw OAuthServerException::invalidClient();
151
            }
152
        } elseif (is_array($client->getRedirectUri()) && count($client->getRedirectUri()) !== 1
153
            || empty($client->getRedirectUri())) {
154
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
155
            throw OAuthServerException::invalidClient();
156
        } else {
157
            $redirectUri = is_array($client->getRedirectUri())
158
                ? $client->getRedirectUri()[0]
159
                : $client->getRedirectUri();
160
        }
161
162
        $scopes = $this->validateScopes(
163
            $this->getQueryStringParameter('scope', $request, $this->defaultScope),
164
            $redirectUri
165
        );
166
167
        // Finalize the requested scopes
168
        $finalizedScopes = $this->scopeRepository->finalizeScopes(
169
            $scopes,
170
            $this->getIdentifier(),
171
            $client
172
        );
173
174
        $stateParameter = $this->getQueryStringParameter('state', $request);
175
176
        $authorizationRequest = new AuthorizationRequest();
177
        $authorizationRequest->setGrantTypeId($this->getIdentifier());
178
        $authorizationRequest->setClient($client);
179
        $authorizationRequest->setRedirectUri($redirectUri);
180
        $authorizationRequest->setState($stateParameter);
181
        $authorizationRequest->setScopes($finalizedScopes);
182
183
        return $authorizationRequest;
184
    }
185
186
    /**
187
     * {@inheritdoc}
188
     */
189
    public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
190
    {
191
        if ($authorizationRequest->getUser() instanceof UserEntityInterface === false) {
192
            throw new \LogicException('An instance of UserEntityInterface should be set on the AuthorizationRequest');
193
        }
194
195
        $finalRedirectUri = ($authorizationRequest->getRedirectUri() === null)
196
            ? is_array($authorizationRequest->getClient()->getRedirectUri())
197
                ? $authorizationRequest->getClient()->getRedirectUri()[0]
198
                : $authorizationRequest->getClient()->getRedirectUri()
199
            : $authorizationRequest->getRedirectUri();
200
201
        // The user approved the client, redirect them back with an access token
202
        if ($authorizationRequest->isAuthorizationApproved() === true) {
203
            $accessToken = $this->issueAccessToken(
204
                $this->accessTokenTTL,
205
                $authorizationRequest->getClient(),
206
                $authorizationRequest->getUser()->getIdentifier(),
207
                $authorizationRequest->getScopes()
208
            );
209
210
            $response = new RedirectResponse();
211
            $response->setRedirectUri(
212
                $this->makeRedirectUri(
213
                    $finalRedirectUri,
214
                    [
215
                        'access_token' => (string) $accessToken->convertToJWT($this->privateKey),
216
                        'token_type'   => 'Bearer',
217
                        'expires_in'   => $accessToken->getExpiryDateTime()->getTimestamp() - (new \DateTime())->getTimestamp(),
218
                        'state'        => $authorizationRequest->getState(),
219
                    ],
220
                    $this->queryDelimiter
221
                )
222
            );
223
224
            return $response;
225
        }
226
227
        // The user denied the client, redirect them back with an error
228
        throw OAuthServerException::accessDenied(
229
            'The user denied the request',
230
            $this->makeRedirectUri(
231
                $finalRedirectUri,
232
                [
233
                    'state' => $authorizationRequest->getState(),
234
                ]
235
            )
236
        );
237
    }
238
}
239