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

85 lines
2.6 KiB
PHP
Raw Permalink Normal View History

<?php
namespace Pterodactyl\Http\Middleware\Api\Daemon;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Repositories\Eloquent\NodeRepository;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Pterodactyl\Exceptions\Repository\RecordNotFoundException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
class DaemonAuthenticate
{
2017-10-30 02:40:34 +00:00
/**
* @var \Pterodactyl\Repositories\Eloquent\NodeRepository
2017-10-30 02:40:34 +00:00
*/
private $repository;
/**
* @var \Illuminate\Contracts\Encryption\Encrypter
*/
private $encrypter;
/**
2017-10-29 17:37:25 +00:00
* Daemon routes that this middleware should be skipped on.
2017-10-30 02:40:34 +00:00
*
* @var array
*/
2017-10-29 17:37:25 +00:00
protected $except = [
'daemon.configuration',
];
/**
* DaemonAuthenticate constructor.
*/
public function __construct(Encrypter $encrypter, NodeRepository $repository)
{
$this->repository = $repository;
$this->encrypter = $encrypter;
}
/**
* Check if a request from the daemon can be properly attributed back to a single node instance.
*
* @return mixed
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function handle(Request $request, Closure $next)
{
2017-10-29 17:37:25 +00:00
if (in_array($request->route()->getName(), $this->except)) {
return $next($request);
}
if (is_null($bearer = $request->bearerToken())) {
2021-06-03 20:35:51 +00:00
throw new HttpException(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.
if (count($parts) !== 2 || empty($parts[0]) || empty($parts[1])) {
2021-01-23 20:33:34 +00:00
throw new BadRequestHttpException('The Authorization header provided was not in a valid format.');
}
try {
/** @var \Pterodactyl\Models\Node $node */
$node = $this->repository->findFirstWhere([
'daemon_token_id' => $parts[0],
]);
if (hash_equals((string) $this->encrypter->decrypt($node->daemon_token), $parts[1])) {
$request->attributes->set('node', $node);
return $next($request);
}
} catch (RecordNotFoundException $exception) {
// Do nothing, we don't want to expose a node not existing at all.
}
2021-01-23 20:33:34 +00:00
throw new AccessDeniedHttpException('You are not authorized to access this resource.');
}
}