registration.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. # Update SSH key if provided (device may have regenerated keys)
  60. ssh_key_updated = False
  61. if data.ssh_public_key:
  62. new_key = data.ssh_public_key.strip()
  63. old_key = (device.config or {}).get("ssh_public_key", "").strip()
  64. if new_key != old_key:
  65. # Update config with new key (preserve other settings)
  66. new_config = {**(device.config or {}), "ssh_public_key": new_key}
  67. device.config = new_config
  68. ssh_key_updated = True
  69. print(f"[REGISTRATION] Updated SSH key for device={mac_address}")
  70. # Re-generate credentials if missing
  71. if not device.device_token or not device.device_password:
  72. device.device_token = _generate_token()
  73. device.device_password = _generate_password()
  74. if ssh_key_updated or not device.device_token:
  75. await db.commit()
  76. # Sync SSH keys if updated
  77. if ssh_key_updated:
  78. asyncio.create_task(sync_authorized_keys())
  79. return RegistrationResponse(
  80. device_token=device.device_token,
  81. device_password=device.device_password,
  82. )
  83. # Check auto-registration setting
  84. settings_result = await db.execute(
  85. select(Settings).where(Settings.key == "auto_registration")
  86. )
  87. auto_reg_setting = settings_result.scalar_one_or_none()
  88. if not auto_reg_setting or not auto_reg_setting.value.get("enabled", False):
  89. raise HTTPException(
  90. status_code=status.HTTP_401_UNAUTHORIZED,
  91. detail="Registration disabled. Contact administrator.",
  92. )
  93. # Create new device with default config
  94. # Deep copy to avoid modifying the global default
  95. device_config = copy.deepcopy(DEFAULT_CONFIG)
  96. # Add SSH public key if provided
  97. if data.ssh_public_key:
  98. device_config["ssh_public_key"] = data.ssh_public_key
  99. device = Device(
  100. mac_address=mac_address,
  101. organization_id=None, # Unassigned
  102. status="online",
  103. config=device_config,
  104. device_token=_generate_token(),
  105. device_password=_generate_password(),
  106. )
  107. db.add(device)
  108. await db.flush()
  109. # Update last_device_at
  110. auto_reg_setting.value["last_device_at"] = datetime.now(timezone.utc).isoformat()
  111. await db.commit()
  112. await db.refresh(device)
  113. print(f"[REGISTRATION] device={mac_address} simple_id={device.simple_id}")
  114. # Sync SSH keys to authorized_keys (background task)
  115. if data.ssh_public_key:
  116. asyncio.create_task(sync_authorized_keys())
  117. return RegistrationResponse(
  118. device_token=device.device_token,
  119. device_password=device.device_password,
  120. )