groups.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. """Group management API routes."""
  2. from fastapi import APIRouter, Depends, HTTPException, status
  3. from sqlalchemy import delete, insert, select
  4. from sqlalchemy.ext.asyncio import AsyncSession
  5. from sqlalchemy.orm import selectinload
  6. from backend.app.core.auth import RequireAdminIfAuthEnabled, RequirePermissionIfAuthEnabled
  7. from backend.app.core.database import get_db
  8. from backend.app.core.filament_scope import clean_rules
  9. from backend.app.core.permissions import (
  10. ALL_PERMISSIONS,
  11. PERMISSION_CATEGORIES,
  12. Permission,
  13. )
  14. from backend.app.core.printer_scope import group_location_names, group_printer_ids
  15. from backend.app.core.websocket import ws_manager
  16. from backend.app.models.group import Group, group_locations, group_printers
  17. from backend.app.models.printer import Printer
  18. from backend.app.models.user import ADMIN_GROUP_NAME, User
  19. from backend.app.schemas.group import (
  20. GroupCreate,
  21. GroupDetailResponse,
  22. GroupResponse,
  23. GroupUpdate,
  24. PermissionCategory,
  25. PermissionInfo,
  26. PermissionsListResponse,
  27. UserBrief,
  28. )
  29. router = APIRouter(prefix="/groups", tags=["groups"])
  30. # Permissions whose derived label would misdescribe what is being granted.
  31. # The derived form for USERS_READ_SLIM is "Read Slim Users", which reads as a
  32. # property of the users rather than of the response -- and an admin ticking a
  33. # box in the group editor has nothing else to go on (#1894).
  34. _PERMISSION_LABEL_OVERRIDES: dict[Permission, str] = {
  35. Permission.USERS_READ_SLIM: "List User Names (id + username only)",
  36. # "Start Unreviewed Queue" says nothing about what happens without it (#1620)
  37. Permission.QUEUE_START_UNREVIEWED: "Print Without Review (else jobs wait for someone to start them)",
  38. }
  39. def _permission_label(perm: Permission) -> str:
  40. """Convert permission enum to human-readable label."""
  41. if perm in _PERMISSION_LABEL_OVERRIDES:
  42. return _PERMISSION_LABEL_OVERRIDES[perm]
  43. # e.g., "printers:read" -> "Read Printers"
  44. parts = perm.value.split(":")
  45. if len(parts) == 2:
  46. resource, action = parts
  47. resource = resource.replace("_", " ").title()
  48. action = action.replace("_", " ").title()
  49. return f"{action} {resource}"
  50. return perm.value
  51. async def _printer_ids_by_group(db: AsyncSession) -> dict[int, list[int]]:
  52. result = await db.execute(select(group_printers.c.group_id, group_printers.c.printer_id))
  53. by_group: dict[int, list[int]] = {}
  54. for group_id, printer_id in result.all():
  55. by_group.setdefault(group_id, []).append(printer_id)
  56. return {gid: sorted(pids) for gid, pids in by_group.items()}
  57. async def _locations_by_group(db: AsyncSession) -> dict[int, list[str]]:
  58. result = await db.execute(select(group_locations.c.group_id, group_locations.c.location))
  59. by_group: dict[int, list[str]] = {}
  60. for group_id, location in result.all():
  61. by_group.setdefault(group_id, []).append(location)
  62. return {gid: sorted(locs) for gid, locs in by_group.items()}
  63. def _clean_locations(locations: list[str]) -> set[str]:
  64. """Trimmed, non-empty location names; refuses ones too long to ever match a printer."""
  65. cleaned = {loc.strip() for loc in locations if loc and loc.strip()}
  66. if any(len(loc) > 100 for loc in cleaned):
  67. raise HTTPException(
  68. status_code=status.HTTP_400_BAD_REQUEST,
  69. detail="Location names are at most 100 characters",
  70. )
  71. return cleaned
  72. async def _apply_printer_scope(
  73. db: AsyncSession,
  74. group: Group,
  75. restrict_printers: bool | None,
  76. printer_ids: list[int] | None,
  77. locations: list[str] | None = None,
  78. ) -> bool:
  79. """Validate and store a group's printer scope (#1727). Returns whether it changed.
  80. The Administrators group can't be restricted: admins see every printer
  81. regardless, so the setting would only mislead.
  82. """
  83. changed = False
  84. if restrict_printers is not None and restrict_printers != bool(group.restrict_printers):
  85. if restrict_printers and group.name == "Administrators":
  86. raise HTTPException(
  87. status_code=status.HTTP_400_BAD_REQUEST,
  88. detail="Administrators always see every printer",
  89. )
  90. group.restrict_printers = restrict_printers
  91. changed = True
  92. if printer_ids is not None:
  93. wanted = set(printer_ids)
  94. if wanted:
  95. found = set((await db.execute(select(Printer.id).where(Printer.id.in_(wanted)))).scalars().all())
  96. missing = sorted(wanted - found)
  97. if missing:
  98. raise HTTPException(
  99. status_code=status.HTTP_400_BAD_REQUEST,
  100. detail=f"Invalid printers: {', '.join(str(pid) for pid in missing)}",
  101. )
  102. current = set(await group_printer_ids(db, group.id)) if group.id is not None else set()
  103. if wanted != current:
  104. if group.id is None:
  105. await db.flush()
  106. await db.execute(delete(group_printers).where(group_printers.c.group_id == group.id))
  107. if wanted:
  108. await db.execute(
  109. insert(group_printers), [{"group_id": group.id, "printer_id": pid} for pid in sorted(wanted)]
  110. )
  111. changed = True
  112. if locations is not None:
  113. # Not checked against existing printers: a location can be granted
  114. # before its first printer is added there.
  115. wanted_locations = _clean_locations(locations)
  116. current_locations = set(await group_location_names(db, group.id)) if group.id is not None else set()
  117. if wanted_locations != current_locations:
  118. if group.id is None:
  119. await db.flush()
  120. await db.execute(delete(group_locations).where(group_locations.c.group_id == group.id))
  121. if wanted_locations:
  122. await db.execute(
  123. insert(group_locations),
  124. [{"group_id": group.id, "location": loc} for loc in sorted(wanted_locations)],
  125. )
  126. changed = True
  127. return changed
  128. def _apply_filament_scope(
  129. group: Group,
  130. restrict_filaments: bool | None,
  131. filament_rule_mode: str | None,
  132. filament_rules: list | None,
  133. ) -> None:
  134. """Store a group's filament scope (#3522).
  135. The Administrators group can't be restricted: admins may use every
  136. filament regardless, so the setting would only mislead.
  137. """
  138. if restrict_filaments is not None and restrict_filaments != bool(group.restrict_filaments):
  139. if restrict_filaments and group.name == ADMIN_GROUP_NAME:
  140. raise HTTPException(
  141. status_code=status.HTTP_400_BAD_REQUEST,
  142. detail="Administrators can always use every filament",
  143. )
  144. group.restrict_filaments = restrict_filaments
  145. if filament_rule_mode is not None and filament_rule_mode != (group.filament_rule_mode or "block"):
  146. group.filament_rule_mode = filament_rule_mode
  147. if filament_rules is not None:
  148. cleaned = clean_rules(filament_rules)
  149. if cleaned != (group.filament_rules or []):
  150. group.filament_rules = cleaned
  151. def _filament_fields(group: Group) -> dict:
  152. return {
  153. "restrict_filaments": bool(group.restrict_filaments),
  154. "filament_rule_mode": group.filament_rule_mode or "block",
  155. "filament_rules": clean_rules(group.filament_rules),
  156. }
  157. def _group_response(group: Group, printer_ids: list[int], locations: list[str], user_count: int) -> GroupResponse:
  158. return GroupResponse(
  159. id=group.id,
  160. name=group.name,
  161. description=group.description,
  162. permissions=group.permissions or [],
  163. is_system=group.is_system,
  164. restrict_printers=bool(group.restrict_printers),
  165. printer_ids=printer_ids,
  166. locations=locations,
  167. **_filament_fields(group),
  168. user_count=user_count,
  169. created_at=group.created_at,
  170. updated_at=group.updated_at,
  171. )
  172. @router.get("/permissions", response_model=PermissionsListResponse)
  173. async def list_permissions(
  174. _: User | None = RequirePermissionIfAuthEnabled(Permission.GROUPS_READ),
  175. ):
  176. """List all available permissions organized by category."""
  177. categories = []
  178. for name, perms in PERMISSION_CATEGORIES.items():
  179. categories.append(
  180. PermissionCategory(
  181. name=name,
  182. permissions=[PermissionInfo(value=p.value, label=_permission_label(p)) for p in perms],
  183. )
  184. )
  185. return PermissionsListResponse(
  186. categories=categories,
  187. all_permissions=ALL_PERMISSIONS,
  188. )
  189. @router.get("", response_model=list[GroupResponse])
  190. @router.get("/", response_model=list[GroupResponse])
  191. async def list_groups(
  192. _: User | None = RequirePermissionIfAuthEnabled(Permission.GROUPS_READ),
  193. db: AsyncSession = Depends(get_db, scope="function"),
  194. ):
  195. """List all groups."""
  196. result = await db.execute(select(Group).options(selectinload(Group.users)).order_by(Group.name))
  197. groups = result.scalars().all()
  198. printers_by_group = await _printer_ids_by_group(db)
  199. locations_by_group = await _locations_by_group(db)
  200. return [
  201. _group_response(
  202. group, printers_by_group.get(group.id, []), locations_by_group.get(group.id, []), len(group.users)
  203. )
  204. for group in groups
  205. ]
  206. @router.post("", response_model=GroupResponse, status_code=status.HTTP_201_CREATED)
  207. @router.post("/", response_model=GroupResponse, status_code=status.HTTP_201_CREATED)
  208. async def create_group(
  209. group_data: GroupCreate,
  210. _admin: User | None = RequireAdminIfAuthEnabled(),
  211. _: User | None = RequirePermissionIfAuthEnabled(Permission.GROUPS_CREATE),
  212. db: AsyncSession = Depends(get_db, scope="function"),
  213. ):
  214. """Create a new group."""
  215. # Check if group name already exists
  216. existing = await db.execute(select(Group).where(Group.name == group_data.name))
  217. if existing.scalar_one_or_none():
  218. raise HTTPException(
  219. status_code=status.HTTP_400_BAD_REQUEST,
  220. detail="Group name already exists",
  221. )
  222. # Validate permissions
  223. invalid_perms = [p for p in group_data.permissions if p not in ALL_PERMISSIONS]
  224. if invalid_perms:
  225. raise HTTPException(
  226. status_code=status.HTTP_400_BAD_REQUEST,
  227. detail=f"Invalid permissions: {', '.join(invalid_perms)}",
  228. )
  229. group = Group(
  230. name=group_data.name,
  231. description=group_data.description,
  232. permissions=group_data.permissions,
  233. is_system=False, # User-created groups are not system groups
  234. restrict_printers=False,
  235. restrict_filaments=False,
  236. filament_rule_mode="block",
  237. )
  238. db.add(group)
  239. await db.flush()
  240. await _apply_printer_scope(db, group, group_data.restrict_printers, group_data.printer_ids, group_data.locations)
  241. _apply_filament_scope(
  242. group, group_data.restrict_filaments, group_data.filament_rule_mode, group_data.filament_rules
  243. )
  244. await db.commit()
  245. await db.refresh(group)
  246. return _group_response(group, await group_printer_ids(db, group.id), await group_location_names(db, group.id), 0)
  247. @router.get("/{group_id}", response_model=GroupDetailResponse)
  248. async def get_group(
  249. group_id: int,
  250. _: User | None = RequirePermissionIfAuthEnabled(Permission.GROUPS_READ),
  251. db: AsyncSession = Depends(get_db, scope="function"),
  252. ):
  253. """Get a group by ID with user list. Read-only — gated on
  254. ``GROUPS_READ`` only."""
  255. result = await db.execute(select(Group).where(Group.id == group_id).options(selectinload(Group.users)))
  256. group = result.scalar_one_or_none()
  257. if not group:
  258. raise HTTPException(
  259. status_code=status.HTTP_404_NOT_FOUND,
  260. detail="Group not found",
  261. )
  262. return GroupDetailResponse(
  263. id=group.id,
  264. name=group.name,
  265. description=group.description,
  266. permissions=group.permissions or [],
  267. is_system=group.is_system,
  268. restrict_printers=bool(group.restrict_printers),
  269. printer_ids=await group_printer_ids(db, group.id),
  270. locations=await group_location_names(db, group.id),
  271. **_filament_fields(group),
  272. user_count=len(group.users),
  273. created_at=group.created_at,
  274. updated_at=group.updated_at,
  275. users=[UserBrief(id=u.id, username=u.username, is_active=u.is_active) for u in group.users],
  276. )
  277. @router.patch("/{group_id}", response_model=GroupResponse)
  278. async def update_group(
  279. group_id: int,
  280. group_data: GroupUpdate,
  281. _admin: User | None = RequireAdminIfAuthEnabled(),
  282. _: User | None = RequirePermissionIfAuthEnabled(Permission.GROUPS_UPDATE),
  283. db: AsyncSession = Depends(get_db, scope="function"),
  284. ):
  285. """Update a group."""
  286. result = await db.execute(select(Group).where(Group.id == group_id).options(selectinload(Group.users)))
  287. group = result.scalar_one_or_none()
  288. if not group:
  289. raise HTTPException(
  290. status_code=status.HTTP_404_NOT_FOUND,
  291. detail="Group not found",
  292. )
  293. # Check if updating name to one that already exists
  294. if group_data.name is not None and group_data.name != group.name:
  295. existing = await db.execute(select(Group).where(Group.name == group_data.name, Group.id != group_id))
  296. if existing.scalar_one_or_none():
  297. raise HTTPException(
  298. status_code=status.HTTP_400_BAD_REQUEST,
  299. detail="Group name already exists",
  300. )
  301. # System groups cannot have their name changed
  302. if group.is_system:
  303. raise HTTPException(
  304. status_code=status.HTTP_400_BAD_REQUEST,
  305. detail="Cannot rename system groups",
  306. )
  307. group.name = group_data.name
  308. if group_data.description is not None:
  309. group.description = group_data.description
  310. if group_data.permissions is not None:
  311. # System groups (Administrators in particular) have fixed permission
  312. # sets that the app depends on — stripping them is a denial-of-
  313. # service vector that even admin callers shouldn't trigger by
  314. # accident through the generic edit form. Mirrors the rename block
  315. # immediately above.
  316. if group.is_system:
  317. raise HTTPException(
  318. status_code=status.HTTP_400_BAD_REQUEST,
  319. detail="Cannot modify permissions of system groups",
  320. )
  321. # Validate permissions
  322. invalid_perms = [p for p in group_data.permissions if p not in ALL_PERMISSIONS]
  323. if invalid_perms:
  324. raise HTTPException(
  325. status_code=status.HTTP_400_BAD_REQUEST,
  326. detail=f"Invalid permissions: {', '.join(invalid_perms)}",
  327. )
  328. group.permissions = group_data.permissions
  329. scope_changed = await _apply_printer_scope(
  330. db, group, group_data.restrict_printers, group_data.printer_ids, group_data.locations
  331. )
  332. _apply_filament_scope(
  333. group, group_data.restrict_filaments, group_data.filament_rule_mode, group_data.filament_rules
  334. )
  335. await db.commit()
  336. await db.refresh(group)
  337. if scope_changed or group_data.permissions is not None:
  338. # Printers, or websocket:connect itself (a socket of a user who lost it
  339. # is closed)
  340. await ws_manager.refresh_printer_scopes()
  341. return _group_response(
  342. group, await group_printer_ids(db, group.id), await group_location_names(db, group.id), len(group.users)
  343. )
  344. @router.delete("/{group_id}", status_code=status.HTTP_204_NO_CONTENT)
  345. async def delete_group(
  346. group_id: int,
  347. _admin: User | None = RequireAdminIfAuthEnabled(),
  348. _: User | None = RequirePermissionIfAuthEnabled(Permission.GROUPS_DELETE),
  349. db: AsyncSession = Depends(get_db, scope="function"),
  350. ):
  351. """Delete a group (non-system groups only)."""
  352. result = await db.execute(select(Group).where(Group.id == group_id))
  353. group = result.scalar_one_or_none()
  354. if not group:
  355. raise HTTPException(
  356. status_code=status.HTTP_404_NOT_FOUND,
  357. detail="Group not found",
  358. )
  359. if group.is_system:
  360. raise HTTPException(
  361. status_code=status.HTTP_400_BAD_REQUEST,
  362. detail="Cannot delete system groups",
  363. )
  364. # SQLite doesn't enforce the FK cascade
  365. await db.execute(delete(group_printers).where(group_printers.c.group_id == group_id))
  366. await db.execute(delete(group_locations).where(group_locations.c.group_id == group_id))
  367. await db.delete(group)
  368. await db.commit()
  369. # Its members may lose printers, or websocket:connect itself
  370. await ws_manager.refresh_printer_scopes()
  371. @router.post("/{group_id}/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
  372. async def add_user_to_group(
  373. group_id: int,
  374. user_id: int,
  375. _admin: User | None = RequireAdminIfAuthEnabled(),
  376. _: User | None = RequirePermissionIfAuthEnabled(Permission.GROUPS_UPDATE),
  377. db: AsyncSession = Depends(get_db, scope="function"),
  378. ):
  379. """Add a user to a group."""
  380. # Get group with users
  381. result = await db.execute(select(Group).where(Group.id == group_id).options(selectinload(Group.users)))
  382. group = result.scalar_one_or_none()
  383. if not group:
  384. raise HTTPException(
  385. status_code=status.HTTP_404_NOT_FOUND,
  386. detail="Group not found",
  387. )
  388. # Get user
  389. user_result = await db.execute(select(User).where(User.id == user_id))
  390. user = user_result.scalar_one_or_none()
  391. if not user:
  392. raise HTTPException(
  393. status_code=status.HTTP_404_NOT_FOUND,
  394. detail="User not found",
  395. )
  396. # Check if user is already in group
  397. if user in group.users:
  398. raise HTTPException(
  399. status_code=status.HTTP_400_BAD_REQUEST,
  400. detail="User is already in this group",
  401. )
  402. group.users.append(user)
  403. # The legacy role follows Administrators membership (#3533).
  404. if group.name == ADMIN_GROUP_NAME:
  405. user.role = "admin"
  406. await db.commit()
  407. await ws_manager.refresh_printer_scopes()
  408. @router.delete("/{group_id}/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
  409. async def remove_user_from_group(
  410. group_id: int,
  411. user_id: int,
  412. _admin: User | None = RequireAdminIfAuthEnabled(),
  413. _: User | None = RequirePermissionIfAuthEnabled(Permission.GROUPS_UPDATE),
  414. db: AsyncSession = Depends(get_db, scope="function"),
  415. ):
  416. """Remove a user from a group."""
  417. # Get group with users
  418. result = await db.execute(select(Group).where(Group.id == group_id).options(selectinload(Group.users)))
  419. group = result.scalar_one_or_none()
  420. if not group:
  421. raise HTTPException(
  422. status_code=status.HTTP_404_NOT_FOUND,
  423. detail="Group not found",
  424. )
  425. # Get user
  426. user_result = await db.execute(select(User).where(User.id == user_id))
  427. user = user_result.scalar_one_or_none()
  428. if not user:
  429. raise HTTPException(
  430. status_code=status.HTTP_404_NOT_FOUND,
  431. detail="User not found",
  432. )
  433. # Check if user is in group
  434. if user not in group.users:
  435. raise HTTPException(
  436. status_code=status.HTTP_400_BAD_REQUEST,
  437. detail="User is not in this group",
  438. )
  439. if group.name == ADMIN_GROUP_NAME:
  440. # Leaving Administrators takes the admin rights with it, so the role
  441. # follows (#3533) -- unless that leaves no active admin.
  442. from backend.app.api.routes.users import _other_active_admins
  443. if user.is_active and not await _other_active_admins(db, user.id):
  444. raise HTTPException(
  445. status_code=status.HTTP_400_BAD_REQUEST,
  446. detail="Cannot remove admin rights from the last admin user",
  447. )
  448. user.role = "user"
  449. group.users.remove(user)
  450. await db.commit()
  451. # They may lose printers, or websocket:connect itself
  452. await ws_manager.refresh_printer_scopes()