Refactor error handling and logging in API responses
This commit is contained in:
20
common.php
20
common.php
@ -235,23 +235,14 @@ function get_bearer_token(): ?string {
|
||||
function require_valid_token(): array {
|
||||
$token = get_bearer_token();
|
||||
if (!$token) {
|
||||
http_response_code(401);
|
||||
header('Content-Type: application/json; charset=UTF-8');
|
||||
echo json_encode(["error" => "Missing Bearer token"]);
|
||||
exit;
|
||||
json_error('UNAUTHORIZED', 'Missing Bearer token', 401);
|
||||
}
|
||||
$rec = token_get_record($token);
|
||||
if (!$rec) {
|
||||
http_response_code(403);
|
||||
header('Content-Type: application/json; charset=UTF-8');
|
||||
echo json_encode(["error" => "Invalid or expired token"]);
|
||||
exit;
|
||||
json_error('UNAUTHORIZED', 'Invalid or expired token', 401);
|
||||
}
|
||||
if (!empty($rec['temp'])) {
|
||||
http_response_code(403);
|
||||
header('Content-Type: application/json; charset=UTF-8');
|
||||
echo json_encode(["error" => "Password change required before access"]);
|
||||
exit;
|
||||
json_error('PASSWORD_CHANGE_REQUIRED', 'Password change required before access', 403);
|
||||
}
|
||||
$rec['_token'] = $token;
|
||||
return $rec;
|
||||
@ -260,10 +251,7 @@ function require_valid_token(): array {
|
||||
function require_role(array $allowed, array $tokenRecord): void {
|
||||
$role = $tokenRecord['role'] ?? '';
|
||||
if (!in_array($role, $allowed, true)) {
|
||||
http_response_code(403);
|
||||
header('Content-Type: application/json; charset=UTF-8');
|
||||
echo json_encode(["error" => "Insufficient permissions"]);
|
||||
exit;
|
||||
json_error('FORBIDDEN', 'Insufficient permissions', 403);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user