misc_pterodactyl-panel/app/Http/Middleware/Api/Daemon/DaemonAuthenticate.php

62 lines
1.9 KiB
PHP
Raw Normal View History

<?php
namespace Pterodactyl\Http\Middleware\Api\Daemon;
use Closure;
use Illuminate\Http\Request;
2022-10-23 22:17:24 -04:00
use Pterodactyl\Models\Node;
use Illuminate\Contracts\Encryption\Encrypter;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class DaemonAuthenticate
{
/**
2017-10-29 12:37:25 -05:00
* Daemon routes that this middleware should be skipped on.
*/
protected array $except = [
2017-10-29 12:37:25 -05:00
'daemon.configuration',
];
/**
* DaemonAuthenticate constructor.
*/
2022-10-23 22:17:24 -04:00
public function __construct(private Encrypter $encrypter)
{
}
/**
* Check if a request from the daemon can be properly attributed back to a single node instance.
*
2022-10-23 22:17:24 -04:00
* @throws HttpException
*/
public function handle(Request $request, Closure $next): mixed
{
2017-10-29 12:37:25 -05:00
if (in_array($request->route()->getName(), $this->except)) {
return $next($request);
}
if (is_null($bearer = $request->bearerToken())) {
2021-06-03 23:35:51 +03:00
throw new HttpException(401, 'Access to this endpoint must include an Authorization header.', null, ['WWW-Authenticate' => 'Bearer']);
}
$parts = explode('.', $bearer);
2022-10-23 22:17:24 -04:00
// Ensure that all the correct parts are provided in the header.
if (count($parts) !== 2 || empty($parts[0]) || empty($parts[1])) {
2021-01-23 12:33:34 -08:00
throw new BadRequestHttpException('The Authorization header provided was not in a valid format.');
}
2022-10-23 22:17:24 -04:00
/** @var Node $node */
$node = Node::query()->where('daemon_token_id', $parts[0])->firstOrFail();
2022-10-23 22:17:24 -04:00
if (hash_equals((string) $this->encrypter->decrypt($node->daemon_token), $parts[1])) {
$request->attributes->set('node', $node);
2022-10-23 22:17:24 -04:00
return $next($request);
}
2021-01-23 12:33:34 -08:00
throw new AccessDeniedHttpException('You are not authorized to access this resource.');
}
}