30 lines
882 B
Python
30 lines
882 B
Python
"""FastAPI 依赖:数据库 session、当前登录用户。"""
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.db import get_db
|
|
from app.models.user import User
|
|
from app.services.security import decode_access_token
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
|
|
|
|
_CRED_EXC = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="无效或过期的凭证",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
|
|
async def get_current_user(
|
|
token: str = Depends(oauth2_scheme),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> User:
|
|
user_id = decode_access_token(token)
|
|
if not user_id:
|
|
raise _CRED_EXC
|
|
user = await db.get(User, user_id)
|
|
if user is None or not user.is_active:
|
|
raise _CRED_EXC
|
|
return user
|