auth.py
4.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
"""认证路由:登录 / 登出 / 当前用户 / 自助改密。"""
import asyncio
import logging
from fastapi import APIRouter, Body, Depends, HTTPException, Response, status
from config import JWT_EXPIRE_HOURS
from src.database.models import WikiPosition, WikiUser
from src.database.session import AsyncSessionLocal
from src.services.identity.local import build_password_fields, get_identity_provider, verify_password
from src.services.identity.tokens import COOKIE_NAME, create_access_token, get_current_user
from src.services.memory.profile_gen import ensure_profile_on_login
logger = logging.getLogger(__name__)
router = APIRouter()
async def _user_payload(user: WikiUser) -> dict:
"""组装返回给前端的用户信息(含岗位名,供顶部展示)。"""
position_name = None
if user.position_id:
async with AsyncSessionLocal() as session:
position = await session.get(WikiPosition, user.position_id)
if position is not None:
position_name = position.name
return {
"id": user.id,
"username": user.username,
"displayName": user.display_name,
"phone": user.phone,
"role": user.role,
"positionId": user.position_id,
"positionName": position_name,
"storeName": user.store_name,
}
@router.post("/auth/login")
async def login(response: Response, data: dict = Body(...)):
"""账号(手机号)+ 密码登录,成功后种下 httpOnly cookie。"""
account = (data.get("account") or "").strip()
password = data.get("password") or ""
if not account or not password:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="账号和密码不能为空")
provider = get_identity_provider()
user = await provider.authenticate(account, password)
if user is None:
# 不区分「账号不存在」与「密码错误」,避免账号枚举
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="账号或密码错误")
token = create_access_token(user)
response.set_cookie(
key=COOKIE_NAME,
value=token,
httponly=True,
samesite="lax",
max_age=JWT_EXPIRE_HOURS * 3600,
path="/",
)
# 首登画像生成:异步执行,不阻塞登录响应。
# 生成完成前画像段落为空,不影响问答可用性。
asyncio.create_task(ensure_profile_on_login(user.id))
payload = await _user_payload(user)
logger.info("[Auth] 登录成功: %s", user.username)
return {"success": True, "user": payload, "token": token}
@router.post("/auth/logout")
async def logout(response: Response):
"""登出:清除 cookie。
注意:本轮未引入 token 黑名单,已签发的 token 在有效期内理论上仍可用。
这是不引入 Redis 的已知取舍,通过缩短 JWT_EXPIRE_HOURS 控制风险窗口。
"""
response.delete_cookie(key=COOKIE_NAME, path="/")
return {"success": True}
@router.get("/auth/me")
async def me(user: WikiUser = Depends(get_current_user)):
"""返回当前登录用户信息。"""
return {"success": True, "user": await _user_payload(user)}
@router.post("/auth/change-password")
async def change_password(
data: dict = Body(...),
user: WikiUser = Depends(get_current_user),
):
"""用户自助改密:需校验旧密码。"""
old_password = data.get("oldPassword") or ""
new_password = data.get("newPassword") or ""
if not old_password or not new_password:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="旧密码和新密码不能为空")
if len(new_password) < 6:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="新密码长度不能少于 6 位")
if new_password == old_password:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="新密码不能与旧密码相同")
if not verify_password(old_password, user.password_salt, user.password_hash):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="旧密码错误")
password_hash, password_salt = build_password_fields(new_password)
async with AsyncSessionLocal() as session:
db_user = await session.get(WikiUser, user.id)
if db_user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
db_user.password_hash = password_hash
db_user.password_salt = password_salt
await session.commit()
logger.info("[Auth] 用户自助修改密码: %s", user.username)
return {"success": True}