2022-01-15 11:48:52 -08:00
|
|
|
<?php
|
2024-03-09 03:19:55 -08:00
|
|
|
|
2023-12-16 09:23:59 -08:00
|
|
|
use Symfony\Component\HttpFoundation\Response;
|
2024-03-09 03:19:55 -08:00
|
|
|
|
2022-02-14 20:48:15 -08:00
|
|
|
/**
|
|
|
|
|
* Allows an endpoint to require an API key to be present (and valid) in the request.
|
|
|
|
|
*
|
|
|
|
|
* @package NamelessMC\Endpoints
|
|
|
|
|
* @author Aberdeener
|
|
|
|
|
* @version 2.0.0-pr13
|
|
|
|
|
* @license MIT
|
|
|
|
|
*/
|
2024-03-09 03:19:55 -08:00
|
|
|
class KeyAuthEndpoint extends EndpointBase
|
|
|
|
|
{
|
2022-02-14 20:48:15 -08:00
|
|
|
/**
|
2022-04-24 19:15:48 +00:00
|
|
|
* Determine if the passed API key (in Authorization header) is valid.
|
2022-02-14 20:48:15 -08:00
|
|
|
*
|
2024-03-09 03:19:55 -08:00
|
|
|
* @param Nameless2API $api Instance of the Nameless2API class
|
|
|
|
|
* @return bool Whether the API key is valid
|
2022-02-14 20:48:15 -08:00
|
|
|
*/
|
2024-03-09 03:19:55 -08:00
|
|
|
final public function isAuthorised(Nameless2API $api): bool
|
|
|
|
|
{
|
2022-06-25 10:00:17 +02:00
|
|
|
$auth_header = HttpUtils::getHeader('Authorization');
|
2022-04-24 19:15:48 +00:00
|
|
|
|
2023-01-21 22:26:14 +01:00
|
|
|
if ($auth_header !== null) {
|
|
|
|
|
$exploded = explode(' ', trim($auth_header));
|
|
|
|
|
|
|
|
|
|
if (count($exploded) !== 2 ||
|
|
|
|
|
strcasecmp($exploded[0], 'Bearer') !== 0) {
|
|
|
|
|
$api->throwError(Nameless2API::ERROR_MISSING_API_KEY, 'Authorization header not in expected format');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$api_key = $exploded[1];
|
|
|
|
|
} else {
|
|
|
|
|
// Some hosting providers remove the Authorization header, fall back to non-standard X-API-Key heeader
|
|
|
|
|
$api_key_header = HttpUtils::getHeader('X-API-Key');
|
|
|
|
|
if ($api_key_header === null) {
|
2023-12-16 09:23:59 -08:00
|
|
|
$api->throwError(Nameless2API::ERROR_MISSING_API_KEY, 'Missing authorization header', Response::HTTP_UNAUTHORIZED);
|
2023-01-21 22:26:14 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$api_key = $api_key_header;
|
2022-01-15 11:48:52 -08:00
|
|
|
}
|
|
|
|
|
|
2023-12-16 09:23:59 -08:00
|
|
|
return $this->validateKey($api_key);
|
2022-01-15 11:48:52 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Validate provided API key to make sure it matches.
|
|
|
|
|
*
|
2024-03-09 03:19:55 -08:00
|
|
|
* @param string $api_key API key to check.
|
|
|
|
|
* @return bool Whether it matches or not.
|
2022-01-15 11:48:52 -08:00
|
|
|
*/
|
2024-03-09 03:19:55 -08:00
|
|
|
private function validateKey(string $api_key): bool
|
|
|
|
|
{
|
2023-06-12 10:30:49 -06:00
|
|
|
$correct_key = Settings::get('mc_api_key');
|
2022-07-03 20:56:15 +02:00
|
|
|
if ($correct_key === null) {
|
2022-06-01 00:20:38 +02:00
|
|
|
die('API key is null');
|
2022-01-15 11:48:52 -08:00
|
|
|
}
|
2022-06-09 20:14:12 +02:00
|
|
|
|
2022-03-31 21:50:33 +02:00
|
|
|
return hash_equals($api_key, $correct_key);
|
2022-01-15 11:48:52 -08:00
|
|
|
}
|
|
|
|
|
}
|