mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-20 08:01:46 +00:00
feat: add admin manual account creation
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
+6
-6
@@ -9,11 +9,11 @@ use crate::{
|
||||
http::{
|
||||
admin::{
|
||||
accounts, api_keys, batch_delete_accounts, batch_delete_api_keys,
|
||||
batch_update_account_status, create_api_key, delete_account, delete_account_cookies,
|
||||
delete_api_key, export_accounts, get_account_cookies, import_accounts, login, logs,
|
||||
refresh_models, set_account_cookies, settings, update_account_label,
|
||||
update_account_status, update_api_key_label, update_api_key_status, usage_stats,
|
||||
usage_stats_summary,
|
||||
batch_update_account_status, create_account, create_api_key, delete_account,
|
||||
delete_account_cookies, delete_api_key, export_accounts, get_account_cookies,
|
||||
import_accounts, login, logs, refresh_models, set_account_cookies, settings,
|
||||
update_account_label, update_account_status, update_api_key_label,
|
||||
update_api_key_status, usage_stats, usage_stats_summary,
|
||||
},
|
||||
health::health,
|
||||
middleware::attach_request_id,
|
||||
@@ -41,7 +41,7 @@ pub fn build_router(state: AppState) -> Router {
|
||||
.route("/admin/refresh-models", post(refresh_models))
|
||||
.route("/admin/usage-stats", get(usage_stats))
|
||||
.route("/admin/usage-stats/summary", get(usage_stats_summary))
|
||||
.route("/admin/accounts", get(accounts))
|
||||
.route("/admin/accounts", get(accounts).post(create_account))
|
||||
.route("/admin/accounts/batch-delete", post(batch_delete_accounts))
|
||||
.route(
|
||||
"/admin/accounts/batch-status",
|
||||
|
||||
@@ -236,6 +236,20 @@ pub struct AccountImportData {
|
||||
pub source_format: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CreateAccountRequest {
|
||||
pub id: Option<String>,
|
||||
pub email: Option<String>,
|
||||
pub account_id: Option<String>,
|
||||
pub user_id: Option<String>,
|
||||
pub label: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub token: Option<String>,
|
||||
pub refresh_token: Option<String>,
|
||||
pub status: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum AccountExportFormat {
|
||||
Native,
|
||||
@@ -1083,6 +1097,156 @@ pub async fn export_accounts(
|
||||
AdminResponse::new(StatusCode::OK, AdminEnvelope::ok(data, request_id)).into_response()
|
||||
}
|
||||
|
||||
pub async fn create_account(
|
||||
State(state): State<AppState>,
|
||||
Extension(request_id): Extension<RequestId>,
|
||||
headers: HeaderMap,
|
||||
Json(payload): Json<CreateAccountRequest>,
|
||||
) -> Response {
|
||||
let request_id = request_id.as_str().to_string();
|
||||
let access_token = payload.token.as_deref().unwrap_or_default().trim();
|
||||
if access_token.is_empty() {
|
||||
return AdminResponse::new(
|
||||
StatusCode::BAD_REQUEST,
|
||||
AdminEnvelope::new(40001, "Account token is required", (), request_id),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
if payload
|
||||
.label
|
||||
.as_ref()
|
||||
.is_some_and(|label| label.chars().count() > 64)
|
||||
{
|
||||
return AdminResponse::new(
|
||||
StatusCode::BAD_REQUEST,
|
||||
AdminEnvelope::new(
|
||||
40001,
|
||||
"Account label must be 64 characters or fewer",
|
||||
(),
|
||||
request_id,
|
||||
),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let status = match parse_import_status(payload.status.as_deref()) {
|
||||
Ok(status) => status,
|
||||
Err(message) => {
|
||||
return AdminResponse::new(
|
||||
StatusCode::BAD_REQUEST,
|
||||
AdminEnvelope::new(40001, message, (), request_id),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
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.account_repository() else {
|
||||
return AdminResponse::new(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
AdminEnvelope::new(
|
||||
50001,
|
||||
"Account repository is not initialized",
|
||||
(),
|
||||
request_id,
|
||||
),
|
||||
)
|
||||
.into_response();
|
||||
};
|
||||
|
||||
let id = normalized_account_id(payload.id);
|
||||
match repo.exists(&id).await {
|
||||
Ok(true) => {
|
||||
return AdminResponse::new(
|
||||
StatusCode::CONFLICT,
|
||||
AdminEnvelope::new(40901, "Account already exists", (), request_id),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Ok(false) => {}
|
||||
Err(_) => {
|
||||
return AdminResponse::new(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
AdminEnvelope::new(50001, "Failed to inspect account", (), request_id),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
|
||||
let email = empty_to_none(payload.email);
|
||||
let account_id = empty_to_none(payload.account_id);
|
||||
let user_id = empty_to_none(payload.user_id);
|
||||
let label = empty_to_none(payload.label);
|
||||
let plan_type = empty_to_none(payload.plan_type);
|
||||
let refresh_token = empty_to_none(payload.refresh_token);
|
||||
let now = Utc::now().to_rfc3339();
|
||||
let pool_account = Account {
|
||||
id: id.clone(),
|
||||
email: email.clone(),
|
||||
account_id: account_id.clone(),
|
||||
user_id: user_id.clone(),
|
||||
label: label.clone(),
|
||||
plan_type: plan_type.clone(),
|
||||
access_token: access_token.to_string(),
|
||||
refresh_token: refresh_token.clone(),
|
||||
access_token_expires_at: None,
|
||||
status,
|
||||
quota_limit_reached: false,
|
||||
quota_cooldown_until: None,
|
||||
cloudflare_cooldown_until: None,
|
||||
added_at: now.clone(),
|
||||
last_used_at: None,
|
||||
};
|
||||
let account = NewAccount {
|
||||
id: id.clone(),
|
||||
email: email.clone(),
|
||||
account_id: account_id.clone(),
|
||||
user_id: user_id.clone(),
|
||||
label: label.clone(),
|
||||
plan_type: plan_type.clone(),
|
||||
access_token: SecretString::new(access_token.to_string().into()),
|
||||
refresh_token: refresh_token.map(|token| SecretString::new(token.into())),
|
||||
access_token_expires_at: None,
|
||||
status,
|
||||
};
|
||||
if repo.insert(account).await.is_err() {
|
||||
return AdminResponse::new(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
AdminEnvelope::new(50001, "Failed to create account", (), request_id),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
state.account_pool().lock().await.insert(pool_account);
|
||||
|
||||
// 手动添加账号的响应只返回可展示元数据,OAuth token 永不回显。
|
||||
AdminResponse::new(
|
||||
StatusCode::OK,
|
||||
AdminEnvelope::ok(
|
||||
AdminAccountData {
|
||||
id,
|
||||
email,
|
||||
account_id,
|
||||
user_id,
|
||||
label,
|
||||
plan_type,
|
||||
status: account_status_value(status).to_string(),
|
||||
access_token_expires_at: None,
|
||||
added_at: now.clone(),
|
||||
updated_at: now,
|
||||
},
|
||||
request_id,
|
||||
),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
pub async fn update_account_label(
|
||||
State(state): State<AppState>,
|
||||
Extension(request_id): Extension<RequestId>,
|
||||
|
||||
@@ -930,6 +930,132 @@ async fn admin_accounts_export_should_return_sub2api_openai_oauth_payload_withou
|
||||
assert!(body["data"]["accounts"][0].get("proxyUrl").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn admin_account_manual_add_should_store_encrypted_token_and_sync_runtime_pool() {
|
||||
let (app, state, pool, _dir) =
|
||||
admin_accounts_test_app("admin-account-manual-add.sqlite", 26).await;
|
||||
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/admin/accounts")
|
||||
.header("content-type", "application/json")
|
||||
.header("cookie", "cpr_admin_session=session_1")
|
||||
.body(Body::from(
|
||||
json!({
|
||||
"id": "acct_manual",
|
||||
"email": "manual@example.com",
|
||||
"accountId": "chatgpt-account",
|
||||
"userId": "chatgpt-user",
|
||||
"label": "Manual Team",
|
||||
"planType": "plus",
|
||||
"token": "manual-access-secret",
|
||||
"refreshToken": "manual-refresh-secret",
|
||||
"status": "active"
|
||||
})
|
||||
.to_string(),
|
||||
))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = response_json(response).await;
|
||||
assert_eq!(body["data"]["id"], "acct_manual");
|
||||
assert_eq!(body["data"]["label"], "Manual Team");
|
||||
assert_eq!(body["data"]["status"], "active");
|
||||
assert!(body["data"].get("token").is_none());
|
||||
assert!(body["data"].get("refreshToken").is_none());
|
||||
|
||||
let stored: (String, String, String, String) = sqlx::query_as(
|
||||
"select access_token_cipher, refresh_token_cipher, label, plan_type from accounts where id = ?",
|
||||
)
|
||||
.bind("acct_manual")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(stored.0.starts_with("v1:"));
|
||||
assert!(!stored.0.contains("manual-access-secret"));
|
||||
assert!(stored.1.starts_with("v1:"));
|
||||
assert!(!stored.1.contains("manual-refresh-secret"));
|
||||
assert_eq!(stored.2, "Manual Team");
|
||||
assert_eq!(stored.3, "plus");
|
||||
|
||||
let acquired = state
|
||||
.account_pool()
|
||||
.lock()
|
||||
.await
|
||||
.acquire("gpt-5.5")
|
||||
.unwrap();
|
||||
assert_eq!(acquired.id, "acct_manual");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn admin_account_manual_add_should_reject_empty_duplicate_or_invalid_accounts() {
|
||||
let (app, _state, _pool, _dir) =
|
||||
admin_accounts_test_app("admin-account-manual-add-invalid.sqlite", 27).await;
|
||||
|
||||
let empty_token = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/admin/accounts")
|
||||
.header("content-type", "application/json")
|
||||
.header("cookie", "cpr_admin_session=session_1")
|
||||
.body(Body::from(r#"{"token":""}"#))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(empty_token.status(), StatusCode::BAD_REQUEST);
|
||||
|
||||
import_test_account(&app, "session_1", "acct_duplicate").await;
|
||||
let duplicate = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/admin/accounts")
|
||||
.header("content-type", "application/json")
|
||||
.header("cookie", "cpr_admin_session=session_1")
|
||||
.body(Body::from(
|
||||
json!({
|
||||
"id": "acct_duplicate",
|
||||
"token": "access-duplicate"
|
||||
})
|
||||
.to_string(),
|
||||
))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(duplicate.status(), StatusCode::CONFLICT);
|
||||
|
||||
let invalid_status = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/admin/accounts")
|
||||
.header("content-type", "application/json")
|
||||
.header("cookie", "cpr_admin_session=session_1")
|
||||
.body(Body::from(
|
||||
json!({
|
||||
"id": "acct_invalid_status",
|
||||
"token": "access-invalid-status",
|
||||
"status": "pending"
|
||||
})
|
||||
.to_string(),
|
||||
))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(invalid_status.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
async fn admin_accounts_test_app(
|
||||
db_name: &str,
|
||||
key_byte: u8,
|
||||
|
||||
Reference in New Issue
Block a user