30 lines
1.2 KiB
Python
30 lines
1.2 KiB
Python
from fastapi import Depends, Header, HTTPException, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.security import decode_access_token
|
|
from app.db import get_db
|
|
from app.models import User
|
|
|
|
|
|
def get_current_user(
|
|
authorization: str | None = Header(default=None),
|
|
db: Session = Depends(get_db),
|
|
) -> User:
|
|
if not authorization or not authorization.lower().startswith("bearer "):
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing bearer token")
|
|
token = authorization.split(" ", 1)[1]
|
|
subject = decode_access_token(token)
|
|
if not subject:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
|
user = db.get(User, int(subject))
|
|
if not user or user.status != "active":
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Inactive or missing user")
|
|
return user
|
|
|
|
|
|
def require_admin(current_user: User = Depends(get_current_user)) -> User:
|
|
role_codes = {role.code for role in current_user.roles}
|
|
if not current_user.is_superuser and role_codes.isdisjoint({"admin", "system_admin"}):
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin permission required")
|
|
return current_user
|