42 lines
1.3 KiB
Python
42 lines
1.3 KiB
Python
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.auth.security import decode_access_token
|
|
from app.db.session import get_db
|
|
from app.models import User
|
|
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
|
|
|
|
ROLE_ORDER = {
|
|
"viewer": 10,
|
|
"operator": 20,
|
|
"admin": 30,
|
|
"owner": 40,
|
|
}
|
|
|
|
|
|
def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User:
|
|
email = decode_access_token(token)
|
|
if not email:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid authentication token",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
user = db.scalar(select(User).where(User.email == email))
|
|
if user is None or not user.is_active:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Inactive or missing user")
|
|
return user
|
|
|
|
|
|
def require_role(minimum_role: str):
|
|
def dependency(user: User = Depends(get_current_user)) -> User:
|
|
if ROLE_ORDER.get(user.role, 0) < ROLE_ORDER[minimum_role]:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Insufficient role")
|
|
return user
|
|
|
|
return dependency
|