api_keys.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import logging
  2. from fastapi import APIRouter, Depends, HTTPException
  3. from sqlalchemy import select
  4. from sqlalchemy.ext.asyncio import AsyncSession
  5. from backend.app.core.auth import RequirePermissionIfAuthEnabled, generate_api_key
  6. from backend.app.core.database import get_db
  7. from backend.app.core.permissions import Permission
  8. from backend.app.models.api_key import APIKey
  9. from backend.app.models.user import User
  10. from backend.app.schemas.api_key import (
  11. APIKeyCreate,
  12. APIKeyCreateResponse,
  13. APIKeyResponse,
  14. APIKeyUpdate,
  15. )
  16. logger = logging.getLogger(__name__)
  17. router = APIRouter(prefix="/api-keys", tags=["api-keys"])
  18. @router.get("/", response_model=list[APIKeyResponse])
  19. async def list_api_keys(
  20. db: AsyncSession = Depends(get_db),
  21. _: User | None = RequirePermissionIfAuthEnabled(Permission.API_KEYS_READ),
  22. ):
  23. """List all API keys (without full key values)."""
  24. result = await db.execute(select(APIKey).order_by(APIKey.created_at.desc()))
  25. return list(result.scalars().all())
  26. @router.post("/", response_model=APIKeyCreateResponse)
  27. async def create_api_key(
  28. data: APIKeyCreate,
  29. db: AsyncSession = Depends(get_db),
  30. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.API_KEYS_CREATE),
  31. ):
  32. """Create a new API key.
  33. IMPORTANT: The full API key is only returned in this response.
  34. Store it securely - it cannot be retrieved again.
  35. """
  36. # Reject can_access_cloud on auth-disabled deployments — there's no per-user
  37. # cloud_token to read against, so the flag would just silently do nothing.
  38. # Surfacing the rejection at create time prevents the user from thinking
  39. # they've configured cloud access when they actually haven't.
  40. if data.can_access_cloud and current_user is None:
  41. raise HTTPException(
  42. status_code=400,
  43. detail="can_access_cloud requires authentication to be enabled (per-user cloud tokens)",
  44. )
  45. # Generate the key
  46. full_key, key_hash, key_prefix = generate_api_key()
  47. api_key = APIKey(
  48. name=data.name,
  49. key_hash=key_hash,
  50. key_prefix=key_prefix,
  51. user_id=current_user.id if current_user else None,
  52. can_queue=data.can_queue,
  53. can_control_printer=data.can_control_printer,
  54. can_read_status=data.can_read_status,
  55. can_manage_library=data.can_manage_library,
  56. can_manage_inventory=data.can_manage_inventory,
  57. can_manage_maintenance=data.can_manage_maintenance,
  58. can_manage_archives=data.can_manage_archives,
  59. can_manage_projects=data.can_manage_projects,
  60. can_access_cloud=data.can_access_cloud,
  61. can_update_energy_cost=data.can_update_energy_cost,
  62. can_send_notifications=data.can_send_notifications,
  63. printer_ids=data.printer_ids,
  64. expires_at=data.expires_at,
  65. )
  66. db.add(api_key)
  67. await db.flush()
  68. await db.refresh(api_key)
  69. # Return with full key (only time it's shown)
  70. return APIKeyCreateResponse(
  71. id=api_key.id,
  72. name=api_key.name,
  73. key_prefix=api_key.key_prefix,
  74. key=full_key, # Only returned on creation
  75. user_id=api_key.user_id,
  76. can_queue=api_key.can_queue,
  77. can_control_printer=api_key.can_control_printer,
  78. can_read_status=api_key.can_read_status,
  79. can_manage_library=api_key.can_manage_library,
  80. can_manage_inventory=api_key.can_manage_inventory,
  81. can_manage_maintenance=api_key.can_manage_maintenance,
  82. can_manage_archives=api_key.can_manage_archives,
  83. can_manage_projects=api_key.can_manage_projects,
  84. can_access_cloud=api_key.can_access_cloud,
  85. can_update_energy_cost=api_key.can_update_energy_cost,
  86. can_send_notifications=api_key.can_send_notifications,
  87. printer_ids=api_key.printer_ids,
  88. enabled=api_key.enabled,
  89. last_used=api_key.last_used,
  90. created_at=api_key.created_at,
  91. expires_at=api_key.expires_at,
  92. )
  93. @router.get("/{key_id}", response_model=APIKeyResponse)
  94. async def get_api_key(
  95. key_id: int,
  96. db: AsyncSession = Depends(get_db),
  97. _: User | None = RequirePermissionIfAuthEnabled(Permission.API_KEYS_READ),
  98. ):
  99. """Get an API key by ID."""
  100. result = await db.execute(select(APIKey).where(APIKey.id == key_id))
  101. api_key = result.scalar_one_or_none()
  102. if not api_key:
  103. raise HTTPException(status_code=404, detail="API key not found")
  104. return api_key
  105. @router.patch("/{key_id}", response_model=APIKeyResponse)
  106. async def update_api_key(
  107. key_id: int,
  108. data: APIKeyUpdate,
  109. db: AsyncSession = Depends(get_db),
  110. _: User | None = RequirePermissionIfAuthEnabled(Permission.API_KEYS_UPDATE),
  111. ):
  112. """Update an API key."""
  113. result = await db.execute(select(APIKey).where(APIKey.id == key_id))
  114. api_key = result.scalar_one_or_none()
  115. if not api_key:
  116. raise HTTPException(status_code=404, detail="API key not found")
  117. # Update fields if provided
  118. if data.name is not None:
  119. api_key.name = data.name
  120. if data.can_queue is not None:
  121. api_key.can_queue = data.can_queue
  122. if data.can_control_printer is not None:
  123. api_key.can_control_printer = data.can_control_printer
  124. if data.can_read_status is not None:
  125. api_key.can_read_status = data.can_read_status
  126. if data.can_manage_library is not None:
  127. api_key.can_manage_library = data.can_manage_library
  128. if data.can_manage_inventory is not None:
  129. api_key.can_manage_inventory = data.can_manage_inventory
  130. if data.can_manage_maintenance is not None:
  131. api_key.can_manage_maintenance = data.can_manage_maintenance
  132. if data.can_manage_archives is not None:
  133. api_key.can_manage_archives = data.can_manage_archives
  134. if data.can_manage_projects is not None:
  135. api_key.can_manage_projects = data.can_manage_projects
  136. if data.can_access_cloud is not None:
  137. # Same constraint as create — flipping cloud access on a legacy key
  138. # without an owner would be silently broken; reject at the route layer.
  139. if data.can_access_cloud and api_key.user_id is None:
  140. raise HTTPException(
  141. status_code=400,
  142. detail="can_access_cloud requires the API key to have an owner; recreate the key after upgrading",
  143. )
  144. api_key.can_access_cloud = data.can_access_cloud
  145. if data.can_update_energy_cost is not None:
  146. api_key.can_update_energy_cost = data.can_update_energy_cost
  147. if data.can_send_notifications is not None:
  148. api_key.can_send_notifications = data.can_send_notifications
  149. if data.printer_ids is not None:
  150. api_key.printer_ids = data.printer_ids
  151. if data.enabled is not None:
  152. api_key.enabled = data.enabled
  153. if data.expires_at is not None:
  154. api_key.expires_at = data.expires_at
  155. await db.flush()
  156. await db.refresh(api_key)
  157. return api_key
  158. @router.delete("/{key_id}")
  159. async def delete_api_key(
  160. key_id: int,
  161. db: AsyncSession = Depends(get_db),
  162. _: User | None = RequirePermissionIfAuthEnabled(Permission.API_KEYS_DELETE),
  163. ):
  164. """Delete (revoke) an API key."""
  165. result = await db.execute(select(APIKey).where(APIKey.id == key_id))
  166. api_key = result.scalar_one_or_none()
  167. if not api_key:
  168. raise HTTPException(status_code=404, detail="API key not found")
  169. await db.delete(api_key)
  170. return {"message": "API key deleted"}