false, 'error' => 'Invalid CSRF token', 'csrf_token' => CsrfMiddleware::getToken() ]); exit; } } // Only allow POST if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); throw new Exception("Method not allowed"); } // Get request data $input = json_decode(file_get_contents('php://input'), true); if (!$input) { http_response_code(400); throw new Exception("Invalid request data"); } $keyId = (int)($input['key_id'] ?? 0); if ($keyId <= 0) { http_response_code(400); throw new Exception("Valid key ID is required"); } // Use centralized database connection $conn = Database::getConnection(); // Get key info for audit log $apiKeyModel = new ApiKeyModel($conn); $keyInfo = $apiKeyModel->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() ]); } }