prepare backend-only fastapi deployment

This commit is contained in:
刘金宝
2026-06-01 17:32:18 +08:00
parent 338e2c8e1d
commit 132155c280
59 changed files with 374 additions and 9155 deletions
+89 -9
View File
@@ -22,6 +22,20 @@ class AuthenticatedUser:
display_name: str | None = None
tenant_id: str | None = None
role: str | None = None
phone: str | None = None
avatar: str | None = None
gender: int | None = None
institution_id: int | None = None
institution_name: str | None = None
department_id: int | None = None
department_name: str | None = None
title_name: str | None = None
major: str | None = None
training_stage: str | None = None
learning_target: str | None = None
current_level: str | None = None
status: int | None = None
profile: dict[str, Any] | None = None
class ExternalAuthService:
@@ -36,7 +50,7 @@ class ExternalAuthService:
outbound_headers = self._build_forward_headers(request)
if not outbound_headers:
raise AppError("AUTH_CREDENTIAL_REQUIRED", "Authorization or Cookie is required", 401)
raise AppError("AUTH_CREDENTIAL_REQUIRED", "Authorization header is required", 401)
cache_key = self._cache_key(outbound_headers)
cached = self._read_cache(cache_key)
@@ -64,16 +78,14 @@ class ExternalAuthService:
return user
def _build_forward_headers(self, request: Request) -> dict[str, str]:
"""认证转发:只透传鉴权必要 Header,避免把无关内部头转发给用户中心。"""
"""认证转发:只透传 Bearer token,避免把无关内部头转发给用户中心。"""
headers: dict[str, str] = {}
authorization = request.headers.get("Authorization")
cookie = request.headers.get("Cookie")
if authorization:
authorization = authorization.strip()
if authorization and " " not in authorization:
authorization = f"Bearer {authorization}"
headers["Authorization"] = authorization
if cookie:
headers["Cookie"] = cookie
if request.headers.get("X-CSRFToken"):
headers["X-CSRFToken"] = request.headers["X-CSRFToken"]
return headers
def _parse_user(self, payload: dict[str, Any]) -> AuthenticatedUser:
@@ -82,18 +94,69 @@ class ExternalAuthService:
user_id = self._first_present(data, ["id", "user_id", "uid", "pk", "uuid"])
if user_id is None:
raise AppError("AUTH_USER_PARSE_FAILED", "auth user id is missing", 502)
status = self._to_int(data.get("status"))
if status == 0:
raise AppError("AUTH_USER_DISABLED", "current user is disabled", 403)
username = self._first_present(data, ["username", "account", "mobile", "phone"])
display_name = self._first_present(data, ["display_name", "name", "nickname", "real_name"])
role = self._first_present(data, ["role", "user_role"])
tenant_id = self._first_present(data, ["tenant_id", "org_id", "organization_id"])
role = self._first_present(data, ["role_type", "role", "user_role"])
institution_id = self._to_int(data.get("institution"))
tenant_id = str(institution_id) if institution_id is not None else None
profile = self._build_profile(data)
return AuthenticatedUser(
user_id=str(user_id),
username=str(username) if username is not None else None,
display_name=str(display_name) if display_name is not None else None,
role=str(role) if role is not None else None,
tenant_id=str(tenant_id) if tenant_id is not None else None,
phone=self._to_str(data.get("phone")),
avatar=self._to_str(data.get("avatar")),
gender=self._to_int(data.get("gender")),
institution_id=institution_id,
institution_name=self._to_str(data.get("institution_name")),
department_id=self._to_int(data.get("department")),
department_name=self._to_str(data.get("department_name")),
title_name=self._to_str(data.get("title_name")),
major=self._to_str(data.get("major")),
training_stage=self._to_str(data.get("training_stage")),
learning_target=self._to_str(data.get("learning_target")),
current_level=self._to_str(data.get("current_level")),
status=status,
profile=profile,
)
def _build_profile(self, data: dict[str, Any]) -> dict[str, Any]:
"""用户画像:按 Django `/me` 字段白名单保留学习画像,供前端和后续 Agent 个性化使用。"""
keys = [
"id",
"username",
"real_name",
"phone",
"avatar",
"gender",
"role_type",
"institution",
"institution_name",
"department",
"department_name",
"title_name",
"major",
"training_stage",
"learning_target",
"competency_profile",
"weak_dimensions",
"strong_dimensions",
"ai_preference",
"total_training_count",
"total_case_count",
"current_level",
"status",
"last_login_time",
"created_at",
"updated_at",
]
return {key: data.get(key) for key in keys if key in data}
@staticmethod
def _first_present(data: dict[str, Any], keys: list[str]) -> Any:
"""用户解析:按优先级读取第一个非空字段。"""
@@ -103,6 +166,23 @@ class ExternalAuthService:
return value
return None
@staticmethod
def _to_int(value: Any) -> int | None:
"""用户解析:把 Django 返回的数字字段稳定转成 int,空值保持 None。"""
if value is None or value == "":
return None
try:
return int(value)
except (TypeError, ValueError):
return None
@staticmethod
def _to_str(value: Any) -> str | None:
"""用户解析:把可展示字段转成字符串,空值保持 None。"""
if value is None or value == "":
return None
return str(value)
@staticmethod
def _cache_key(headers: dict[str, str]) -> str:
"""认证缓存:基于鉴权凭证生成不可逆缓存键,避免保存明文 token。"""