This commit is contained in:
gr
2026-11-04 10:14:23 +08:00
parent f7f323462c
commit b7c3a962dd
759 changed files with 74649 additions and 4421 deletions
+42 -6
View File
@@ -49,6 +49,8 @@ import knowledge_api
import remote_api
import zyt_auth
import group_sso
import group_access
import group_authorization
# 账号下拉框里「全部」的取值。用 -1 而不是 0:0 早就有含义了(旧版未归属数据),
# 而"不传"在 FastAPI 里就是 None,同样已经被占用。
@@ -64,7 +66,7 @@ DEV_ORIGINS = [
# ── 请求体 ───────────────────────────────────────────────────────────────────
class LoginBody(BaseModel):
username: str
password: str
password: str = Field(repr=False)
device_name: str = "web"
@@ -370,10 +372,12 @@ def create_app(
release_directory = database.path.parent / "releases"
release_directory.mkdir(parents=True, exist_ok=True)
app = FastAPI(title="企微客服助手管理 API", version="2.0")
group_access_snapshot = group_access.AccessSnapshot(database)
group_authorization_service = group_authorization.GroupAuthorization(database)
@app.exception_handler(RequestValidationError)
async def safe_group_validation(request: Request, exc: RequestValidationError):
if request.url.path == "/api/v2/auth/group/exchange":
if request.url.path in {"/api/v2/auth/group/exchange", "/api/v2/auth/login"}:
# Pydantic's default error projection includes the submitted input.
return JSONResponse(status_code=422, content={"detail": "集团登录请求无效,请重新登录"})
return await request_validation_exception_handler(request, exc)
@@ -386,7 +390,7 @@ def create_app(
# callback codes in the ASGI scope later used by access logging.
request.scope["query_string"] = b""
response = await call_next(request)
if path == "/auth/group-login" or path.startswith("/api/v2/auth/group/"):
if path in {"/auth/group-login", "/api/v2/auth/login"} or path.startswith("/api/v2/auth/group/"):
response.headers["Cache-Control"] = "no-store"
response.headers["Referrer-Policy"] = "no-referrer"
return response
@@ -698,6 +702,22 @@ def create_app(
)
return {"ok": True}
@app.post("/api/v2/group/access-snapshot")
async def group_access_metadata(request: Request):
# Machine credentials only: no human login/enrollment or authorization
# mutation is reachable from this dedicated read-only projection.
return await group_access.handle_request(request, group_access_snapshot)
@app.post("/api/v2/group/access-options")
async def group_authorization_options(request: Request):
return await group_authorization.handle_request(
request, group_authorization_service, group_authorization.OPTIONS_PATH)
@app.post("/api/v2/group/access-update")
async def group_authorization_update(request: Request):
return await group_authorization.handle_request(
request, group_authorization_service, group_authorization.UPDATE_PATH)
# ── 管理端认证 ───────────────────────────────────────────────────────
@app.get("/api/v2/auth/group/config")
async def group_config() -> dict:
@@ -733,22 +753,38 @@ def create_app(
if not backend.LOGIN_LIMITER.allowed(key):
raise HTTPException(status_code=429, detail="登录失败次数过多,请稍后再试")
user = database.authenticate(body.username, body.password)
group_login = False
if user is None:
config = group_sso.GroupPasswordConfig.from_env()
if config is not None:
try:
identity = await asyncio.to_thread(
group_sso.password_login, config, body.username, body.password,
)
user = await asyncio.to_thread(database.group_sso_user, identity)
group_login = True
except ValueError:
# Includes remote failures and locally disabled bindings.
# Do not reflect upstream responses, URLs, or credentials.
user = None
if not user:
backend.LOGIN_LIMITER.failure(key)
database.audit(None, "login.failed", f"username={body.username}", ip)
raise HTTPException(status_code=401, detail="用户名或密码不正确")
backend.LOGIN_LIMITER.success(key)
lifetime = 8 * 3600 if group_login else 30 * 86400
token, _ = database.create_token(
int(user["id"]), "api", body.device_name, 30 * 86400
int(user["id"]), "api", body.device_name, lifetime
)
database.audit(int(user["id"]), "login.api", body.device_name, ip)
database.audit(int(user["id"]), "login.group" if group_login else "login.api",
"provider=zyt_group" if group_login else body.device_name, ip)
principal = Principal(user, database.permissions_for_user(int(user["id"])))
# 首次登录不拦 API:改密页面本身也要调接口。前端凭
# must_change_password 把用户锁在改密页上,比后端一刀切 403 好用得多
# ——老实现那样连改密接口都调不通,只能去网页后台改。
return {
"access_token": token,
"expires_in": 30 * 86400,
"expires_in": lifetime,
"user": principal.payload(),
}