Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Services/Nodes/NodeJWTService.php
10262 views
1
<?php
2
3
namespace Pterodactyl\Services\Nodes;
4
5
use Carbon\CarbonImmutable;
6
use Illuminate\Support\Str;
7
use Pterodactyl\Models\Node;
8
use Pterodactyl\Models\User;
9
use Lcobucci\JWT\Configuration;
10
use Lcobucci\JWT\UnencryptedToken;
11
use Lcobucci\JWT\Signer\Hmac\Sha256;
12
use Lcobucci\JWT\Signer\Key\InMemory;
13
use Pterodactyl\Extensions\Lcobucci\JWT\Encoding\TimestampDates;
14
15
class NodeJWTService
16
{
17
private array $claims = [];
18
19
private ?User $user = null;
20
21
private \DateTimeImmutable $expiresAt;
22
23
private ?string $subject = null;
24
25
/**
26
* Set the claims to include in this JWT.
27
*/
28
public function setClaims(array $claims): self
29
{
30
$this->claims = $claims;
31
32
return $this;
33
}
34
35
/**
36
* Attaches a user to the JWT being created and will automatically inject the
37
* "user_uuid" key into the final claims array with the user's UUID.
38
*/
39
public function setUser(User $user): self
40
{
41
$this->user = $user;
42
43
return $this;
44
}
45
46
public function setExpiresAt(\DateTimeImmutable $date): self
47
{
48
$this->expiresAt = $date;
49
50
return $this;
51
}
52
53
public function setSubject(string $subject): self
54
{
55
$this->subject = $subject;
56
57
return $this;
58
}
59
60
/**
61
* Generate a new JWT for a given node.
62
*/
63
public function handle(Node $node, ?string $identifiedBy, string $algo = 'md5'): UnencryptedToken
64
{
65
$identifier = hash($algo, $identifiedBy);
66
$config = Configuration::forSymmetricSigner(new Sha256(), InMemory::plainText($node->getDecryptedKey()));
67
68
$builder = $config->builder(new TimestampDates())
69
->issuedBy(config('app.url'))
70
->permittedFor($node->getConnectionAddress())
71
->identifiedBy($identifier)
72
->withHeader('jti', $identifier)
73
->issuedAt(CarbonImmutable::now())
74
->canOnlyBeUsedAfter(CarbonImmutable::now()->subMinutes(5));
75
76
if (isset($this->expiresAt)) {
77
$builder = $builder->expiresAt($this->expiresAt);
78
}
79
80
if (!empty($this->subject)) {
81
$builder = $builder->relatedTo($this->subject)->withHeader('sub', $this->subject);
82
}
83
84
foreach ($this->claims as $key => $value) {
85
$builder = $builder->withClaim($key, $value);
86
}
87
88
if (!is_null($this->user)) {
89
$builder = $builder
90
->withClaim('user_uuid', $this->user->uuid)
91
// The "user_id" claim is deprecated and should not be referenced — it remains
92
// here solely to ensure older versions of Wings are unaffected when the Panel
93
// is updated.
94
//
95
// This claim will be removed in [email protected] or later.
96
->withClaim('user_id', $this->user->id);
97
}
98
99
return $builder
100
->withClaim('unique_id', Str::random())
101
->getToken($config->signer(), $config->signingKey());
102
}
103
}
104
105