From da4af50b4578e21b22abc04cfaff23c6c47b0fd5 Mon Sep 17 00:00:00 2001 From: milky0217 Date: Mon, 25 May 2026 16:27:01 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20mock=5Flogin=E6=94=AF=E6=8C=81X-Mock-Key?= =?UTF-8?q?=E8=AF=B7=E6=B1=82=E5=A4=B4=E9=89=B4=E6=9D=83=20+=20deploy?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E9=85=8D=E7=BD=AE=E9=9A=8F=E6=9C=BA=E5=AF=86?= =?UTF-8?q?=E9=92=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/common.sh | 11 +++++++++++ src/handlers/auth.rs | 18 +++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/lib/common.sh b/lib/common.sh index efc49b0..2cc6360 100644 --- a/lib/common.sh +++ b/lib/common.sh @@ -106,6 +106,17 @@ deploy_service_file() { fi rsync -avzP "$(get_service_file_local)" "${REMOTE_USER}@${REMOTE_HOST}:/etc/systemd/system/${SERVICE_NAME}" + + # 开发环境自动配置 mock login(带随机密钥) + if [ "${APP_ENV}" = "development" ]; then + local has_mock; has_mock=$(remote "grep -c 'MOCK_LOGIN_ENABLED' /etc/systemd/system/${SERVICE_NAME} 2>/dev/null || echo 0") + if [ "$has_mock" = "0" ]; then + local mock_key; mock_key=$(openssl rand -base64 12 2>/dev/null | tr -d '\n' || echo "dev-mock-$(date +%s)") + remote "sed -i '/^\[Service\]/a Environment=MOCK_LOGIN_ENABLED=true\nEnvironment=MOCK_LOGIN_KEY=${mock_key}' /etc/systemd/system/${SERVICE_NAME}" + log_info "自动配置 MOCK_LOGIN_ENABLED=true, MOCK_LOGIN_KEY=${mock_key}" + fi + fi + remote "systemctl daemon-reload" log_info "service 文件部署完成,使用 systemctl restart ${SERVICE_NAME} 重启" } diff --git a/src/handlers/auth.rs b/src/handlers/auth.rs index 5e15ecd..d985a80 100644 --- a/src/handlers/auth.rs +++ b/src/handlers/auth.rs @@ -231,18 +231,34 @@ pub struct MockLoginResponse { /// GET /api/mock-login /// 沙箱测试用:无需微信 code,直接返回 JWT -/// 通过环境变量 MOCK_LOGIN_ENABLED 控制是否启用 +/// 通过环境变量 MOCK_LOGIN_ENABLED + MOCK_LOGIN_KEY 控制启用 +/// MOCK_LOGIN_ENABLED=true 且未设 MOCK_LOGIN_KEY:任何请求可用(不安全) +/// MOCK_LOGIN_ENABLED=true 且设了 MOCK_LOGIN_KEY:需携带 X-Mock-Key 请求头 #[get("/api/mock-login")] pub async fn mock_login( pool: web::Data, query: web::Query, app_state: web::Data, + req: HttpRequest, ) -> impl Responder { // 检查是否启用 if std::env::var("MOCK_LOGIN_ENABLED").ok() != Some("true".to_string()) { return HttpResponse::NotFound().json(ErrorResponse::<()>::error("模拟登录未启用")); } + // 如果设置了 MOCK_LOGIN_KEY,验证请求头 + if let Ok(key) = std::env::var("MOCK_LOGIN_KEY") { + if !key.is_empty() { + let header_key = req.headers() + .get("X-Mock-Key") + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + if header_key != key { + return HttpResponse::Forbidden().json(ErrorResponse::<()>::error("模拟登录密钥错误")); + } + } + } + let user_id = match query.user_id { Some(id) => { // 验证用户存在