default_config.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """
  2. Superadmin endpoint for managing default device configuration.
  3. """
  4. import json
  5. from pathlib import Path
  6. from typing import Annotated
  7. from fastapi import APIRouter, Depends, HTTPException, status
  8. from pydantic import BaseModel
  9. from app.api.deps import get_current_superadmin
  10. from app.models.user import User
  11. router = APIRouter()
  12. DEFAULT_CONFIG_PATH = Path(__file__).parent.parent.parent.parent / "default_config.json"
  13. @router.get("/default-config")
  14. async def get_default_config(
  15. current_user: Annotated[User, Depends(get_current_superadmin)],
  16. ):
  17. """
  18. Get default device configuration (superadmin only).
  19. Returns the default config that will be copied to newly registered devices.
  20. """
  21. try:
  22. with open(DEFAULT_CONFIG_PATH, "r") as f:
  23. config = json.load(f)
  24. return config
  25. except FileNotFoundError:
  26. raise HTTPException(
  27. status_code=status.HTTP_404_NOT_FOUND,
  28. detail="Default config file not found",
  29. )
  30. except json.JSONDecodeError:
  31. raise HTTPException(
  32. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  33. detail="Invalid JSON in default config file",
  34. )
  35. @router.put("/default-config")
  36. async def update_default_config(
  37. config: dict,
  38. current_user: Annotated[User, Depends(get_current_superadmin)],
  39. ):
  40. """
  41. Update default device configuration (superadmin only).
  42. Updates the default config file. Changes only affect newly registered devices.
  43. Existing devices keep their current configuration.
  44. """
  45. try:
  46. # Write config to file with pretty formatting
  47. with open(DEFAULT_CONFIG_PATH, "w") as f:
  48. json.dump(config, f, indent=2)
  49. return {"success": True, "message": "Default config updated"}
  50. except Exception as e:
  51. raise HTTPException(
  52. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  53. detail=f"Failed to save config: {str(e)}",
  54. )