Files
algorithm/backend/app/dependencies.py
2026-02-18 09:36:18 +08:00

44 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
通用依赖项模块包含常用的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