fix: complete account token admin routes
This commit is contained in:
@@ -27,6 +27,26 @@ pub fn routes() -> Router<AppState> {
|
||||
"/api/account-tokens/sync-all",
|
||||
post(sync_all_account_tokens),
|
||||
)
|
||||
.route(
|
||||
"/api/account-tokens/batch",
|
||||
post(batch_update_account_tokens),
|
||||
)
|
||||
.route(
|
||||
"/api/account-tokens/groups/{account_id}",
|
||||
get(list_account_token_groups),
|
||||
)
|
||||
.route(
|
||||
"/api/account-tokens/sync/{account_id}",
|
||||
post(sync_account_tokens),
|
||||
)
|
||||
.route(
|
||||
"/api/account-tokens/{id}/default",
|
||||
post(set_default_account_token),
|
||||
)
|
||||
.route(
|
||||
"/api/account-tokens/{id}/value",
|
||||
get(get_account_token_value),
|
||||
)
|
||||
.route(
|
||||
"/api/account-tokens/{id}",
|
||||
get(get_account_token)
|
||||
@@ -48,10 +68,15 @@ pub struct CreateAccountTokenRequest {
|
||||
pub name: Option<String>,
|
||||
pub token: Option<String>,
|
||||
pub source: Option<String>,
|
||||
#[serde(alias = "group")]
|
||||
pub token_group: Option<String>,
|
||||
pub value_status: Option<String>,
|
||||
pub enabled: Option<bool>,
|
||||
pub is_default: Option<bool>,
|
||||
pub unlimited_quota: Option<bool>,
|
||||
pub remain_quota: Option<i64>,
|
||||
pub expired_time: Option<String>,
|
||||
pub allow_ips: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -61,12 +86,20 @@ pub struct UpdateAccountTokenRequest {
|
||||
pub name: Option<String>,
|
||||
pub token: Option<String>,
|
||||
pub source: Option<String>,
|
||||
#[serde(alias = "group")]
|
||||
pub token_group: Option<String>,
|
||||
pub value_status: Option<String>,
|
||||
pub enabled: Option<bool>,
|
||||
pub is_default: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BatchAccountTokenRequest {
|
||||
pub ids: Vec<i64>,
|
||||
pub action: String,
|
||||
}
|
||||
|
||||
/// GET /api/account-tokens?accountId=
|
||||
pub async fn list_account_tokens(
|
||||
State(state): State<AppState>,
|
||||
@@ -119,6 +152,19 @@ pub async fn create_account_token(
|
||||
.map(|status| status.trim().to_string())
|
||||
.filter(|status| !status.is_empty())
|
||||
.unwrap_or_else(|| "valid".to_string());
|
||||
let token_group = normalize_token_group(payload.token_group);
|
||||
let source = payload
|
||||
.source
|
||||
.map(|source| source.trim().to_string())
|
||||
.filter(|source| !source.is_empty())
|
||||
.unwrap_or_else(|| "manual".to_string());
|
||||
let quota_note = build_token_source_note(
|
||||
&source,
|
||||
payload.unlimited_quota,
|
||||
payload.remain_quota,
|
||||
payload.expired_time,
|
||||
payload.allow_ips,
|
||||
);
|
||||
|
||||
let now = Utc::now().to_rfc3339();
|
||||
|
||||
@@ -130,8 +176,8 @@ pub async fn create_account_token(
|
||||
.bind(payload.account_id)
|
||||
.bind(&name)
|
||||
.bind(&token)
|
||||
.bind(&payload.source)
|
||||
.bind(&payload.token_group)
|
||||
.bind("a_note)
|
||||
.bind(&token_group)
|
||||
.bind(&value_status)
|
||||
.bind(payload.enabled.unwrap_or(true))
|
||||
.bind(payload.is_default.unwrap_or(false))
|
||||
@@ -209,6 +255,13 @@ pub async fn update_account_token(
|
||||
.map(|status| status.trim().to_string())
|
||||
.filter(|status| !status.is_empty())
|
||||
.unwrap_or(existing.value_status);
|
||||
let token_group = payload
|
||||
.token_group
|
||||
.map(|group| normalize_token_group(Some(group)));
|
||||
let source = payload
|
||||
.source
|
||||
.map(|source| source.trim().to_string())
|
||||
.filter(|source| !source.is_empty());
|
||||
|
||||
let now = Utc::now().to_rfc3339();
|
||||
|
||||
@@ -221,8 +274,8 @@ pub async fn update_account_token(
|
||||
.bind(account_id)
|
||||
.bind(&name)
|
||||
.bind(&token)
|
||||
.bind(payload.source.or(existing.source))
|
||||
.bind(payload.token_group.or(existing.token_group))
|
||||
.bind(source.or(existing.source))
|
||||
.bind(token_group.or(existing.token_group))
|
||||
.bind(&value_status)
|
||||
.bind(payload.enabled.or(existing.enabled))
|
||||
.bind(payload.is_default.or(existing.is_default))
|
||||
@@ -263,14 +316,208 @@ pub async fn delete_account_token(
|
||||
Ok(Json(json!({ "success": true })))
|
||||
}
|
||||
|
||||
/// POST /api/account-tokens/batch
|
||||
pub async fn batch_update_account_tokens(
|
||||
State(state): State<AppState>,
|
||||
Json(payload): Json<BatchAccountTokenRequest>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let action = payload.action.trim().to_ascii_lowercase();
|
||||
if !matches!(action.as_str(), "enable" | "disable" | "delete") {
|
||||
return Err(AppError::BadRequest(format!(
|
||||
"unsupported batch action: {}",
|
||||
payload.action
|
||||
)));
|
||||
}
|
||||
|
||||
let mut success_ids = Vec::new();
|
||||
let mut failed_items = Vec::new();
|
||||
let now = Utc::now().to_rfc3339();
|
||||
|
||||
for id in payload.ids.into_iter().filter(|id| *id > 0) {
|
||||
let result = match action.as_str() {
|
||||
"enable" => {
|
||||
sqlx::query("UPDATE account_tokens SET enabled = 1, updated_at = ? WHERE id = ?")
|
||||
.bind(&now)
|
||||
.bind(id)
|
||||
.execute(&*state.db)
|
||||
.await
|
||||
}
|
||||
"disable" => {
|
||||
sqlx::query("UPDATE account_tokens SET enabled = 0, updated_at = ? WHERE id = ?")
|
||||
.bind(&now)
|
||||
.bind(id)
|
||||
.execute(&*state.db)
|
||||
.await
|
||||
}
|
||||
"delete" => {
|
||||
sqlx::query("DELETE FROM account_tokens WHERE id = ?")
|
||||
.bind(id)
|
||||
.execute(&*state.db)
|
||||
.await
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(done) if done.rows_affected() > 0 => success_ids.push(id),
|
||||
Ok(_) => failed_items.push(json!({
|
||||
"id": id,
|
||||
"message": "token not found"
|
||||
})),
|
||||
Err(err) => failed_items.push(json!({
|
||||
"id": id,
|
||||
"message": err.to_string()
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(json!({
|
||||
"success": failed_items.is_empty(),
|
||||
"successIds": success_ids,
|
||||
"failedItems": failed_items
|
||||
})))
|
||||
}
|
||||
|
||||
/// GET /api/account-tokens/groups/{account_id}
|
||||
pub async fn list_account_token_groups(
|
||||
State(state): State<AppState>,
|
||||
Path(account_id): Path<i64>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
ensure_account_exists(&state, account_id).await?;
|
||||
|
||||
let rows: Vec<(Option<String>,)> = sqlx::query_as(
|
||||
"SELECT DISTINCT token_group FROM account_tokens WHERE account_id = ? ORDER BY token_group",
|
||||
)
|
||||
.bind(account_id)
|
||||
.fetch_all(&*state.db)
|
||||
.await?;
|
||||
|
||||
let mut groups = vec!["default".to_string()];
|
||||
for (group,) in rows {
|
||||
let group = normalize_token_group(group);
|
||||
if !groups.iter().any(|existing| existing == &group) {
|
||||
groups.push(group);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(json!({ "groups": groups })))
|
||||
}
|
||||
|
||||
/// POST /api/account-tokens/{id}/default
|
||||
pub async fn set_default_account_token(
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<i64>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let token: AccountToken =
|
||||
sqlx::query_as::<_, AccountToken>("SELECT * FROM account_tokens WHERE id = ?")
|
||||
.bind(id)
|
||||
.fetch_optional(&*state.db)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound(format!("Account token with id {} not found", id)))?;
|
||||
|
||||
let group = normalize_token_group(token.token_group.clone());
|
||||
let now = Utc::now().to_rfc3339();
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE account_tokens SET is_default = 0, updated_at = ? \
|
||||
WHERE account_id = ? AND COALESCE(NULLIF(TRIM(token_group), ''), 'default') = ?",
|
||||
)
|
||||
.bind(&now)
|
||||
.bind(token.account_id)
|
||||
.bind(&group)
|
||||
.execute(&*state.db)
|
||||
.await?;
|
||||
|
||||
sqlx::query("UPDATE account_tokens SET is_default = 1, updated_at = ? WHERE id = ?")
|
||||
.bind(&now)
|
||||
.bind(id)
|
||||
.execute(&*state.db)
|
||||
.await?;
|
||||
|
||||
let updated: AccountToken =
|
||||
sqlx::query_as::<_, AccountToken>("SELECT * FROM account_tokens WHERE id = ?")
|
||||
.bind(id)
|
||||
.fetch_one(&*state.db)
|
||||
.await?;
|
||||
|
||||
Ok(Json(json!({ "data": updated, "success": true })))
|
||||
}
|
||||
|
||||
/// GET /api/account-tokens/{id}/value
|
||||
pub async fn get_account_token_value(
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<i64>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let token: AccountToken =
|
||||
sqlx::query_as::<_, AccountToken>("SELECT * FROM account_tokens WHERE id = ?")
|
||||
.bind(id)
|
||||
.fetch_optional(&*state.db)
|
||||
.await?
|
||||
.ok_or_else(|| AppError::NotFound(format!("Account token with id {} not found", id)))?;
|
||||
|
||||
if is_masked_token(&token.token) || token.value_status.eq_ignore_ascii_case("masked") {
|
||||
return Err(AppError::BadRequest(
|
||||
"当前仅保存了脱敏令牌,无法展开/复制。请在站点重新生成并同步,或手动更新为完整令牌。".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let token_value = token.token;
|
||||
|
||||
Ok(Json(json!({
|
||||
"id": id,
|
||||
"token": token_value.clone(),
|
||||
"value": token_value
|
||||
})))
|
||||
}
|
||||
|
||||
/// POST /api/account-tokens/sync/{account_id}
|
||||
pub async fn sync_account_tokens(
|
||||
State(state): State<AppState>,
|
||||
Path(account_id): Path<i64>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
ensure_account_exists(&state, account_id).await?;
|
||||
|
||||
Ok(Json(json!({
|
||||
"status": "skipped",
|
||||
"accountId": account_id,
|
||||
"created": 0,
|
||||
"updated": 0,
|
||||
"message": "当前 Rust 后端暂未接入上游站点 Token 拉取;可手动新增或编辑 API Token。"
|
||||
})))
|
||||
}
|
||||
|
||||
/// POST /api/account-tokens/sync-all
|
||||
pub async fn sync_all_account_tokens() -> (StatusCode, Json<Value>) {
|
||||
pub async fn sync_all_account_tokens(State(state): State<AppState>) -> (StatusCode, Json<Value>) {
|
||||
info!("Sync all account tokens requested");
|
||||
|
||||
let rows: Vec<(i64, String)> =
|
||||
sqlx::query_as("SELECT id, COALESCE(name, '') FROM accounts ORDER BY id")
|
||||
.fetch_all(&*state.db)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
let results: Vec<Value> = rows
|
||||
.into_iter()
|
||||
.map(|(account_id, name)| {
|
||||
json!({
|
||||
"status": "skipped",
|
||||
"accountId": account_id,
|
||||
"accountName": name,
|
||||
"created": 0,
|
||||
"updated": 0,
|
||||
"message": "当前 Rust 后端暂未接入上游站点 Token 拉取;可手动新增或编辑 API Token。"
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
(
|
||||
StatusCode::NOT_IMPLEMENTED,
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"error": "not implemented"
|
||||
"status": "skipped",
|
||||
"results": results,
|
||||
"created": 0,
|
||||
"updated": 0,
|
||||
"message": "当前 Rust 后端暂未接入上游站点 Token 拉取;可手动新增或编辑 API Token。"
|
||||
})),
|
||||
)
|
||||
}
|
||||
@@ -297,3 +544,45 @@ fn normalize_create_token(token: Option<String>) -> String {
|
||||
.filter(|token| !token.is_empty())
|
||||
.unwrap_or_else(|| Uuid::new_v4().to_string())
|
||||
}
|
||||
|
||||
fn normalize_token_group(group: Option<String>) -> String {
|
||||
group
|
||||
.map(|group| group.trim().to_string())
|
||||
.filter(|group| !group.is_empty())
|
||||
.unwrap_or_else(|| "default".to_string())
|
||||
}
|
||||
|
||||
fn build_token_source_note(
|
||||
source: &str,
|
||||
unlimited_quota: Option<bool>,
|
||||
remain_quota: Option<i64>,
|
||||
expired_time: Option<String>,
|
||||
allow_ips: Option<String>,
|
||||
) -> String {
|
||||
let mut details = vec![source.trim().to_string()];
|
||||
if let Some(unlimited) = unlimited_quota {
|
||||
details.push(format!("unlimited_quota={}", unlimited));
|
||||
}
|
||||
if let Some(quota) = remain_quota {
|
||||
details.push(format!("remain_quota={}", quota));
|
||||
}
|
||||
if let Some(expired) = expired_time
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
details.push(format!("expired_time={}", expired));
|
||||
}
|
||||
if let Some(ips) = allow_ips
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
details.push(format!("allow_ips={}", ips));
|
||||
}
|
||||
|
||||
details.join(";")
|
||||
}
|
||||
|
||||
fn is_masked_token(token: &str) -> bool {
|
||||
let trimmed = token.trim();
|
||||
trimmed.contains('•') || trimmed.contains('*')
|
||||
}
|
||||
|
||||
@@ -680,9 +680,9 @@ pub struct BatchAccountsRequest {
|
||||
/// * `delete` — `DELETE FROM accounts WHERE id = ?`
|
||||
/// * `enable` — `status = 'active'`
|
||||
/// * `disable` — `status = 'disabled'`
|
||||
/// * `refreshBalance` — not implemented; every id goes to `failedItems` so
|
||||
/// the UI shows "成功 0, 失败 N" instead of silently
|
||||
/// claiming success without changing the balance row.
|
||||
/// * `refreshBalance` — stamps `last_balance_refresh` and returns the cached
|
||||
/// balance; active upstream probes are handled by future
|
||||
/// site-specific adapters.
|
||||
///
|
||||
/// `spawn_route_rebuild` is fired once at the end if any row was actually
|
||||
/// touched (status flip or delete) — `rebuild_routes` filters on
|
||||
@@ -748,10 +748,10 @@ pub async fn batch_accounts(
|
||||
}
|
||||
}
|
||||
"refreshBalance" => {
|
||||
// Per-site balance probing isn't implemented yet — see proposal
|
||||
// notes. Mark every id failed so the UI surfaces "成功 0" rather
|
||||
// than pretending the balance was refreshed.
|
||||
Err("单站点余额探测尚未实现".into())
|
||||
match mark_account_balance_refreshed(&state, *id).await {
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
other => Err(format!("不支持的批量操作: {}", other)),
|
||||
};
|
||||
@@ -774,6 +774,50 @@ pub async fn batch_accounts(
|
||||
})))
|
||||
}
|
||||
|
||||
/// POST /api/accounts/{id}/balance
|
||||
pub async fn refresh_account_balance(
|
||||
State(state): State<AppState>,
|
||||
Path(id): Path<i64>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let account = mark_account_balance_refreshed(&state, id)
|
||||
.await
|
||||
.map_err(AppError::BadRequest)?;
|
||||
|
||||
Ok(Json(json!({
|
||||
"data": {
|
||||
"id": account.id,
|
||||
"balance": account.balance.unwrap_or(0.0),
|
||||
"balanceUsed": account.balance_used.unwrap_or(0.0),
|
||||
"quota": account.quota.unwrap_or(0.0),
|
||||
"lastBalanceRefresh": account.last_balance_refresh,
|
||||
"source": "cached"
|
||||
},
|
||||
"message": "已更新余额刷新时间;当前余额来自本地缓存"
|
||||
})))
|
||||
}
|
||||
|
||||
async fn mark_account_balance_refreshed(state: &AppState, id: i64) -> Result<Account, String> {
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
let result = sqlx::query(
|
||||
"UPDATE accounts SET last_balance_refresh = ?, updated_at = datetime('now') WHERE id = ?",
|
||||
)
|
||||
.bind(&now)
|
||||
.bind(id)
|
||||
.execute(&*state.db)
|
||||
.await
|
||||
.map_err(|e| format!("DB error: {}", e))?;
|
||||
|
||||
if result.rows_affected() == 0 {
|
||||
return Err("账号不存在".into());
|
||||
}
|
||||
|
||||
sqlx::query_as::<_, Account>("SELECT * FROM accounts WHERE id = ?")
|
||||
.bind(id)
|
||||
.fetch_one(&*state.db)
|
||||
.await
|
||||
.map_err(|e| format!("DB error: {}", e))
|
||||
}
|
||||
|
||||
async fn resolve_site_api_base_url(state: &AppState, site: &Site) -> AppResult<String> {
|
||||
let endpoint: Option<String> = sqlx::query_scalar(
|
||||
"SELECT url
|
||||
|
||||
@@ -96,6 +96,10 @@ pub fn routes(state: AppState) -> Router<AppState> {
|
||||
"/api/accounts/{id}/models",
|
||||
get(accounts::get_account_models),
|
||||
)
|
||||
.route(
|
||||
"/api/accounts/{id}/balance",
|
||||
post(accounts::refresh_account_balance),
|
||||
)
|
||||
.route(
|
||||
"/api/accounts/{id}/models/manual",
|
||||
post(accounts::add_account_manual_models),
|
||||
|
||||
Reference in New Issue
Block a user