GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 7f0d16...8ce98c )
by François
02:09
created

OAuthClient::getAuthorizeUri()   B

Complexity

Conditions 2
Paths 1

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 29
rs 8.8571
cc 2
eloc 19
nc 1
nop 2
1
<?php
2
3
/**
4
 * Copyright (c) 2016, 2017 François Kooman <[email protected]>.
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in all
14
 * copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
 * SOFTWARE.
23
 */
24
25
namespace fkooman\OAuth\Client;
26
27
use DateTime;
28
use fkooman\OAuth\Client\Exception\OAuthException;
29
use fkooman\OAuth\Client\Exception\OAuthServerException;
30
use fkooman\OAuth\Client\Http\HttpClientInterface;
31
use fkooman\OAuth\Client\Http\Request;
32
use fkooman\OAuth\Client\Http\Response;
33
use ParagonIE\ConstantTime\Base64;
34
35
class OAuthClient
36
{
37
    /** @var TokenStorageInterface */
38
    private $tokenStorage;
39
40
    /** @var \fkooman\OAuth\Client\Http\HttpClientInterface */
41
    private $httpClient;
42
43
    /** @var SessionInterface */
44
    private $session;
45
46
    /** @var RandomInterface */
47
    private $random;
48
49
    /** @var \DateTime */
50
    private $dateTime;
51
52
    /** @var Provider */
53
    private $provider = null;
54
55
    /** @var string */
56
    private $userId = null;
57
58
    /**
59
     * @param TokenStorageInterface    $tokenStorage
60
     * @param Http\HttpClientInterface $httpClient
61
     */
62
    public function __construct(TokenStorageInterface $tokenStorage, HttpClientInterface $httpClient)
63
    {
64
        $this->tokenStorage = $tokenStorage;
65
        $this->httpClient = $httpClient;
66
67
        $this->session = new Session();
68
        $this->random = new Random();
69
        $this->dateTime = new DateTime();
70
    }
71
72
    /**
73
     * @param Provider $provider
74
     */
75
    public function setProvider(Provider $provider)
76
    {
77
        $this->provider = $provider;
78
    }
79
80
    /**
81
     * @param SessionInterface $session
82
     */
83
    public function setSession(SessionInterface $session)
84
    {
85
        $this->session = $session;
86
    }
87
88
    /**
89
     * @param RandomInterface $random
90
     */
91
    public function setRandom(RandomInterface $random)
92
    {
93
        $this->random = $random;
94
    }
95
96
    /**
97
     * @param DateTime $dateTime
98
     */
99
    public function setDateTime(DateTime $dateTime)
100
    {
101
        $this->dateTime = $dateTime;
102
    }
103
104
    /**
105
     * @param string $userId
106
     */
107
    public function setUserId($userId)
108
    {
109
        $this->userId = $userId;
110
    }
111
112
    /**
113
     * Perform a GET request, convenience wrapper for ::send().
114
     *
115
     * @param string $requestScope
116
     * @param string $requestUri
117
     * @param array  $requestHeaders
118
     *
119
     * @return Http\Response|false
120
     */
121
    public function get($requestScope, $requestUri, array $requestHeaders = [])
122
    {
123
        return $this->send($requestScope, Request::get($requestUri, $requestHeaders));
124
    }
125
126
    /**
127
     * Perform a POST request, convenience wrapper for ::send().
128
     *
129
     * @param string $requestScope
130
     * @param string $requestUri
131
     * @param array  $postBody
132
     * @param array  $requestHeaders
133
     *
134
     * @return Http\Response|false
135
     */
136
    public function post($requestScope, $requestUri, array $postBody, array $requestHeaders = [])
137
    {
138
        return $this->send($requestScope, Request::post($requestUri, $postBody, $requestHeaders));
139
    }
140
141
    /**
142
     * Perform a HTTP request.
143
     *
144
     * @param string       $requestScope
145
     * @param Http\Request $request
146
     *
147
     * @return Response|false
148
     */
149
    public function send($requestScope, Request $request)
150
    {
151
        if (is_null($this->userId)) {
152
            throw new OAuthException('userId not set');
153
        }
154
155
        if (false === $accessToken = $this->getAccessToken($requestScope)) {
156
            return false;
157
        }
158
159
        if ($accessToken->isExpired($this->dateTime)) {
160
            // access_token is expired, try to refresh it
161
            if (is_null($accessToken->getRefreshToken())) {
162
                // we do not have a refresh_token, delete this access token, it
163
                // is useless now...
164
                $this->tokenStorage->deleteAccessToken($this->userId, $accessToken);
165
166
                return false;
167
            }
168
169
            // try to refresh the AccessToken
170
            if (false === $accessToken = $this->refreshAccessToken($accessToken)) {
171
                // didn't work
172
                return false;
173
            }
174
        }
175
176
        // add Authorization header to the request headers
177
        $request->setHeader('Authorization', sprintf('Bearer %s', $accessToken->getToken()));
178
179
        $response = $this->httpClient->send($request);
180
        if (401 === $response->getStatusCode()) {
181
            // the access_token was not accepted, but isn't expired, we assume
182
            // the user revoked it, also no need to try with refresh_token
183
            $this->tokenStorage->deleteAccessToken($this->userId, $accessToken);
184
185
            return false;
186
        }
187
188
        return $response;
189
    }
190
191
    /**
192
     * Obtain an authorization request URL to start the authorization process
193
     * at the OAuth provider.
194
     *
195
     * @param string $scope       the space separated scope tokens
196
     * @param string $redirectUri the URL registered at the OAuth provider, to
197
     *                            be redirected back to
198
     *
199
     * @return string the authorization request URL
200
     *
201
     * @see https://tools.ietf.org/html/rfc6749#section-3.3
202
     * @see https://tools.ietf.org/html/rfc6749#section-3.1.2
203
     */
204
    public function getAuthorizeUri($scope, $redirectUri)
205
    {
206
        $queryParameters = [
207
            'client_id' => $this->provider->getClientId(),
208
            'redirect_uri' => $redirectUri,
209
            'scope' => $scope,
210
            'state' => $this->random->get(16),
211
            'response_type' => 'code',
212
        ];
213
214
        $authorizeUri = sprintf(
215
            '%s%s%s',
216
            $this->provider->getAuthorizationEndpoint(),
217
            false === strpos($this->provider->getAuthorizationEndpoint(), '?') ? '?' : '&',
218
            http_build_query($queryParameters, '&')
219
        );
220
        $this->session->set(
221
            '_oauth2_session',
222
            array_merge(
223
                $queryParameters,
224
                [
225
                    'user_id' => $this->userId,
226
                    'provider_id' => $this->provider->getProviderId(),
227
                ]
228
            )
229
        );
230
231
        return $authorizeUri;
232
    }
233
234
    /**
235
     * @param string $responseCode  the code passed to the "code"
236
     *                              query parameter on the callback URL
237
     * @param string $responseState the state passed to the "state"
238
     *                              query parameter on the callback URL
239
     */
240
    public function handleCallback($responseCode, $responseState)
241
    {
242
        if (is_null($this->userId)) {
243
            throw new OAuthException('userId not set');
244
        }
245
246
        $sessionData = $this->session->get('_oauth2_session');
247
248
        // delete the session, we don't want it to be used multiple times...
249
        $this->session->del('_oauth2_session');
250
251
        if (!hash_equals($sessionData['state'], $responseState)) {
252
            // the OAuth state from the initial request MUST be the same as the
253
            // state used by the response
254
            throw new OAuthException('invalid session (state)');
255
        }
256
257
        // session providerId MUST match current set Provider
258
        if ($sessionData['provider_id'] !== $this->provider->getProviderId()) {
259
            throw new OAuthException('invalid session (provider_id)');
260
        }
261
262
        // session userId MUST match current set userId
263
        if ($sessionData['user_id'] !== $this->userId) {
264
            throw new OAuthException('invalid session (user_id)');
265
        }
266
267
        // prepare access_token request
268
        $tokenRequestData = [
269
            'client_id' => $this->provider->getClientId(),
270
            'grant_type' => 'authorization_code',
271
            'code' => $responseCode,
272
            'redirect_uri' => $sessionData['redirect_uri'],
273
        ];
274
275
        $response = $this->httpClient->send(
276
            Request::post(
277
                $this->provider->getTokenEndpoint(),
278
                $tokenRequestData,
279
                [
280
                    'Authorization' => sprintf(
281
                        'Basic %s',
282
                        Base64::encode(
283
                            sprintf('%s:%s', $this->provider->getClientId(), $this->provider->getSecret())
284
                        )
285
                    ),
286
                ]
287
            )
288
        );
289
290
        if (400 === $response->getStatusCode()) {
291
            // check for "invalid_grant"
292
            $responseData = $response->json();
293 View Code Duplication
            if (!array_key_exists('error', $responseData) || 'invalid_grant' !== $responseData['error']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
294
                // not an "invalid_grant", we can't deal with this here...
295
                throw new OAuthServerException($response);
296
            }
297
298
            throw new OAuthException('authorization_code was not accepted by the server');
299
        }
300
301
        if (!$response->isOkay()) {
302
            // if there is any other error, we can't deal with this here...
303
            throw new OAuthServerException($response);
304
        }
305
306
        $this->tokenStorage->addAccessToken(
307
            $this->userId,
308
            AccessToken::fromCodeResponse(
309
                $this->provider,
310
                $this->dateTime,
311
                $response->json(),
312
                // in case server does not return a scope, we know it granted
313
                // our requested scope
314
                $sessionData['scope']
315
            )
316
        );
317
    }
318
319
    /**
320
     * @param AccessToken $accessToken
321
     *
322
     * @return AccessToken|false
323
     */
324
    private function refreshAccessToken(AccessToken $accessToken)
325
    {
326
        // prepare access_token request
327
        $tokenRequestData = [
328
            'grant_type' => 'refresh_token',
329
            'refresh_token' => $accessToken->getRefreshToken(),
330
            'scope' => $accessToken->getScope(),
331
        ];
332
333
        $response = $this->httpClient->send(
334
            Request::post(
335
                $this->provider->getTokenEndpoint(),
336
                $tokenRequestData,
337
                [
338
                    'Authorization' => sprintf(
339
                        'Basic %s',
340
                        Base64::encode(
341
                            sprintf('%s:%s', $this->provider->getClientId(), $this->provider->getSecret())
342
                        )
343
                    ),
344
                ]
345
            )
346
        );
347
348
        if (400 === $response->getStatusCode()) {
349
            // check for "invalid_grant"
350
            $responseData = $response->json();
351 View Code Duplication
            if (!array_key_exists('error', $responseData) || 'invalid_grant' !== $responseData['error']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
352
                // not an "invalid_grant", we can't deal with this here...
353
                throw new OAuthServerException($response);
354
            }
355
356
            // delete the access_token, we assume the user revoked it
357
            $this->tokenStorage->deleteAccessToken($this->userId, $accessToken);
358
359
            return false;
360
        }
361
362
        if (!$response->isOkay()) {
363
            // if there is any other error, we can't deal with this here...
364
            throw new OAuthServerException($response);
365
        }
366
367
        $accessToken = AccessToken::fromRefreshResponse(
368
            $this->provider,
369
            $this->dateTime,
370
            $response->json(),
371
            // provide the old AccessToken to borrow some fields if the server
372
            // does not provide them on "refresh"
373
            $accessToken
374
        );
375
376
        // store the refreshed AccessToken
377
        $this->tokenStorage->addAccessToken($this->userId, $accessToken);
378
379
        return $accessToken;
380
    }
381
382
    /**
383
     * Find an AccessToken in the list that matches this scope, bound to
384
     * providerId and userId.
385
     *
386
     * @param string $scope
387
     *
388
     * @return AccessToken|false
389
     */
390
    private function getAccessToken($scope)
391
    {
392
        $accessTokenList = $this->tokenStorage->getAccessToken($this->userId);
393
        foreach ($accessTokenList as $accessToken) {
394
            if ($this->provider->getProviderId() !== $accessToken->getProviderId()) {
395
                continue;
396
            }
397
            if ($scope !== $accessToken->getScope()) {
398
                continue;
399
            }
400
401
            return $accessToken;
402
        }
403
404
        return false;
405
    }
406
}
407