62 lines
2.1 KiB
Python
62 lines
2.1 KiB
Python
from __future__ import annotations
|
|
|
|
from collections.abc import Generator
|
|
|
|
from fastapi import Depends, Header, HTTPException, Request, status
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.config import get_settings
|
|
from app.core.db import SessionLocal
|
|
from app.core.security import SessionPayload, read_session_token
|
|
from app.models.user import User
|
|
from app.schemas import CurrentUser, Role
|
|
|
|
settings = get_settings()
|
|
_VALID_ROLES = frozenset(Role.__args__) # type: ignore[attr-defined]
|
|
|
|
|
|
def get_db() -> Generator[Session, None, None]:
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def get_current_user(request: Request, db: Session = Depends(get_db)) -> CurrentUser:
|
|
token = request.cookies.get(settings.session_cookie_name)
|
|
payload: SessionPayload | None = read_session_token(token) if token else None
|
|
if payload is None or payload.role not in _VALID_ROLES:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
|
|
user = db.get(User, payload.user_id)
|
|
if (
|
|
user is None
|
|
or not user.active
|
|
or user.public_ref != payload.public_ref
|
|
or user.role not in _VALID_ROLES
|
|
):
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated")
|
|
role: Role = user.role # type: ignore[assignment]
|
|
return CurrentUser(public_ref=user.public_ref, display_name=user.display_name, role=role)
|
|
|
|
|
|
def require_operations_manager(
|
|
user: CurrentUser = Depends(get_current_user),
|
|
) -> CurrentUser:
|
|
if user.role != "operations_manager":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN, detail="Operations Manager role required"
|
|
)
|
|
return user
|
|
|
|
|
|
def require_mcp_service_token(
|
|
x_service_token: str = Header(..., alias="X-Service-Token"),
|
|
x_client_id: str = Header(default="unknown-mcp-client", alias="X-Client-Id"),
|
|
) -> str:
|
|
if x_service_token != settings.mcp_hub_service_token:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid service token"
|
|
)
|
|
return x_client_id
|