cosmo/backend/app/api/device.py

105 lines
3.7 KiB
Python

"""
Device management API routes - logged in web user binds / lists / unbinds terminals
"""
import logging
from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.models.db import TerminalDevice, User
from app.models.schemas.terminal import DeviceBindRequest, DeviceResponse
from app.services.auth_deps import get_current_user
from app.services.redis_cache import redis_cache
from app.services.terminal_service import PairingError, terminal_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/devices", tags=["devices"])
# A 6 digit code has 10^6 variants, so failed redemption attempts are capped per user.
BIND_WINDOW_SECONDS = 600
BIND_MAX_ATTEMPTS = 10
# 终端每 5 分钟拉一次订阅数据,在线判定窗口必须比它长,否则设备永远显示离线
ONLINE_WINDOW_SECONDS = 360
def _to_response(device: TerminalDevice) -> DeviceResponse:
online = bool(
device.last_seen_at
and datetime.utcnow() - device.last_seen_at < timedelta(seconds=ONLINE_WINDOW_SECONDS)
)
return DeviceResponse(
id=device.id,
name=device.name,
status=device.status,
bound_at=device.bound_at,
last_seen_at=device.last_seen_at,
online=online,
board=device.board,
firmware_version=device.firmware_version,
)
async def _ensure_bind_allowed(user_id: int) -> None:
"""Redis backed attempt counter, skipped when Redis is unavailable."""
client = redis_cache.client
if client is None:
return
key = f"terminal:bind_attempts:{user_id}"
attempts = await client.incr(key)
if attempts == 1:
await client.expire(key, BIND_WINDOW_SECONDS)
if attempts > BIND_MAX_ATTEMPTS:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=f"绑定尝试过多,请 {BIND_WINDOW_SECONDS // 60} 分钟后再试",
)
async def _reset_bind_attempts(user_id: int) -> None:
client = redis_cache.client
if client is not None:
await client.delete(f"terminal:bind_attempts:{user_id}")
@router.post("/bind", response_model=DeviceResponse)
async def bind_terminal(
payload: DeviceBindRequest,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Bind a terminal by the 6 digit code displayed on its screen."""
await _ensure_bind_allowed(current_user.id)
try:
device = await terminal_service.bind_device(db, current_user.id, payload.code)
except PairingError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
await _reset_bind_attempts(current_user.id)
return _to_response(device)
@router.get("", response_model=list[DeviceResponse])
async def list_terminals(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Terminals bound to the current user."""
devices = await terminal_service.list_devices(db, current_user.id)
return [_to_response(device) for device in devices]
@router.delete("/{device_id}", status_code=status.HTTP_204_NO_CONTENT)
async def unbind_terminal(
device_id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Release a terminal. Its long lived token stops working immediately."""
removed = await terminal_service.unbind_device(db, current_user.id, device_id)
if not removed:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="未找到该设备或设备不属于当前账号"
)