Completed
Push — master ( 1de13c...bf55ce )
by Alex
33:38
created

BearerTokenResponse::generateHttpResponse()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 39
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 39
rs 8.8571
cc 2
eloc 24
nc 2
nop 1
1
<?php
2
/**
3
 * OAuth 2.0 Bearer Token Type.
4
 *
5
 * @author      Alex Bilbie <[email protected]>
6
 * @copyright   Copyright (c) Alex Bilbie
7
 * @license     http://mit-license.org/
8
 *
9
 * @link        https://github.com/thephpleague/oauth2-server
10
 */
11
namespace League\OAuth2\Server\ResponseTypes;
12
13
use League\OAuth2\Server\Entities\RefreshTokenEntityInterface;
14
use Psr\Http\Message\ResponseInterface;
15
16
class BearerTokenResponse extends AbstractResponseType
17
{
18
    /**
19
     * {@inheritdoc}
20
     */
21
    public function generateHttpResponse(ResponseInterface $response)
22
    {
23
        $expireDateTime = $this->accessToken->getExpiryDateTime()->getTimestamp();
24
25
        $jwtAccessToken = $this->accessToken->convertToJWT($this->privateKey);
26
27
        $responseParams = [
28
            'token_type'   => 'Bearer',
29
            'expires_in'   => $expireDateTime - (new \DateTime())->getTimestamp(),
30
            'access_token' => (string) $jwtAccessToken,
31
        ];
32
33
        if ($this->refreshToken instanceof RefreshTokenEntityInterface) {
34
            $refreshToken = $this->encrypt(
35
                json_encode(
36
                    [
37
                        'client_id'        => $this->accessToken->getClient()->getIdentifier(),
38
                        'refresh_token_id' => $this->refreshToken->getIdentifier(),
39
                        'access_token_id'  => $this->accessToken->getIdentifier(),
40
                        'scopes'           => $this->accessToken->getScopes(),
41
                        'user_id'          => $this->accessToken->getUserIdentifier(),
42
                        'expire_time'      => $this->refreshToken->getExpiryDateTime()->getTimestamp(),
43
                    ]
44
                )
45
            );
46
47
            $responseParams['refresh_token'] = $refreshToken;
48
        }
49
50
        $response = $response
51
            ->withStatus(200)
52
            ->withHeader('pragma', 'no-cache')
53
            ->withHeader('cache-control', 'no-store')
54
            ->withHeader('content-type', 'application/json; charset=UTF-8');
55
56
        $response->getBody()->write(json_encode($responseParams));
57
58
        return $response;
59
    }
60
}
61