Passed
Pull Request — master (#1410)
by
unknown
31:10
created

DeviceCodeGrant::getIdentifier()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * OAuth 2.0 Device Code grant.
5
 *
6
 * @author      Andrew Millington <[email protected]>
7
 * @copyright   Copyright (c) Alex Bilbie
8
 * @license     http://mit-license.org/
9
 *
10
 * @link        https://github.com/thephpleague/oauth2-server
11
 */
12
13
declare(strict_types=1);
14
15
namespace League\OAuth2\Server\Grant;
16
17
use DateInterval;
18
use DateTimeImmutable;
19
use Error;
20
use Exception;
21
use League\OAuth2\Server\Entities\ClientEntityInterface;
22
use League\OAuth2\Server\Entities\DeviceCodeEntityInterface;
23
use League\OAuth2\Server\Entities\ScopeEntityInterface;
24
use League\OAuth2\Server\Exception\OAuthServerException;
25
use League\OAuth2\Server\Exception\UniqueTokenIdentifierConstraintViolationException;
26
use League\OAuth2\Server\Repositories\DeviceCodeRepositoryInterface;
27
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
28
use League\OAuth2\Server\RequestEvent;
29
use League\OAuth2\Server\ResponseTypes\DeviceCodeResponse;
30
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
31
use Psr\Http\Message\ServerRequestInterface;
32
use TypeError;
33
34
use function is_null;
35
use function random_int;
36
use function strlen;
37
use function time;
38
39
/**
40
 * Device Code grant class.
41
 */
42
class DeviceCodeGrant extends AbstractGrant
43
{
44
    protected DeviceCodeRepositoryInterface $deviceCodeRepository;
45
    private bool $includeVerificationUriComplete = false;
46
    private bool $intervalVisibility = false;
47
    private string $verificationUri;
48
49 17
    public function __construct(
50
        DeviceCodeRepositoryInterface $deviceCodeRepository,
51
        RefreshTokenRepositoryInterface $refreshTokenRepository,
52
        private DateInterval $deviceCodeTTL,
53
        string $verificationUri,
54
        private readonly int $retryInterval = 5
55
    ) {
56 17
        $this->setDeviceCodeRepository($deviceCodeRepository);
57 17
        $this->setRefreshTokenRepository($refreshTokenRepository);
58
59 17
        $this->refreshTokenTTL = new DateInterval('P1M');
60
61 17
        $this->setVerificationUri($verificationUri);
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67 2
    public function canRespondToDeviceAuthorizationRequest(ServerRequestInterface $request): bool
68
    {
69 2
        return true;
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75 7
    public function respondToDeviceAuthorizationRequest(ServerRequestInterface $request): DeviceCodeResponse
76
    {
77 7
        $clientId = $this->getRequestParameter(
78 7
            'client_id',
79 7
            $request,
80 7
            $this->getServerParameter('PHP_AUTH_USER', $request)
81 7
        );
82
83 7
        if ($clientId === null) {
84 2
            throw OAuthServerException::invalidRequest('client_id');
85
        }
86
87 5
        $client = $this->getClientEntityOrFail($clientId, $request);
88
89 4
        $scopes = $this->validateScopes($this->getRequestParameter('scope', $request, $this->defaultScope));
90
91 4
        $deviceCodeEntity = $this->issueDeviceCode(
92 4
            $this->deviceCodeTTL,
93 4
            $client,
94 4
            $this->verificationUri,
95 4
            $scopes
96 4
        );
97
98 4
        $response = new DeviceCodeResponse();
99
100 4
        if ($this->includeVerificationUriComplete === true) {
101 1
            $response->includeVerificationUriComplete();
102
        }
103
104 4
        if ($this->intervalVisibility === true) {
105
            $response->includeInterval();
106 4
        }
107
108
        $response->setDeviceCodeEntity($deviceCodeEntity);
109
110
        return $response;
111
    }
112 3
113
    /**
114 3
     * {@inheritdoc}
115
     */
116 3
    public function completeDeviceAuthorizationRequest(string $deviceCode, string $userId, bool $userApproved): void
117
    {
118
        $deviceCode = $this->deviceCodeRepository->getDeviceCodeEntityByDeviceCode($deviceCode);
119
120 3
        if ($deviceCode instanceof DeviceCodeEntityInterface === false) {
121
            throw OAuthServerException::invalidRequest('device_code', 'Device code does not exist');
122
        }
123
124 3
        if ($userId === '') {
125 3
            throw OAuthServerException::invalidRequest('user_id', 'User ID is required');
126
        }
127 3
128
        $deviceCode->setUserIdentifier($userId);
129
        $deviceCode->setUserApproved($userApproved);
130
131
        $this->deviceCodeRepository->persistDeviceCode($deviceCode);
132
    }
133 7
134
    /**
135
     * {@inheritdoc}
136
     */
137
    public function respondToAccessTokenRequest(
138
        ServerRequestInterface $request,
139 7
        ResponseTypeInterface $responseType,
140 6
        DateInterval $accessTokenTTL
141
    ): ResponseTypeInterface {
142 3
        // Validate request
143 3
        $client = $this->validateClient($request);
144
        $deviceCodeEntity = $this->validateDeviceCode($request, $client);
145
146 3
        // If device code has no user associated, respond with pending or slow down
147 1
        if (is_null($deviceCodeEntity->getUserIdentifier())) {
148
            $shouldSlowDown = $this->deviceCodePolledTooSoon($deviceCodeEntity->getLastPolledAt());
149
150 2
            $deviceCodeEntity->setLastPolledAt(new DateTimeImmutable());
151 1
            $this->deviceCodeRepository->persistDeviceCode($deviceCodeEntity);
152
153
            if ($shouldSlowDown) {
154
                throw OAuthServerException::slowDown();
155 1
            }
156
157
            throw OAuthServerException::authorizationPending();
158 1
        }
159 1
160 1
        if ($deviceCodeEntity->getUserApproved() === false) {
161
            throw OAuthServerException::accessDenied();
162
        }
163 1
164
        // Finalize the requested scopes
165 1
        $finalizedScopes = $this->scopeRepository->finalizeScopes($deviceCodeEntity->getScopes(), $this->getIdentifier(), $client, $deviceCodeEntity->getUserIdentifier());
166 1
167 1
        // Issue and persist new access token
168
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $deviceCodeEntity->getUserIdentifier(), $finalizedScopes);
169
        $this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
170 1
        $responseType->setAccessToken($accessToken);
171
172 1
        // Issue and persist new refresh token if given
173
        $refreshToken = $this->issueRefreshToken($accessToken);
174
175
        if ($refreshToken !== null) {
176
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
177
            $responseType->setRefreshToken($refreshToken);
178 6
        }
179
180 6
        $this->deviceCodeRepository->revokeDeviceCode($deviceCodeEntity->getIdentifier());
181
182 6
        return $responseType;
183 1
    }
184
185
    /**
186 5
     * @throws OAuthServerException
187 5
     */
188 5
    protected function validateDeviceCode(ServerRequestInterface $request, ClientEntityInterface $client): DeviceCodeEntityInterface
189
    {
190 5
        $deviceCode = $this->getRequestParameter('device_code', $request);
191
192
        if (is_null($deviceCode)) {
193
            throw OAuthServerException::invalidRequest('device_code');
194
        }
195
196 5
        $deviceCodeEntity = $this->deviceCodeRepository->getDeviceCodeEntityByDeviceCode(
197 1
            $deviceCode
198
        );
199
200 4
        if ($deviceCodeEntity instanceof DeviceCodeEntityInterface === false) {
201
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::USER_AUTHENTICATION_FAILED, $request));
202
203
            throw OAuthServerException::invalidGrant();
204 4
        }
205
206
        if (time() > $deviceCodeEntity->getExpiryDateTime()->getTimestamp()) {
207
            throw OAuthServerException::expiredToken('device_code');
208 4
        }
209 1
210
        if ($this->deviceCodeRepository->isDeviceCodeRevoked($deviceCode) === true) {
211
            throw OAuthServerException::invalidRequest('device_code', 'Device code has been revoked');
212 3
        }
213
214
        if ($deviceCodeEntity->getClient()->getIdentifier() !== $client->getIdentifier()) {
215 4
            throw OAuthServerException::invalidRequest('device_code', 'Device code was not issued to this client');
216
        }
217 4
218
        return $deviceCodeEntity;
219
    }
220
221
    private function deviceCodePolledTooSoon(?DateTimeImmutable $lastPoll): bool
222
    {
223 17
        return $lastPoll !== null && $lastPoll->getTimestamp() + $this->retryInterval > time();
224
    }
225 17
226
    /**
227
     * Set the verification uri
228
     */
229
    public function setVerificationUri(string $verificationUri): void
230
    {
231 8
        $this->verificationUri = $verificationUri;
232
    }
233 8
234
    /**
235
     * {@inheritdoc}
236 17
     */
237
    public function getIdentifier(): string
238 17
    {
239
        return 'urn:ietf:params:oauth:grant-type:device_code';
240
    }
241
242
    private function setDeviceCodeRepository(DeviceCodeRepositoryInterface $deviceCodeRepository): void
243
    {
244
        $this->deviceCodeRepository = $deviceCodeRepository;
245
    }
246
247
    /**
248
     * Issue a device code.
249 4
     *
250
     * @param ScopeEntityInterface[] $scopes
251
     *
252
     * @throws OAuthServerException
253
     * @throws UniqueTokenIdentifierConstraintViolationException
254
     */
255 4
    protected function issueDeviceCode(
256
        DateInterval $deviceCodeTTL,
257 4
        ClientEntityInterface $client,
258 4
        string $verificationUri,
259 4
        array $scopes = [],
260 4
    ): DeviceCodeEntityInterface {
261
        $maxGenerationAttempts = self::MAX_RANDOM_TOKEN_GENERATION_ATTEMPTS;
262 4
263 1
        $deviceCode = $this->deviceCodeRepository->getNewDeviceCode();
264
        $deviceCode->setExpiryDateTime((new DateTimeImmutable())->add($deviceCodeTTL));
265
        $deviceCode->setClient($client);
266 4
        $deviceCode->setVerificationUri($verificationUri);
267 4
        $deviceCode->setInterval($this->retryInterval);
268
269
        foreach ($scopes as $scope) {
270 4
            $deviceCode->addScope($scope);
271 4
        }
272 4
273
        while ($maxGenerationAttempts-- > 0) {
274
            $deviceCode->setIdentifier($this->generateUniqueIdentifier());
275 4
            $deviceCode->setUserCode($this->generateUserCode());
276
277 4
            try {
278
                $this->deviceCodeRepository->persistDeviceCode($deviceCode);
279
280
                return $deviceCode;
281
            } catch (UniqueTokenIdentifierConstraintViolationException $e) {
282
                if ($maxGenerationAttempts === 0) {
283
                    throw $e;
284
                }
285
            }
286
        }
287
288
        // This should never be hit. It is here to work around a PHPStan false error
289
        return $deviceCode;
290
    }
291
292
    /**
293
     * Generate a new user code.
294 4
     *
295
     * @throws OAuthServerException
296
     */
297 4
    protected function generateUserCode(int $length = 8): string
298 4
    {
299
        try {
300 4
            $userCode = '';
301 4
            $userCodeCharacters = 'BCDFGHJKLMNPQRSTVWXZ';
302
303
            while (strlen($userCode) < $length) {
304 4
                $userCode .= $userCodeCharacters[random_int(0, 19)];
305
            }
306
307
            return $userCode;
308
            // @codeCoverageIgnoreStart
309
        } catch (TypeError | Error $e) {
310
            throw OAuthServerException::serverError('An unexpected error has occurred', $e);
311
        } catch (Exception $e) {
312
            // If you get this message, the CSPRNG failed hard.
313
            throw OAuthServerException::serverError('Could not generate a random string', $e);
314
        }
315 1
        // @codeCoverageIgnoreEnd
316
    }
317 1
318
    public function setIntervalVisibility(bool $intervalVisibility): void
319
    {
320 4
        $this->intervalVisibility = $intervalVisibility;
321
    }
322 4
323
    public function getIntervalVisibility(): bool
324
    {
325 1
        return $this->intervalVisibility;
326
    }
327 1
328
    public function setIncludeVerificationUriComplete(bool $includeVerificationUriComplete): void
329
    {
330
        $this->includeVerificationUriComplete = $includeVerificationUriComplete;
331
    }
332
}
333