Files
pterodactyl-panel/app/Http/Middleware/Api/Daemon/DaemonAuthenticate.php
T

72 lines
2.4 KiB
PHP
Raw Normal View History

<?php
2026-10-05 18:10:18 -04:00
declare(strict_types=1);
namespace Pterodactyl\Http\Middleware\Api\Daemon;
2026-10-05 18:10:18 -04:00
use Closure;
use Illuminate\Contracts\Encryption\Encrypter;
2026-10-05 18:10:18 -04:00
use Illuminate\Http\Request;
use Pterodactyl\Http\Concerns\ResolvesRequestContext;
use Pterodactyl\Models\Node;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
2026-10-05 18:10:18 -04:00
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
class DaemonAuthenticate
{
2026-10-05 18:10:18 -04:00
use ResolvesRequestContext;
/**
2017-10-29 12:37:25 -05:00
* Daemon routes that this middleware should be skipped on.
2026-10-05 18:10:18 -04:00
*
* @var list<string>
*/
2022-10-14 10:59:20 -06:00
protected array $except = [
2017-10-29 12:37:25 -05:00
'daemon.configuration',
];
/**
* DaemonAuthenticate constructor.
*/
2026-10-05 18:10:18 -04:00
public function __construct(private readonly Encrypter $encrypter) {}
/**
* Check if a request from the daemon can be properly attributed back to a single node instance.
*
2024-10-21 19:18:20 -06:00
* @throws HttpException
*/
2026-10-05 18:10:18 -04:00
/**
* @param Closure(Request):Response $next
* @return Response
*/
public function handle(Request $request, Closure $next): mixed
{
2026-10-05 18:10:18 -04:00
if (in_array($this->resolvedRoute($request)->getName(), $this->except, true)) {
2017-10-29 12:37:25 -05:00
return $next($request);
}
2026-10-05 18:10:18 -04:00
throw_if(($bearer = $request->bearerToken()) === null, HttpException::class, 401, 'Access to this endpoint must include an Authorization header.', null, ['WWW-Authenticate' => 'Bearer']);
$parts = explode('.', $bearer);
// Ensure that all of the correct parts are provided in the header.
2026-10-05 18:10:18 -04:00
throw_if(count($parts) !== 2 || empty($parts[0]) || empty($parts[1]), BadRequestHttpException::class, 'The Authorization header provided was not in a valid format.');
2026-10-05 18:10:18 -04:00
// Unknown token ids and wrong tokens fail identically.
$node = Node::query()->where('daemon_token_id', $parts[0])->first();
if ($node !== null) {
$token = $this->encrypter->decrypt($node->daemon_token);
throw_unless(is_string($token), AccessDeniedHttpException::class, 'The authentication token provided is not valid.');
2026-10-05 18:10:18 -04:00
if (hash_equals($token, $parts[1])) {
$request->attributes->set('node', $node);
return $next($request);
}
}
2021-01-23 12:33:34 -08:00
throw new AccessDeniedHttpException('You are not authorized to access this resource.');
}
}