69 lines
2.2 KiB
Python
69 lines
2.2 KiB
Python
from typing import Annotated
|
|
|
|
import jwt
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.database import get_db
|
|
from app.core.security import decode_access_token
|
|
from app.models import Admin, AdminRole
|
|
|
|
DbSession = Annotated[AsyncSession, Depends(get_db)]
|
|
|
|
_bearer = HTTPBearer(auto_error=False, description="JWT from POST /api/auth/login")
|
|
|
|
|
|
def _unauthorized(detail: str) -> HTTPException:
|
|
return HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail=detail,
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
|
|
async def get_current_admin(
|
|
db: DbSession,
|
|
credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(_bearer)],
|
|
) -> Admin:
|
|
if credentials is None or credentials.scheme.lower() != "bearer":
|
|
raise _unauthorized("Not authenticated")
|
|
try:
|
|
payload = decode_access_token(credentials.credentials)
|
|
admin_id = int(payload["sub"])
|
|
except jwt.ExpiredSignatureError:
|
|
raise _unauthorized("Session expired. Please log in again.") from None
|
|
except (jwt.PyJWTError, KeyError, ValueError):
|
|
raise _unauthorized("Invalid authentication token") from None
|
|
|
|
admin = await db.get(Admin, admin_id)
|
|
if admin is None or not admin.is_active:
|
|
raise _unauthorized("Account not found or disabled")
|
|
return admin
|
|
|
|
|
|
CurrentAdmin = Annotated[Admin, Depends(get_current_admin)]
|
|
|
|
|
|
def require_roles(*roles: AdminRole):
|
|
allowed = set(roles)
|
|
|
|
async def checker(admin: CurrentAdmin) -> Admin:
|
|
if admin.role not in allowed:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="You do not have permission to perform this action",
|
|
)
|
|
return admin
|
|
|
|
return checker
|
|
|
|
|
|
# Convenience role groups
|
|
ALL_ROLES = (AdminRole.SUPER_ADMIN, AdminRole.ADMIN, AdminRole.EDITOR)
|
|
MANAGERS = (AdminRole.SUPER_ADMIN, AdminRole.ADMIN)
|
|
|
|
AnyAdmin = Annotated[Admin, Depends(require_roles(*ALL_ROLES))]
|
|
ManagerAdmin = Annotated[Admin, Depends(require_roles(*MANAGERS))]
|
|
SuperAdmin = Annotated[Admin, Depends(require_roles(AdminRole.SUPER_ADMIN))]
|