Spaces:
Runtime error

File size: 5,213 Bytes
c0be5f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
@router /api/auth
@description 授权路由模块
@author wjh
@created at 2025-11-6
"""
import jwt
from config.security import JWT_SECRET, create_token, blacklist_token, is_token_blacklisted
from fastapi import APIRouter, HTTPException, Header, Depends
import time
from schemas.auth_schema import WeChatLoginRequest, PhoneBindRequest, PhoneLoginRequest
from service import auth_service
from models.user_model import User
from dependencies.auth import get_current_user

router = APIRouter()

# 微信登录路由 (wechat login)
@router.post("/wx_login")
async def wx_login(data: WeChatLoginRequest):
    try:
        user_data = await auth_service.process_wx_login(data)
        return {"success": True, "data": user_data}
    except (ValueError, ConnectionError) as e:
        raise HTTPException(status_code=400, detail=str(e)) from e
    except Exception as e:
        # Log the exception for debugging
        print(f"An unexpected error occurred during wx_login: {e}")
        raise HTTPException(status_code=500, detail=f"服务器内部错误: {e}") from e

# 绑定手机号路由 (phone bind)
@router.post("/bind_phone")
async def bind_phone(data: PhoneBindRequest, authorization: str | None = Header(None)):
    if not authorization or not authorization.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="未认证:缺少 Bearer Token")
    token = authorization.split(" ", 1)[1]
    try:
        payload = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])
        openid = payload.get("openid")
        if not openid:
            raise HTTPException(status_code=401, detail="令牌无效:缺少 openid")
    except jwt.PyJWTError as exc:
        raise HTTPException(status_code=401, detail="令牌解析失败") from exc

    result = await auth_service.process_bind_phone(data, openid)
    return {"success": True, "message": "手机号绑定成功", "data": result}

# 手机号登录路由 (phonenumber login)
@router.post("/phone_login")
async def phone_login(data: PhoneLoginRequest):
    try:
        user_data = await auth_service.process_phone_login(data)
        return {"success": True, "data": user_data}
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e)) from e
    except Exception as e:
        # Log the exception for debugging
        print(f"An unexpected error occurred during phone_login: {e}")
        raise HTTPException(status_code=400, detail=str(e)) from e

# 刷新令牌(refresh token)
@router.post("/refresh")
async def refresh_token(authorization: str | None = Header(None)):
    if not authorization or not authorization.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="未认证:缺少 Bearer Token")
    token = authorization.split(" ", 1)[1]
    try:
        # 黑名单检查
        if is_token_blacklisted(token):
            raise HTTPException(status_code=401, detail="令牌已失效")
        payload = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])  # 验证当前令牌有效
        openid = payload.get("openid")
        if not openid:
            raise HTTPException(status_code=401, detail="令牌无效:缺少 openid")
        new_token = create_token(openid)
        expires_at = int(time.time()) + 60 * 60 * 24
        return {"success": True, "token": new_token, "expires_at": expires_at}
    except jwt.ExpiredSignatureError:
        # 过期令牌不可刷新(安全起见);前端需重新登录
        raise HTTPException(status_code=401, detail="令牌已过期,无法刷新") 
    except jwt.PyJWTError as exc:
        raise HTTPException(status_code=401, detail="令牌解析失败") from exc

# 校验令牌(validate token)
@router.get("/validate")
async def validate_token(authorization: str | None = Header(None)):
    if not authorization or not authorization.startswith("Bearer "):
        return {"valid": False, "reason": "missing_token"}
    token = authorization.split(" ", 1)[1]
    try:
        payload = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])  # 验证有效性与过期
        return {"valid": True, "payload": {"openid": payload.get("openid"), "exp": payload.get("exp")}}
    except jwt.ExpiredSignatureError:
        return {"valid": False, "reason": "expired"}
    except jwt.PyJWTError:
        return {"valid": False, "reason": "invalid"}

@router.get("/me")
async def get_me(current_user: User = Depends(get_current_user)):
    return {
        "success": True,
        "data": {
            "id": current_user.id,
            "openid": current_user.openid,
            "nickname": current_user.nickname or "",
            "avatarUrl": current_user.avatar_url or "",
            "phone_number": current_user.phone_number or ""
        }
    }

# 登出(logout):示例为无状态登出,前端清除令牌
@router.post("/logout")
async def logout(authorization: str | None = Header(None)):
    # 服务端不维护持久会话;可选将当前令牌加入内存黑名单
    token = None
    if authorization and authorization.startswith("Bearer "):
        token = authorization.split(" ", 1)[1]
    if token:
        blacklist_token(token)
    return {"success": True}