64 lines
1.7 KiB
Python
64 lines
1.7 KiB
Python
|
|
"""
|
||
|
|
依赖注入
|
||
|
|
"""
|
||
|
|
from typing import Generator, Optional
|
||
|
|
from fastapi import Depends, HTTPException, status
|
||
|
|
from fastapi.security import OAuth2PasswordBearer
|
||
|
|
from sqlalchemy.orm import Session
|
||
|
|
from ..core.database import get_db
|
||
|
|
from ..core.security import verify_token
|
||
|
|
from ..models.user import User, UserRole
|
||
|
|
|
||
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
|
||
|
|
|
||
|
|
|
||
|
|
def get_current_user(
|
||
|
|
db: Session = Depends(get_db),
|
||
|
|
token: str = Depends(oauth2_scheme)
|
||
|
|
) -> User:
|
||
|
|
"""
|
||
|
|
获取当前登录用户
|
||
|
|
"""
|
||
|
|
credentials_exception = HTTPException(
|
||
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||
|
|
detail="Could not validate credentials",
|
||
|
|
headers={"WWW-Authenticate": "Bearer"},
|
||
|
|
)
|
||
|
|
|
||
|
|
user_id = verify_token(token)
|
||
|
|
if user_id is None:
|
||
|
|
raise credentials_exception
|
||
|
|
|
||
|
|
user = db.query(User).filter(User.id == int(user_id)).first()
|
||
|
|
if user is None:
|
||
|
|
raise credentials_exception
|
||
|
|
|
||
|
|
if not user.is_active:
|
||
|
|
raise HTTPException(status_code=400, detail="Inactive user")
|
||
|
|
|
||
|
|
return user
|
||
|
|
|
||
|
|
|
||
|
|
def get_current_admin(current_user: User = Depends(get_current_user)) -> User:
|
||
|
|
"""
|
||
|
|
获取当前管理员用户
|
||
|
|
"""
|
||
|
|
if current_user.role != UserRole.ADMIN:
|
||
|
|
raise HTTPException(
|
||
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
||
|
|
detail="Not enough permissions"
|
||
|
|
)
|
||
|
|
return current_user
|
||
|
|
|
||
|
|
|
||
|
|
def get_current_streamer(current_user: User = Depends(get_current_user)) -> User:
|
||
|
|
"""
|
||
|
|
获取当前主播用户
|
||
|
|
"""
|
||
|
|
if current_user.role not in [UserRole.STREAMER, UserRole.ADMIN]:
|
||
|
|
raise HTTPException(
|
||
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
||
|
|
detail="Not a streamer"
|
||
|
|
)
|
||
|
|
return current_user
|