admin.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from fastapi import APIRouter, HTTPException, Depends, status
  2. from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
  3. from schemas import RefreshRemotesResponse
  4. from services.admin import get_admin_service, AdminService
  5. router = APIRouter(prefix="/admin", tags=["admin"])
  6. security = HTTPBearer()
  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 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. token = credentials.credentials
  21. try:
  22. if not await admin_service.verify_token(token):
  23. raise HTTPException(
  24. status_code=status.HTTP_401_UNAUTHORIZED,
  25. detail="Invalid authentication token"
  26. )
  27. except RuntimeError as e:
  28. raise HTTPException(
  29. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  30. detail=str(e)
  31. )
  32. @router.post(
  33. "/refresh_remotes",
  34. response_model=RefreshRemotesResponse,
  35. responses={
  36. 401: {"description": "Invalid or missing authentication token"},
  37. 500: {
  38. "description": (
  39. "Server configuration error (token not configured) "
  40. "or refresh operation failed"
  41. )
  42. }
  43. }
  44. )
  45. async def refresh_remotes(
  46. _: None = Depends(verify_admin_token),
  47. admin_service: AdminService = Depends(get_admin_service)
  48. ):
  49. """
  50. Trigger a hot reset/refresh of remote metadata.
  51. This endpoint requires bearer token authentication in the Authorization
  52. header:
  53. ```
  54. Authorization: Bearer <your-token>
  55. ```
  56. Returns:
  57. RefreshRemotesResponse: List of remotes that were refreshed
  58. Raises:
  59. 401: Invalid or missing authentication token
  60. 500: Refresh operation failed
  61. """
  62. try:
  63. remotes = await admin_service.refresh_remotes()
  64. return RefreshRemotesResponse(remotes=remotes)
  65. except Exception as e:
  66. raise HTTPException(
  67. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  68. detail=f"Failed to refresh remotes: {str(e)}"
  69. )