Files
panel-pelican-dev/app/Http/Middleware/Api/Daemon/DaemonAuthenticate.php

56 lines
1.7 KiB
PHP
Raw Permalink Normal View History

<?php
2024-03-12 22:39:16 -04:00
namespace App\Http\Middleware\Api\Daemon;
2024-03-16 21:34:09 -04:00
use App\Models\Node;
2025-09-24 13:34:19 +02:00
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
2025-09-24 13:34:19 +02:00
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
class DaemonAuthenticate
{
/**
2017-10-29 12:37:25 -05:00
* Daemon routes that this middleware should be skipped on.
*
* @var string[]
*/
protected array $except = [
2017-10-29 12:37:25 -05:00
'daemon.configuration',
];
/**
* Check if a request from the daemon can be properly attributed back to a single node instance.
*
* @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);
2024-03-16 21:34:09 -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.');
}
2024-03-16 21:34:09 -04:00
/** @var Node $node */
$node = Node::query()->where('daemon_token_id', $parts[0])->firstOrFail();
if (hash_equals((string) $node->daemon_token, $parts[1])) {
2024-03-16 21:34:09 -04:00
$request->attributes->set('node', $node);
2024-03-16 21:34:09 -04:00
return $next($request);
}
2021-01-23 12:33:34 -08:00
throw new AccessDeniedHttpException('You are not authorized to access this resource.');
}
}