mc-cms-namelessmc/core/classes/Endpoints/KeyAuthEndpoint.php

63 lines
1.9 KiB
PHP
Raw Permalink Normal View History

2022-01-15 11:48:52 -08:00
<?php
use Symfony\Component\HttpFoundation\Response;
/**
* 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
*/
class KeyAuthEndpoint extends EndpointBase
{
/**
* Determine if the passed API key (in Authorization header) is valid.
*
* @param Nameless2API $api Instance of the Nameless2API class
* @return bool Whether the API key is valid
*/
final public function isAuthorised(Nameless2API $api): bool
{
2022-06-25 10:00:17 +02:00
$auth_header = HttpUtils::getHeader('Authorization');
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) {
$api->throwError(Nameless2API::ERROR_MISSING_API_KEY, 'Missing authorization header', Response::HTTP_UNAUTHORIZED);
}
$api_key = $api_key_header;
2022-01-15 11:48:52 -08:00
}
return $this->validateKey($api_key);
2022-01-15 11:48:52 -08:00
}
/**
* Validate provided API key to make sure it matches.
*
* @param string $api_key API key to check.
* @return bool Whether it matches or not.
2022-01-15 11:48:52 -08:00
*/
private function validateKey(string $api_key): bool
{
$correct_key = Settings::get('mc_api_key');
2022-07-03 20:56:15 +02:00
if ($correct_key === null) {
die('API key is null');
2022-01-15 11:48:52 -08:00
}
2022-03-31 21:50:33 +02:00
return hash_equals($api_key, $correct_key);
2022-01-15 11:48:52 -08:00
}
}