58 lines
2.0 KiB
Python
58 lines
2.0 KiB
Python
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from jose import jwt, JWTError
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
from pydantic import ValidationError
|
|
|
|
from app.core.database import get_db
|
|
from app.core.security import security
|
|
from app.core.config import get_settings
|
|
from app.models.user import User, UserRole
|
|
|
|
settings = get_settings()
|
|
|
|
# Define OAuth2 scheme here or import from auth if needed.
|
|
# Defining here creates a separate instance which is fine as they share config.
|
|
# Ideally auth.py should import from here, but modifying auth.py is risky now.
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"/{settings.API_VERSION}/auth/login")
|
|
|
|
async def get_current_user(
|
|
token: str = Depends(oauth2_scheme),
|
|
db: AsyncSession = Depends(get_db)
|
|
) -> User:
|
|
payload = security.verify_token(token)
|
|
if payload is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
user_id: str = payload.get("sub")
|
|
if user_id is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
result = await db.execute(select(User).where(User.id == user_id))
|
|
user = result.scalars().first()
|
|
|
|
if user is None:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
|
|
if not user.is_active:
|
|
raise HTTPException(status_code=400, detail="Inactive user")
|
|
|
|
return user
|
|
|
|
async def get_current_active_superuser(
|
|
current_user: User = Depends(get_current_user),
|
|
) -> User:
|
|
if current_user.role != UserRole.ADMIN:
|
|
raise HTTPException(
|
|
status_code=403, detail="The user doesn't have enough privileges"
|
|
)
|
|
return current_user
|