registration.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. """
  2. Device registration endpoint.
  3. """
  4. import copy
  5. import json
  6. import secrets
  7. from base64 import b64encode
  8. from datetime import datetime, timezone
  9. from pathlib import Path
  10. from typing import Annotated
  11. from fastapi import APIRouter, Depends, HTTPException, status
  12. from pydantic import BaseModel
  13. from sqlalchemy import select, update
  14. from sqlalchemy.ext.asyncio import AsyncSession
  15. from app.core.database import get_db
  16. from app.models.device import Device
  17. from app.models.settings import Settings
  18. router = APIRouter()
  19. # Load default config from JSON file
  20. DEFAULT_CONFIG_PATH = Path(__file__).parent.parent.parent / "default_config.json"
  21. with open(DEFAULT_CONFIG_PATH, "r") as f:
  22. DEFAULT_CONFIG = json.load(f)
  23. class RegistrationRequest(BaseModel):
  24. """Device registration request."""
  25. device_id: str # MAC address
  26. ssh_public_key: str | None = None
  27. class RegistrationResponse(BaseModel):
  28. """Device registration response."""
  29. device_token: str
  30. device_password: str
  31. def _generate_token() -> str:
  32. """Generate 32-byte base64 token."""
  33. return b64encode(secrets.token_bytes(32)).decode("ascii")
  34. def _generate_password() -> str:
  35. """Generate 8-digit password."""
  36. n = secrets.randbelow(10**8)
  37. return f"{n:08d}"
  38. @router.post("/registration", response_model=RegistrationResponse, status_code=201)
  39. async def register_device(
  40. data: RegistrationRequest,
  41. db: Annotated[AsyncSession, Depends(get_db)],
  42. ):
  43. """
  44. Register new device or return existing credentials.
  45. Requires auto_registration to be enabled in settings.
  46. """
  47. mac_address = data.device_id.lower().strip()
  48. if not mac_address:
  49. raise HTTPException(
  50. status_code=status.HTTP_400_BAD_REQUEST,
  51. detail="Missing device_id",
  52. )
  53. # Check if device already exists
  54. result = await db.execute(select(Device).where(Device.mac_address == mac_address))
  55. device = result.scalar_one_or_none()
  56. if device:
  57. # Return existing credentials
  58. if not device.device_token or not device.device_password:
  59. # Re-generate if missing
  60. device.device_token = _generate_token()
  61. device.device_password = _generate_password()
  62. await db.commit()
  63. return RegistrationResponse(
  64. device_token=device.device_token,
  65. device_password=device.device_password,
  66. )
  67. # Check auto-registration setting
  68. settings_result = await db.execute(
  69. select(Settings).where(Settings.key == "auto_registration")
  70. )
  71. auto_reg_setting = settings_result.scalar_one_or_none()
  72. if not auto_reg_setting or not auto_reg_setting.value.get("enabled", False):
  73. raise HTTPException(
  74. status_code=status.HTTP_401_UNAUTHORIZED,
  75. detail="Registration disabled. Contact administrator.",
  76. )
  77. # Create new device with default config
  78. # Deep copy to avoid modifying the global default
  79. device_config = copy.deepcopy(DEFAULT_CONFIG)
  80. # Add SSH public key if provided
  81. if data.ssh_public_key:
  82. device_config["ssh_public_key"] = data.ssh_public_key
  83. device = Device(
  84. mac_address=mac_address,
  85. organization_id=None, # Unassigned
  86. status="online",
  87. config=device_config,
  88. device_token=_generate_token(),
  89. device_password=_generate_password(),
  90. )
  91. db.add(device)
  92. await db.flush()
  93. # Update last_device_at
  94. auto_reg_setting.value["last_device_at"] = datetime.now(timezone.utc).isoformat()
  95. await db.commit()
  96. await db.refresh(device)
  97. print(f"[REGISTRATION] device={mac_address} simple_id={device.simple_id}")
  98. return RegistrationResponse(
  99. device_token=device.device_token,
  100. device_password=device.device_password,
  101. )