devices.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. """
  2. Client endpoints for viewing organization devices.
  3. """
  4. from typing import Annotated
  5. from fastapi import APIRouter, Depends, HTTPException, Query, status
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from app.api.deps import get_current_user
  8. from app.core.database import get_db
  9. from app.models.user import User
  10. from app.schemas.device import DeviceListResponse, DeviceResponse
  11. from app.services import device_service
  12. router = APIRouter()
  13. @router.get("", response_model=DeviceListResponse)
  14. async def list_organization_devices(
  15. db: Annotated[AsyncSession, Depends(get_db)],
  16. current_user: Annotated[User, Depends(get_current_user)],
  17. skip: int = Query(0, ge=0, description="Number of records to skip"),
  18. limit: int = Query(100, ge=1, le=1000, description="Max records to return"),
  19. status: str | None = Query(None, description="Filter by status"),
  20. ):
  21. """
  22. List devices assigned to current user's organization.
  23. All authenticated users can view devices in their organization.
  24. """
  25. if not current_user.organization_id:
  26. raise HTTPException(
  27. status_code=status.HTTP_400_BAD_REQUEST,
  28. detail="User is not assigned to any organization",
  29. )
  30. devices, total = await device_service.list_devices(
  31. db,
  32. skip=skip,
  33. limit=limit,
  34. organization_id=current_user.organization_id,
  35. status=status,
  36. )
  37. return DeviceListResponse(
  38. devices=devices,
  39. total=total,
  40. )
  41. @router.get("/{device_id}", response_model=DeviceResponse)
  42. async def get_organization_device(
  43. device_id: int,
  44. db: Annotated[AsyncSession, Depends(get_db)],
  45. current_user: Annotated[User, Depends(get_current_user)],
  46. ):
  47. """
  48. Get device details from current organization.
  49. Users can view devices in their organization.
  50. """
  51. device = await device_service.get_device(db, device_id)
  52. if not device:
  53. raise HTTPException(
  54. status_code=status.HTTP_404_NOT_FOUND,
  55. detail="Device not found",
  56. )
  57. # Check if device belongs to same organization
  58. if device.organization_id != current_user.organization_id:
  59. raise HTTPException(
  60. status_code=status.HTTP_403_FORBIDDEN,
  61. detail="Cannot view devices from other organizations",
  62. )
  63. return device