36 lines
1.1 KiB
Python
36 lines
1.1 KiB
Python
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
from app.core.database import get_db
|
|
from app.core.security import decode_token
|
|
from app.models.user import User
|
|
|
|
bearer = HTTPBearer(auto_error=True)
|
|
|
|
|
|
async def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials = Depends(bearer),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> User:
|
|
token = credentials.credentials
|
|
payload = decode_token(token)
|
|
|
|
if payload is None or payload.get("type") != "access":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Token 无效或已过期",
|
|
)
|
|
|
|
user_id = int(payload["sub"])
|
|
result = await db.execute(select(User).where(User.id == user_id))
|
|
user = result.scalar_one_or_none()
|
|
|
|
if user is None or not user.is_active:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="用户不存在或已被禁用",
|
|
)
|
|
|
|
return user
|