分页总数(#5): - get_all_tasks 的 total 原为 len(flat_tasks)(当前页条数),移动端 「我的任务」用 tasks.length < total 判断 hasMore,首页满员时恒为 false,列表永远停在第一页 20 条。改为独立 COUNT 查询(与 notifications.py 已有写法保持一致)。 可观测性(#9): - 新增 core/logging.py:单行 JSON 结构化日志 + request_id/user 上下文 注入;零第三方依赖;接管 uvicorn 自带 handler 避免格式绕过。 - 新增 core/middleware.py:RequestContextMiddleware 生成/透传 X-Request-ID 并回写响应头,输出含耗时/用户的结构化访问日志。 - 新增 core/health.py:拆分存活/就绪探针。/health/live 不触依赖; /health/ready 探主库,不可用返回 503;MOM 挂掉仅降级不摘流量。 - main.py:全局异常处理器只把堆栈写日志,响应体仅回 request_id; 接入可选 Sentry(未装 SDK 时静默跳过)。 - auth_service:解析 Token 后写入 user 上下文,日志自动带操作人。 注:异常处理器由 ServerErrorMiddleware 调用,此时 contextvar 已被重置, 故 request_id 同时写入 request.state(由 ASGI scope 承载)再读取。 已用 TestClient 验证:探针状态码/检查项、X-Request-ID 透传与生成、 500 响应携带可对账的 request_id 且不泄露堆栈。
140 lines
4.5 KiB
Python
140 lines
4.5 KiB
Python
"""认证服务 — 对接 MOM 系统 sys_user 表 + Track 自有 JWT(双 Token 架构)"""
|
||
from fastapi import HTTPException, status, Depends
|
||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||
from jose import JWTError, jwt
|
||
from werkzeug.security import check_password_hash
|
||
|
||
from app.core.config import settings
|
||
from app.core.security import (
|
||
create_access_token,
|
||
create_refresh_token,
|
||
decode_token,
|
||
ALGORITHM,
|
||
TOKEN_TYPE_ACCESS,
|
||
TOKEN_TYPE_REFRESH,
|
||
)
|
||
from app.core.mom_database import MomSessionLocal
|
||
from app.core.logging import user_var
|
||
from app.schemas.user import LoginResponse, UserResponse
|
||
|
||
security = HTTPBearer()
|
||
|
||
|
||
def login(username: str, password: str) -> LoginResponse:
|
||
"""登录 — 签发双 Token(Access + Refresh)"""
|
||
db = MomSessionLocal()
|
||
try:
|
||
# 1. 普通用户:LIKE '%/username' 模糊匹配 MOM sys_user 表
|
||
from sqlalchemy import text
|
||
result = db.execute(
|
||
text(
|
||
"SELECT id, username, department, role, password_hash "
|
||
"FROM sys_user "
|
||
"WHERE username LIKE :pattern"
|
||
),
|
||
{"pattern": f"%/{username}"},
|
||
)
|
||
row = result.fetchone()
|
||
|
||
if not row:
|
||
raise HTTPException(
|
||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||
detail="用户名或密码错误",
|
||
)
|
||
|
||
user_id, full_username, department, role, password_hash = row
|
||
|
||
# 2. Werkzeug scrypt 密码验证
|
||
if not check_password_hash(password_hash, password):
|
||
raise HTTPException(
|
||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||
detail="用户名或密码错误",
|
||
)
|
||
|
||
# 3. 解析 display_name("张三/zhangsan01" → "张三")
|
||
display_name = full_username.split("/")[0] if "/" in full_username else full_username
|
||
|
||
token_data = {
|
||
"sub": str(user_id),
|
||
"role": role or "operator",
|
||
"username": username,
|
||
"display_name": display_name,
|
||
}
|
||
|
||
return LoginResponse(
|
||
access_token=create_access_token(data=token_data),
|
||
refresh_token=create_refresh_token(data=token_data),
|
||
user=UserResponse(
|
||
id=str(user_id),
|
||
username=username,
|
||
display_name=display_name,
|
||
role=role or "operator",
|
||
),
|
||
)
|
||
|
||
finally:
|
||
db.close()
|
||
|
||
|
||
def refresh_access_token(refresh_token: str) -> dict:
|
||
"""
|
||
使用 Refresh Token 换取新的 Access Token。
|
||
校验:
|
||
1. Token 签名是否有效
|
||
2. Token type 是否为 "refresh"
|
||
3. Token 是否未过期
|
||
"""
|
||
try:
|
||
payload = decode_token(refresh_token)
|
||
except JWTError:
|
||
raise HTTPException(
|
||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||
detail="Refresh Token 无效或已过期,请重新登录",
|
||
)
|
||
|
||
# 校验 token 类型
|
||
if payload.get("type") != TOKEN_TYPE_REFRESH:
|
||
raise HTTPException(
|
||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||
detail="无效的 Token 类型,仅接受 Refresh Token",
|
||
)
|
||
|
||
# 提取用户信息,签发新的 Access Token
|
||
access_token = create_access_token(
|
||
data={
|
||
"sub": payload.get("sub"),
|
||
"role": payload.get("role", "operator"),
|
||
"username": payload.get("username", ""),
|
||
"display_name": payload.get("display_name", ""),
|
||
}
|
||
)
|
||
|
||
return {"access_token": access_token, "token_type": "bearer"}
|
||
|
||
|
||
async def get_current_user(
|
||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||
) -> dict:
|
||
"""从 Bearer Token 解析当前用户(仅接受 Access Token)"""
|
||
token = credentials.credentials
|
||
try:
|
||
payload = decode_token(token)
|
||
user_id = payload.get("sub")
|
||
if not user_id:
|
||
raise HTTPException(status_code=401, detail="无效的 Token")
|
||
|
||
# 校验:仅接受 access token
|
||
if payload.get("type") == TOKEN_TYPE_REFRESH:
|
||
raise HTTPException(
|
||
status_code=401,
|
||
detail="请使用 Access Token 访问 API,Refresh Token 仅用于刷新",
|
||
)
|
||
|
||
# 注入日志上下文:此后本请求的所有日志都会自动带上操作人。
|
||
# username 即 assignee_id 口径,排查「谁干了什么」时比数字 id 直观得多。
|
||
user_var.set(payload.get("username") or user_id)
|
||
|
||
return payload
|
||
except JWTError:
|
||
raise HTTPException(status_code=401, detail="无效的 Token")
|