44 lines
1.5 KiB
Python
44 lines
1.5 KiB
Python
"""
|
||
通用依赖项模块,包含常用的FastAPI依赖项函数
|
||
"""
|
||
|
||
from fastapi import Depends, HTTPException, status
|
||
from fastapi.security import OAuth2PasswordBearer
|
||
from sqlalchemy.orm import Session
|
||
from typing import Optional
|
||
|
||
from app.models.database import get_db
|
||
from app.services.user import UserService
|
||
from app.schemas.user import UserResponse
|
||
|
||
# OAuth2密码Bearer
|
||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/users/login", auto_error=False)
|
||
|
||
|
||
async def get_current_active_user(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):
|
||
"""获取当前活跃用户"""
|
||
user = UserService.get_current_user(db, token)
|
||
if not user:
|
||
raise HTTPException(
|
||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||
detail="Could not validate credentials",
|
||
headers={"WWW-Authenticate": "Bearer"},
|
||
)
|
||
if hasattr(user, 'status') and user.status != "active":
|
||
raise HTTPException(status_code=400, detail="Inactive user")
|
||
return user
|
||
|
||
|
||
async def get_current_active_user_optional(db: Session = Depends(get_db), token: Optional[str] = Depends(oauth2_scheme)):
|
||
"""获取当前活跃用户(可选,未登录返回None)"""
|
||
if not token:
|
||
return None
|
||
try:
|
||
user = UserService.get_current_user(db, token)
|
||
if not user:
|
||
return None
|
||
if hasattr(user, 'status') and user.status != "active":
|
||
return None
|
||
return user
|
||
except:
|
||
return None |