config.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """
  2. Device configuration endpoint.
  3. """
  4. from typing import Annotated
  5. from fastapi import APIRouter, Depends, Header, HTTPException, Query, status
  6. from sqlalchemy import select, update
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from app.core.database import get_db
  9. from app.models.device import Device
  10. router = APIRouter()
  11. async def _auth_device_token(
  12. authorization: str | None, db: AsyncSession
  13. ) -> Device:
  14. """Authenticate device by token from Authorization header."""
  15. if not authorization or not authorization.lower().startswith("bearer "):
  16. raise HTTPException(
  17. status_code=status.HTTP_401_UNAUTHORIZED,
  18. detail="Missing token",
  19. )
  20. token = authorization.split(None, 1)[1]
  21. result = await db.execute(select(Device).where(Device.device_token == token))
  22. device = result.scalar_one_or_none()
  23. if not device:
  24. raise HTTPException(
  25. status_code=status.HTTP_401_UNAUTHORIZED,
  26. detail="Invalid token",
  27. )
  28. return device
  29. @router.get("/config")
  30. async def get_device_config(
  31. db: Annotated[AsyncSession, Depends(get_db)],
  32. device_id: str = Query(..., description="Device MAC address"),
  33. eth_ip: str | None = Query(None),
  34. wlan_ip: str | None = Query(None),
  35. modem_ip: str | None = Query(None),
  36. authorization: Annotated[str | None, Header()] = None,
  37. ):
  38. """
  39. Get device configuration.
  40. Returns config with BLE/WiFi settings, tunnel config, etc.
  41. Updates device last_seen_at timestamp.
  42. """
  43. device = await _auth_device_token(authorization, db)
  44. # Update last_seen_at timestamp
  45. from datetime import datetime, timezone
  46. device.last_seen_at = datetime.now(timezone.utc)
  47. await db.commit()
  48. # Return device config from database
  49. # Config was copied from default_config.json during registration
  50. return device.config or {}