|
| 1 | +""" |
| 2 | +[INPUT]: 依赖 jose, os, FastAPI |
| 3 | +[OUTPUT]: get_current_user 依赖函数, AuthUser 数据模型 |
| 4 | +[POS]: Supabase JWT 验证 |
| 5 | +[PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md |
| 6 | +""" |
| 7 | + |
| 8 | +import os |
| 9 | +from typing import Annotated |
| 10 | + |
| 11 | +from fastapi import Depends, HTTPException, status |
| 12 | +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer |
| 13 | +from jose import JWTError, jwt |
| 14 | +from pydantic import BaseModel |
| 15 | + |
| 16 | +# ============================================================================= |
| 17 | +# 配置 |
| 18 | +# ============================================================================= |
| 19 | + |
| 20 | +SUPABASE_JWT_SECRET = os.getenv("SUPABASE_JWT_SECRET", "") |
| 21 | +SUPABASE_URL = os.getenv("SUPABASE_URL", "") |
| 22 | + |
| 23 | +ALGORITHM = "HS256" |
| 24 | + |
| 25 | + |
| 26 | +# ============================================================================= |
| 27 | +# 数据模型 |
| 28 | +# ============================================================================= |
| 29 | + |
| 30 | + |
| 31 | +class AuthUser(BaseModel): |
| 32 | + """认证用户信息""" |
| 33 | + id: str |
| 34 | + email: str | None = None |
| 35 | + role: str = "authenticated" |
| 36 | + aud: str = "authenticated" |
| 37 | + |
| 38 | + |
| 39 | +# ============================================================================= |
| 40 | +# JWT 验证 |
| 41 | +# ============================================================================= |
| 42 | + |
| 43 | +security = HTTPBearer(auto_error=False) |
| 44 | + |
| 45 | + |
| 46 | +async def get_current_user( |
| 47 | + credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)], |
| 48 | +) -> AuthUser: |
| 49 | + """ |
| 50 | + 验证 Supabase JWT 并返回当前用户 |
| 51 | +
|
| 52 | + Args: |
| 53 | + credentials: HTTP Bearer Token |
| 54 | +
|
| 55 | + Returns: |
| 56 | + AuthUser: 当前用户信息 |
| 57 | +
|
| 58 | + Raises: |
| 59 | + HTTPException 401: Token 无效或缺失 |
| 60 | + """ |
| 61 | + if not credentials: |
| 62 | + raise HTTPException( |
| 63 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 64 | + detail="Missing authorization header", |
| 65 | + ) |
| 66 | + |
| 67 | + token = credentials.credentials |
| 68 | + |
| 69 | + try: |
| 70 | + payload = jwt.decode( |
| 71 | + token, |
| 72 | + SUPABASE_JWT_SECRET, |
| 73 | + algorithms=[ALGORITHM], |
| 74 | + options={"verify_aud": False}, |
| 75 | + ) |
| 76 | + except JWTError as e: |
| 77 | + raise HTTPException( |
| 78 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 79 | + detail=f"Invalid token: {str(e)}", |
| 80 | + ) from e |
| 81 | + |
| 82 | + user_id = payload.get("sub") |
| 83 | + if not user_id: |
| 84 | + raise HTTPException( |
| 85 | + status_code=status.HTTP_401_UNAUTHORIZED, |
| 86 | + detail="Token missing user id", |
| 87 | + ) |
| 88 | + |
| 89 | + return AuthUser( |
| 90 | + id=user_id, |
| 91 | + email=payload.get("email"), |
| 92 | + role=payload.get("role", "authenticated"), |
| 93 | + aud=payload.get("aud", "authenticated"), |
| 94 | + ) |
| 95 | + |
| 96 | + |
| 97 | +async def get_optional_user( |
| 98 | + credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)], |
| 99 | +) -> AuthUser | None: |
| 100 | + """ |
| 101 | + 可选的用户认证,不抛出异常 |
| 102 | +
|
| 103 | + Returns: |
| 104 | + AuthUser | None: 当前用户信息,未认证返回 None |
| 105 | + """ |
| 106 | + if not credentials: |
| 107 | + return None |
| 108 | + |
| 109 | + try: |
| 110 | + return await get_current_user(credentials) |
| 111 | + except HTTPException: |
| 112 | + return None |
| 113 | + |
| 114 | + |
| 115 | +# ============================================================================= |
| 116 | +# 类型别名 |
| 117 | +# ============================================================================= |
| 118 | + |
| 119 | +CurrentUser = Annotated[AuthUser, Depends(get_current_user)] |
| 120 | +OptionalUser = Annotated[AuthUser | None, Depends(get_optional_user)] |
0 commit comments