39 lines
1.3 KiB
Python
39 lines
1.3 KiB
Python
from typing import Dict, Any
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
|
|
from .db import get_user_by_username
|
|
from .security import safe_decode_token, TokenError
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
|
|
|
|
|
|
def get_current_user(token: str = Depends(oauth2_scheme)) -> Dict[str, Any]:
|
|
try:
|
|
payload = safe_decode_token(token)
|
|
except TokenError as exc:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") from exc
|
|
|
|
username = payload.get("sub")
|
|
if not username:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token subject")
|
|
|
|
user = get_user_by_username(username)
|
|
if not user:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
|
if user.get("is_blocked"):
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is blocked")
|
|
|
|
return {
|
|
"username": user["username"],
|
|
"role": user["role"],
|
|
"auth_provider": user.get("auth_provider", "local"),
|
|
}
|
|
|
|
|
|
def require_admin(user: Dict[str, Any] = Depends(get_current_user)) -> Dict[str, Any]:
|
|
if user.get("role") != "admin":
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")
|
|
return user
|