registration.py 3.9 KB

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