49 lines
1.7 KiB
Python
49 lines
1.7 KiB
Python
from typing import Generator, Optional
|
|
from fastapi import Depends, Header
|
|
from sqlalchemy.orm import Session
|
|
from app.database import SessionLocal, get_db
|
|
from app.models.user import User, UserRole
|
|
from app.core.security import decode_access_token
|
|
from app.core.exceptions import AuthException, ForbiddenException
|
|
|
|
|
|
def get_current_user(
|
|
authorization: Optional[str] = Header(None),
|
|
db: Session = Depends(get_db)
|
|
) -> User:
|
|
"""Extracts and verifies JWT bearer token from Authorization header."""
|
|
if not authorization or not authorization.startswith("Bearer "):
|
|
raise AuthException("Missing or malformed Authorization header")
|
|
|
|
token = authorization.split("Bearer ")[1].strip()
|
|
payload = decode_access_token(token)
|
|
if not payload:
|
|
raise AuthException("Token is invalid or expired")
|
|
|
|
user_id_str = payload.get("sub")
|
|
if not user_id_str:
|
|
raise AuthException("Token payload missing subject identifier")
|
|
|
|
try:
|
|
user_id = int(user_id_str)
|
|
except ValueError:
|
|
raise AuthException("Invalid user identifier in token")
|
|
|
|
user = db.query(User).filter(User.id == user_id).first()
|
|
if not user:
|
|
raise AuthException("User associated with token does not exist")
|
|
|
|
if not user.is_active:
|
|
raise ForbiddenException("User account is deactivated")
|
|
|
|
return user
|
|
|
|
|
|
def require_super_admin(
|
|
current_user: User = Depends(get_current_user)
|
|
) -> User:
|
|
"""Ensures that the authenticated user possesses the super_admin role."""
|
|
if current_user.role != UserRole.SUPER_ADMIN.value:
|
|
raise ForbiddenException("Super admin privileges required")
|
|
return current_user
|