getKeyById($keyId); if (!$keyInfo) { http_response_code(404); throw new Exception("API key not found"); } if (!$keyInfo['is_active']) { http_response_code(409); throw new Exception("API key is already revoked"); } // Revoke the key $success = $apiKeyModel->revokeKey($keyId); if (!$success) { http_response_code(500); throw new Exception("Failed to revoke API key"); } // Log the action $auditLog = new AuditLogModel($conn); $auditLog->log( $_SESSION['user']['user_id'], 'revoke', 'api_key', $keyId, ['key_name' => $keyInfo['key_name'], 'key_prefix' => $keyInfo['key_prefix']] ); // Clear output buffer ob_end_clean(); // Return success header('Content-Type: application/json'); echo json_encode([ 'success' => true, 'message' => 'API key revoked successfully' ]); } catch (Exception $e) { ob_end_clean(); header('Content-Type: application/json'); // Preserve any specific status set before the throw (401/403/404/409/...); // only fall back to 500 when nothing more specific was set. $code = http_response_code(); if (!is_int($code) || $code < 400) { $code = 500; } http_response_code($code); if ($code >= 500) { error_log("Revoke API key error: " . $e->getMessage()); echo json_encode([ 'success' => false, 'error' => 'An internal error occurred' ]); } else { echo json_encode([ 'success' => false, 'error' => $e->getMessage() ]); } }