Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Http/Middleware/Api/Daemon/DaemonAuthenticate.php
10277 views
1
<?php
2
3
namespace Pterodactyl\Http\Middleware\Api\Daemon;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Contracts\Encryption\Encrypter;
7
use Pterodactyl\Repositories\Eloquent\NodeRepository;
8
use Symfony\Component\HttpKernel\Exception\HttpException;
9
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
10
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
11
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
12
13
class DaemonAuthenticate
14
{
15
/**
16
* Daemon routes that this middleware should be skipped on.
17
*/
18
protected array $except = [
19
'daemon.configuration',
20
];
21
22
/**
23
* DaemonAuthenticate constructor.
24
*/
25
public function __construct(private Encrypter $encrypter, private NodeRepository $repository)
26
{
27
}
28
29
/**
30
* Check if a request from the daemon can be properly attributed back to a single node instance.
31
*
32
* @throws HttpException
33
*/
34
public function handle(Request $request, \Closure $next): mixed
35
{
36
if (in_array($request->route()->getName(), $this->except)) {
37
return $next($request);
38
}
39
40
if (is_null($bearer = $request->bearerToken())) {
41
throw new HttpException(401, 'Access to this endpoint must include an Authorization header.', null, ['WWW-Authenticate' => 'Bearer']);
42
}
43
44
$parts = explode('.', $bearer);
45
// Ensure that all of the correct parts are provided in the header.
46
if (count($parts) !== 2 || empty($parts[0]) || empty($parts[1])) {
47
throw new BadRequestHttpException('The Authorization header provided was not in a valid format.');
48
}
49
50
try {
51
/** @var \Pterodactyl\Models\Node $node */
52
$node = $this->repository->findFirstWhere([
53
'daemon_token_id' => $parts[0],
54
]);
55
56
if (hash_equals((string) $this->encrypter->decrypt($node->daemon_token), $parts[1])) {
57
$request->attributes->set('node', $node);
58
59
return $next($request);
60
}
61
} catch (RecordNotFoundException $exception) {
62
// Do nothing, we don't want to expose a node not existing at all.
63
}
64
65
throw new AccessDeniedHttpException('You are not authorized to access this resource.');
66
}
67
}
68
69