97 lines
2.5 KiB
PHP
97 lines
2.5 KiB
PHP
<?php
|
|
/**
|
|
* Authentication — App Key Validation
|
|
*/
|
|
|
|
require_once __DIR__ . '/../config.php';
|
|
|
|
class Auth
|
|
{
|
|
/**
|
|
* Validate the app_key from request.
|
|
* Supports both Flutter app key and Caller device key.
|
|
*
|
|
* @param string|null $key The key provided in request
|
|
* @param string $required Which key type is required: 'app' | 'device' | 'any'
|
|
* @return bool
|
|
*/
|
|
public static function validate(?string $key, string $required = 'any'): bool
|
|
{
|
|
if ($key === null || $key === '') {
|
|
return false;
|
|
}
|
|
|
|
switch ($required) {
|
|
case 'app':
|
|
return hash_equals(APP_KEY, $key);
|
|
case 'device':
|
|
return hash_equals(DEVICE_KEY, $key);
|
|
case 'any':
|
|
return hash_equals(APP_KEY, $key) || hash_equals(DEVICE_KEY, $key);
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Extract app_key from request (header or body).
|
|
*/
|
|
public static function getKeyFromRequest(): ?string
|
|
{
|
|
// Check header first
|
|
$headerKey = $_SERVER['HTTP_X_APP_KEY']
|
|
?? $_SERVER['HTTP_APP_KEY']
|
|
?? null;
|
|
|
|
if ($headerKey !== null) {
|
|
return $headerKey;
|
|
}
|
|
|
|
// Check JSON body
|
|
$body = json_decode(file_get_contents('php://input'), true);
|
|
if (is_array($body) && isset($body['app_key'])) {
|
|
return $body['app_key'];
|
|
}
|
|
|
|
// Check POST data
|
|
if (isset($_POST['app_key'])) {
|
|
return $_POST['app_key'];
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Require authentication — sends 401 and exits on failure.
|
|
*/
|
|
public static function requireAuth(string $required = 'any'): void
|
|
{
|
|
$key = self::getKeyFromRequest();
|
|
if (!self::validate($key, $required)) {
|
|
http_response_code(401);
|
|
header('Content-Type: application/json');
|
|
echo json_encode([
|
|
'success' => false,
|
|
'message' => 'invalid_app_key',
|
|
]);
|
|
exit;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Determine if the provided key is the device key.
|
|
*/
|
|
public static function isDeviceKey(?string $key): bool
|
|
{
|
|
return $key !== null && hash_equals(DEVICE_KEY, $key);
|
|
}
|
|
|
|
/**
|
|
* Determine if the provided key is the app key.
|
|
*/
|
|
public static function isAppKey(?string $key): bool
|
|
{
|
|
return $key !== null && hash_equals(APP_KEY, $key);
|
|
}
|
|
}
|