23 lines
865 B
Python
23 lines
865 B
Python
"""FastAPI 通用依赖:当前用户。"""
|
|
from fastapi import Depends, HTTPException
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from sqlalchemy.orm import Session
|
|
|
|
from ..database import get_db
|
|
from ..models import User
|
|
from .security import decode_token
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
|
|
|
|
|
|
def get_current_user(token: str | None = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User:
|
|
if not token:
|
|
raise HTTPException(status_code=401, detail="未登录")
|
|
payload = decode_token(token)
|
|
if not payload:
|
|
raise HTTPException(status_code=401, detail="登录已过期,请重新登录")
|
|
user = db.get(User, int(payload["sub"]))
|
|
if not user or not user.is_active:
|
|
raise HTTPException(status_code=401, detail="用户不存在或已禁用")
|
|
return user
|