AccessTokenEntity   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 11
dl 0
loc 55
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A convertToJWT() 0 23 4
A getUserEntity() 0 4 1
1
<?php
2
3
namespace AdvancedLearning\Oauth2Server\Entities;
4
5
use AdvancedLearning\Oauth2Server\Repositories\UserRepository;
6
use Lcobucci\JWT\Builder;
7
use Lcobucci\JWT\Signer\Key;
8
use Lcobucci\JWT\Signer\Rsa\Sha256;
9
use League\OAuth2\Server\CryptKey;
10
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
11
use League\OAuth2\Server\Entities\Traits\AccessTokenTrait;
12
use League\OAuth2\Server\Entities\Traits\EntityTrait;
13
use League\OAuth2\Server\Entities\Traits\TokenEntityTrait;
14
15
class AccessTokenEntity implements AccessTokenEntityInterface
16
{
17
    use TokenEntityTrait, EntityTrait, AccessTokenTrait;
18
19
    /**
20
     * AccessTokenEntity constructor.
21
     *
22
     * @param null|string $userIdentifier The identifier of the user.
23
     * @param array       $scopes         The scopes to assign the user.
24
     */
25
    public function __construct(?string $userIdentifier, array $scopes)
26
    {
27
        $this->setUserIdentifier($userIdentifier);
28
29
        foreach ($scopes as $scope) {
30
            $this->addScope($scope);
31
        }
32
    }
33
34
    /**
35
     * Generate a JWT from the access token
36
     *
37
     * @param CryptKey $privateKey
38
     *
39
     * @return string
40
     */
41
    public function convertToJWT(CryptKey $privateKey)
42
    {
43
        $tokenBuilder = (new Builder())
44
            ->setAudience($this->getClient()->getIdentifier())
45
            ->setId($this->getIdentifier(), true)
46
            ->setIssuedAt(time())
47
            ->setNotBefore(time())
48
            ->setExpiration($this->getExpiryDateTime()->getTimestamp())
49
            ->setSubject($this->getUserIdentifier())
50
            ->set('scopes', $this->getScopes());
51
52
        // add user name to claims
53
        if ($this->getUserIdentifier()) {
54
            $userEntity = $this->getUserEntity();
55
            $member = $userEntity->getMember();
56
57
            $tokenBuilder->set('fn', $member ? $member->FirstName : null)
58
                ->set('ln', $member ? $member->Surname : null);
59
        }
60
61
        return $tokenBuilder->sign(new Sha256(), new Key($privateKey->getKeyPath(), $privateKey->getPassPhrase()))
62
            ->getToken();
63
    }
64
65
    protected function getUserEntity()
66
    {
67
        return (new UserRepository())->getUserEntityByIdentifier($this->getUserIdentifier());
68
    }
69
}
70