feat: add admin api key mutations

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-06-12 13:56:35 +08:00
co-authored by Codex
parent 51a518f692
commit 14fd4f5ef6
6 changed files with 363 additions and 7 deletions
+8 -2
View File
@@ -9,8 +9,9 @@ use crate::{
http::{
admin::{
accounts, api_keys, batch_delete_accounts, batch_update_account_status, create_api_key,
delete_account, import_accounts, login, logs, refresh_models, settings,
update_account_label, update_account_status, usage_stats, usage_stats_summary,
delete_account, delete_api_key, import_accounts, login, logs, refresh_models, settings,
update_account_label, update_account_status, update_api_key_status, usage_stats,
usage_stats_summary,
},
health::health,
middleware::attach_request_id,
@@ -55,6 +56,11 @@ pub fn build_router(state: AppState) -> Router {
)
.route("/admin/accounts/import", post(import_accounts))
.route("/admin/api-keys", get(api_keys).post(create_api_key))
.route("/admin/api-keys/{key_id}", delete(delete_api_key))
.route(
"/admin/api-keys/{key_id}/status",
patch(update_api_key_status),
)
.with_state(state)
.layer(TraceLayer::new_for_http())
.layer(from_fn(attach_request_id))
+17
View File
@@ -137,6 +137,23 @@ impl ClientApiKeyRepository {
}
Ok(false)
}
pub async fn set_enabled(&self, id: &str, enabled: bool) -> ClientApiKeyRepositoryResult<bool> {
let result = sqlx::query("update client_api_keys set enabled = ? where id = ?")
.bind(if enabled { 1_i64 } else { 0_i64 })
.bind(id)
.execute(&self.pool)
.await?;
Ok(result.rows_affected() > 0)
}
pub async fn delete(&self, id: &str) -> ClientApiKeyRepositoryResult<bool> {
let result = sqlx::query("delete from client_api_keys where id = ?")
.bind(id)
.execute(&self.pool)
.await?;
Ok(result.rows_affected() > 0)
}
}
fn key_from_row(row: &sqlx::sqlite::SqliteRow) -> StoredClientApiKey {
+142
View File
@@ -325,6 +325,25 @@ pub struct CreatedClientApiKeyData {
pub plaintext: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateClientApiKeyStatusRequest {
pub status: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateClientApiKeyStatusData {
pub id: String,
pub enabled: bool,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteClientApiKeyData {
pub deleted: bool,
}
impl From<StoredClientApiKey> for ClientApiKeyData {
fn from(key: StoredClientApiKey) -> Self {
Self {
@@ -1537,6 +1556,121 @@ pub async fn create_api_key(
}
}
pub async fn update_api_key_status(
State(state): State<AppState>,
Extension(request_id): Extension<RequestId>,
headers: HeaderMap,
Path(key_id): Path<String>,
Json(payload): Json<UpdateClientApiKeyStatusRequest>,
) -> Response {
let request_id = request_id.as_str().to_string();
let Some(pool) = state.db() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Database is not initialized", (), request_id),
)
.into_response();
};
if let Err(response) = require_admin_session(pool, &headers, &request_id).await {
return response;
}
let enabled = match parse_client_api_key_enabled_status(&payload.status) {
Ok(enabled) => enabled,
Err(message) => {
return AdminResponse::new(
StatusCode::BAD_REQUEST,
AdminEnvelope::new(40001, message, (), request_id),
)
.into_response();
}
};
let Some(repo) = state.client_api_key_repository() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(
50001,
"API key repository is not initialized",
(),
request_id,
),
)
.into_response();
};
match repo.set_enabled(&key_id, enabled).await {
Ok(true) => AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(
UpdateClientApiKeyStatusData {
id: key_id,
enabled,
},
request_id,
),
)
.into_response(),
Ok(false) => AdminResponse::new(
StatusCode::NOT_FOUND,
AdminEnvelope::new(40401, "API key not found", (), request_id),
)
.into_response(),
Err(_) => AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to update API key status", (), request_id),
)
.into_response(),
}
}
pub async fn delete_api_key(
State(state): State<AppState>,
Extension(request_id): Extension<RequestId>,
headers: HeaderMap,
Path(key_id): Path<String>,
) -> Response {
let request_id = request_id.as_str().to_string();
let Some(pool) = state.db() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Database is not initialized", (), request_id),
)
.into_response();
};
if let Err(response) = require_admin_session(pool, &headers, &request_id).await {
return response;
}
let Some(repo) = state.client_api_key_repository() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(
50001,
"API key repository is not initialized",
(),
request_id,
),
)
.into_response();
};
match repo.delete(&key_id).await {
Ok(true) => AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(DeleteClientApiKeyData { deleted: true }, request_id),
)
.into_response(),
Ok(false) => AdminResponse::new(
StatusCode::NOT_FOUND,
AdminEnvelope::new(40401, "API key not found", (), request_id),
)
.into_response(),
Err(_) => AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to delete API key", (), request_id),
)
.into_response(),
}
}
#[derive(Debug)]
struct AdminUserRow {
id: String,
@@ -1947,6 +2081,14 @@ fn parse_admin_account_status(status: &str) -> Result<AccountStatus, String> {
}
}
fn parse_client_api_key_enabled_status(status: &str) -> Result<bool, String> {
match status.trim().to_ascii_lowercase().as_str() {
"active" => Ok(true),
"disabled" => Ok(false),
other => Err(format!("Unsupported API key status: {other}")),
}
}
fn account_status_value(status: AccountStatus) -> &'static str {
match status {
AccountStatus::Active => "active",