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
|
|
|
|