admin.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. from fastapi import APIRouter, HTTPException, Depends, status
  2. from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
  3. from web.schemas import RefreshVersionsResponse
  4. from web.services.admin import get_admin_service, AdminService
  5. router = APIRouter(prefix="/admin", tags=["admin"])
  6. security = HTTPBearer(auto_error=False)
  7. async def verify_admin_token(
  8. credentials: HTTPAuthorizationCredentials = Depends(security),
  9. admin_service: AdminService = Depends(get_admin_service)
  10. ) -> None:
  11. """
  12. Verify the bearer token for admin API authentication.
  13. Args:
  14. credentials: HTTP authorization credentials from request header
  15. admin_service: Admin service instance
  16. Raises:
  17. 401: Invalid or missing token
  18. 500: Server configuration error (token not configured)
  19. """
  20. if credentials is None or credentials.scheme.lower() != "bearer":
  21. raise HTTPException(
  22. status_code=status.HTTP_401_UNAUTHORIZED,
  23. detail="Missing or invalid authentication token"
  24. )
  25. token = credentials.credentials
  26. try:
  27. if not await admin_service.verify_admin_token(token):
  28. raise HTTPException(
  29. status_code=status.HTTP_401_UNAUTHORIZED,
  30. detail="Invalid authentication token"
  31. )
  32. except RuntimeError as e:
  33. raise HTTPException(
  34. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  35. detail=str(e)
  36. )
  37. @router.post(
  38. "/refresh_versions",
  39. response_model=RefreshVersionsResponse,
  40. responses={
  41. 401: {"description": "Invalid or missing authentication token"},
  42. 500: {
  43. "description": (
  44. "Server configuration error (token not configured) "
  45. "or refresh operation failed"
  46. )
  47. }
  48. }
  49. )
  50. async def refresh_versions(
  51. _: None = Depends(verify_admin_token),
  52. admin_service: AdminService = Depends(get_admin_service)
  53. ):
  54. """
  55. Trigger a refresh of all version metadata providers.
  56. This endpoint requires bearer token authentication in the Authorization
  57. header:
  58. ```
  59. Authorization: Bearer <your-token>
  60. ```
  61. Returns:
  62. RefreshVersionsResponse: Git remotes synced after the refresh
  63. Raises:
  64. 401: Invalid or missing authentication token
  65. 500: Refresh operation failed
  66. """
  67. try:
  68. remotes = await admin_service.refresh_versions()
  69. return RefreshVersionsResponse(remotes=remotes)
  70. except Exception as e:
  71. raise HTTPException(
  72. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  73. detail=f"Failed to refresh versions: {str(e)}"
  74. )