users.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. from datetime import datetime, timezone
  2. from typing import Annotated
  3. import jwt as _jwt
  4. from fastapi import APIRouter, Depends, HTTPException, Query, status
  5. from fastapi.security import HTTPAuthorizationCredentials
  6. from sqlalchemy import delete, func, select, update as sql_update
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from sqlalchemy.orm import selectinload
  9. from backend.app.api.routes.settings import get_external_login_url
  10. from backend.app.core.auth import (
  11. ALGORITHM,
  12. SECRET_KEY,
  13. RequireAdminIfAuthEnabled,
  14. RequireAnyPermissionIfAuthEnabled,
  15. RequirePermissionIfAuthEnabled,
  16. get_current_user_optional,
  17. get_password_hash,
  18. revoke_jti,
  19. security,
  20. verify_password,
  21. )
  22. from backend.app.core.database import get_db
  23. from backend.app.core.permissions import Permission
  24. from backend.app.core.websocket import ws_manager
  25. from backend.app.models.api_key import APIKey
  26. from backend.app.models.archive import PrintArchive
  27. from backend.app.models.auth_ephemeral import AuthEphemeralToken
  28. from backend.app.models.connected_app import ConnectedApp, ConnectedAppGrant
  29. from backend.app.models.group import Group
  30. from backend.app.models.library import LibraryFile
  31. from backend.app.models.long_lived_token import LongLivedToken
  32. from backend.app.models.oidc_provider import UserOIDCLink
  33. from backend.app.models.print_batch import PrintBatch
  34. from backend.app.models.print_log import PrintLogEntry
  35. from backend.app.models.print_queue import PrintQueueItem
  36. from backend.app.models.settings import Settings
  37. from backend.app.models.user import ADMIN_GROUP_NAME, User
  38. from backend.app.models.user_otp_code import UserOTPCode
  39. from backend.app.models.user_totp import UserTOTP
  40. from backend.app.schemas.auth import (
  41. ChangePasswordRequest,
  42. GroupBrief,
  43. UserCreate,
  44. UserResponse,
  45. UserSlim,
  46. UserUpdate,
  47. )
  48. from backend.app.services.email_service import (
  49. create_welcome_email_from_template,
  50. generate_secure_password,
  51. get_smtp_settings,
  52. send_email,
  53. )
  54. from backend.app.services.finance_defaults import ensure_user_finance_defaults
  55. from backend.app.services.printer_manager import printer_manager
  56. from backend.app.services.slice_dispatch import slice_dispatch
  57. from backend.app.utils.library_paths import remove_library_photos_dir
  58. from backend.app.utils.local_time import utcnow_naive
  59. router = APIRouter(prefix="/users", tags=["users"])
  60. def _user_to_response(user: User) -> UserResponse:
  61. """Convert a User model to UserResponse schema."""
  62. return UserResponse(
  63. id=user.id,
  64. username=user.username,
  65. email=user.email,
  66. role=user.role,
  67. is_active=user.is_active,
  68. is_admin=user.is_admin,
  69. auth_source=getattr(user, "auth_source", "local"),
  70. groups=[GroupBrief(id=g.id, name=g.name) for g in user.groups],
  71. permissions=sorted(user.get_permissions()),
  72. created_at=user.created_at.isoformat(),
  73. )
  74. @router.get("", response_model=list[UserResponse])
  75. @router.get("/", response_model=list[UserResponse])
  76. async def list_users(
  77. _: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_READ),
  78. db: AsyncSession = Depends(get_db, scope="function"),
  79. ):
  80. """List all users.
  81. Read-only — gated on ``USERS_READ`` only. Operator-visible UIs
  82. (Stats filter-by-user, Archives Print Log username column, File
  83. Manager username autocomplete) consume this endpoint via custom-
  84. group ``users:read`` grants without admin role. The admin-only
  85. boundary lives on the write endpoints below."""
  86. result = await db.execute(select(User).options(selectinload(User.groups)).order_by(User.created_at))
  87. users = result.scalars().all()
  88. return [_user_to_response(user) for user in users]
  89. async def drop_pending_tokens(db: AsyncSession, username: str) -> None:
  90. """Delete the one-time tokens pending under a username that is going away.
  91. Reset links, 2FA and OIDC steps, connect codes, camera, WebSocket and slicer
  92. tokens are looked up by username, so they would work for whoever is given
  93. the name next. The logout list (revoked_jti) stays: dropping an entry would
  94. make the logged-out token valid again.
  95. """
  96. await db.execute(
  97. delete(AuthEphemeralToken).where(
  98. # Both sides in SQL: SQLite's lower() changes only ASCII letters, so
  99. # it never equals Python's lower() of a name with an umlaut.
  100. func.lower(AuthEphemeralToken.username) == func.lower(username),
  101. AuthEphemeralToken.token_type != "revoked_jti",
  102. )
  103. )
  104. @router.post("", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
  105. @router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
  106. async def create_user(
  107. user_data: UserCreate,
  108. _admin: User | None = RequireAdminIfAuthEnabled(),
  109. _: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_CREATE),
  110. db: AsyncSession = Depends(get_db, scope="function"),
  111. ):
  112. """Create a new user.
  113. When advanced authentication is enabled:
  114. - Email is required
  115. - Password is auto-generated and emailed to user
  116. - Admin cannot set or see the password
  117. """
  118. import logging
  119. logger = logging.getLogger(__name__)
  120. # Check if advanced auth is enabled
  121. result = await db.execute(select(Settings).where(Settings.key == "advanced_auth_enabled"))
  122. advanced_auth_setting = result.scalar_one_or_none()
  123. advanced_auth_enabled = advanced_auth_setting and advanced_auth_setting.value.lower() == "true"
  124. # Check if username already exists (case-insensitive)
  125. existing_user = await db.execute(select(User).where(func.lower(User.username) == func.lower(user_data.username)))
  126. if existing_user.scalar_one_or_none():
  127. raise HTTPException(
  128. status_code=status.HTTP_400_BAD_REQUEST,
  129. detail="Username already exists",
  130. )
  131. # Validate role
  132. if user_data.role not in ["admin", "user"]:
  133. raise HTTPException(
  134. status_code=status.HTTP_400_BAD_REQUEST,
  135. detail="Role must be 'admin' or 'user'",
  136. )
  137. # Advanced auth validation
  138. if advanced_auth_enabled:
  139. if not user_data.email:
  140. raise HTTPException(
  141. status_code=status.HTTP_400_BAD_REQUEST,
  142. detail="Email is required when advanced authentication is enabled",
  143. )
  144. # Check if email already exists (case-insensitive)
  145. existing_email = await db.execute(select(User).where(func.lower(User.email) == func.lower(user_data.email)))
  146. if existing_email.scalar_one_or_none():
  147. raise HTTPException(
  148. status_code=status.HTTP_400_BAD_REQUEST,
  149. detail="Email already exists",
  150. )
  151. # Generate password if advanced auth enabled, otherwise require password
  152. if advanced_auth_enabled:
  153. password = generate_secure_password()
  154. else:
  155. if not user_data.password:
  156. raise HTTPException(
  157. status_code=status.HTTP_400_BAD_REQUEST,
  158. detail="Password is required when advanced authentication is disabled",
  159. )
  160. password = user_data.password
  161. new_user = User(
  162. username=user_data.username,
  163. email=user_data.email,
  164. password_hash=get_password_hash(password),
  165. role=user_data.role,
  166. is_active=True,
  167. )
  168. # Handle group assignments
  169. if user_data.group_ids:
  170. groups_result = await db.execute(select(Group).where(Group.id.in_(user_data.group_ids)))
  171. groups = groups_result.scalars().all()
  172. if len(groups) != len(user_data.group_ids):
  173. raise HTTPException(
  174. status_code=status.HTTP_400_BAD_REQUEST,
  175. detail="One or more group IDs are invalid",
  176. )
  177. new_user.groups = list(groups)
  178. elif user_data.role == "admin":
  179. admin_group = (await db.execute(select(Group).where(Group.name == ADMIN_GROUP_NAME))).scalar_one_or_none()
  180. new_user.groups = [admin_group] if admin_group else []
  181. else:
  182. new_user.groups = []
  183. # As in update_user: the groups decide, role follows (#3533).
  184. new_user.sync_role_to_groups()
  185. db.add(new_user)
  186. await db.flush()
  187. await ensure_user_finance_defaults(db, new_user)
  188. await db.commit()
  189. await db.refresh(new_user)
  190. # Send welcome email if advanced auth enabled
  191. if advanced_auth_enabled and new_user.email:
  192. try:
  193. smtp_settings = await get_smtp_settings(db)
  194. if smtp_settings:
  195. login_url = await get_external_login_url(db)
  196. subject, text_body, html_body = await create_welcome_email_from_template(
  197. db, new_user.username, password, login_url
  198. )
  199. send_email(smtp_settings, new_user.email, subject, text_body, html_body)
  200. logger.info(f"Welcome email sent to {new_user.email}")
  201. else:
  202. logger.warning(f"SMTP not configured, could not send welcome email to {new_user.email}")
  203. except Exception as e:
  204. logger.error(f"Failed to send welcome email: {e}")
  205. # Don't fail user creation if email fails
  206. return _user_to_response(new_user)
  207. @router.get("/slim", response_model=list[UserSlim])
  208. async def list_users_slim(
  209. _: User | None = RequireAnyPermissionIfAuthEnabled(Permission.USERS_READ_SLIM, Permission.USERS_READ),
  210. db: AsyncSession = Depends(get_db, scope="function"),
  211. ):
  212. """List users as ``{id, username}`` only (#1894).
  213. Exists so an API key -- or a group that should not see emails, roles and
  214. permission sets -- can turn the ``created_by_id`` values it already gets
  215. back from archives, stats and the queue into names.
  216. ``USERS_READ`` is accepted alongside ``USERS_READ_SLIM`` because it is
  217. strictly broader; groups that already hold it keep working without a
  218. permission backfill. For API keys only the slim permission resolves (the
  219. full one is unmapped = administrative), so a key reaches this and not the
  220. listing above.
  221. Declared before ``/{user_id}`` on purpose: FastAPI matches in declaration
  222. order, and the reverse order would parse "slim" as the int path parameter
  223. and answer 422.
  224. """
  225. result = await db.execute(select(User.id, User.username).order_by(User.username))
  226. return [UserSlim(id=row.id, username=row.username) for row in result.all()]
  227. @router.get("/{user_id}", response_model=UserResponse)
  228. async def get_user(
  229. user_id: int,
  230. _: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_READ),
  231. db: AsyncSession = Depends(get_db, scope="function"),
  232. ):
  233. """Get a user by ID. Read-only — gated on ``USERS_READ`` only."""
  234. result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
  235. user = result.scalar_one_or_none()
  236. if not user:
  237. raise HTTPException(
  238. status_code=status.HTTP_404_NOT_FOUND,
  239. detail="User not found",
  240. )
  241. return _user_to_response(user)
  242. async def _other_active_admins(db: AsyncSession, user_id: int) -> bool:
  243. """Is there an active admin other than this user, by role or by group?"""
  244. role_admin = await db.scalar(
  245. select(User.id).where(User.role == "admin", User.is_active.is_(True), User.id != user_id).limit(1)
  246. )
  247. if role_admin is not None:
  248. return True
  249. admin_group = (
  250. await db.execute(select(Group).where(Group.name == ADMIN_GROUP_NAME).options(selectinload(Group.users)))
  251. ).scalar_one_or_none()
  252. return any(u.is_active and u.id != user_id for u in (admin_group.users if admin_group else []))
  253. @router.patch("/{user_id}", response_model=UserResponse)
  254. async def update_user(
  255. user_id: int,
  256. user_data: UserUpdate,
  257. _admin: User | None = RequireAdminIfAuthEnabled(),
  258. _: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_UPDATE),
  259. db: AsyncSession = Depends(get_db, scope="function"),
  260. ):
  261. """Update a user."""
  262. close_sockets = False
  263. deactivated_keys: list[int] = []
  264. result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
  265. user = result.scalar_one_or_none()
  266. if not user:
  267. raise HTTPException(
  268. status_code=status.HTTP_404_NOT_FOUND,
  269. detail="User not found",
  270. )
  271. # The groups decide who is an admin, and role follows them (#3533). With
  272. # both sent, the groups win; role alone moves the user in or out of
  273. # Administrators.
  274. if user_data.role is not None and user_data.role not in ["admin", "user"]:
  275. raise HTTPException(
  276. status_code=status.HTTP_400_BAD_REQUEST,
  277. detail="Role must be 'admin' or 'user'",
  278. )
  279. new_groups: list[Group] | None = None
  280. if user_data.group_ids is not None:
  281. groups_result = await db.execute(select(Group).where(Group.id.in_(user_data.group_ids)))
  282. new_groups = list(groups_result.scalars().all())
  283. if len(new_groups) != len(user_data.group_ids):
  284. raise HTTPException(
  285. status_code=status.HTTP_400_BAD_REQUEST,
  286. detail="One or more group IDs are invalid",
  287. )
  288. elif user_data.role is not None:
  289. admin_group = (await db.execute(select(Group).where(Group.name == ADMIN_GROUP_NAME))).scalar_one_or_none()
  290. others = [g for g in user.groups if g.name != ADMIN_GROUP_NAME]
  291. new_groups = others + [admin_group] if user_data.role == "admin" and admin_group else others
  292. # Prevent leaving no active admin: by deactivation, or by taking the
  293. # admin rights away.
  294. stays_active = user.is_active if user_data.is_active is None else user_data.is_active
  295. stays_admin = user.is_admin if new_groups is None else any(g.name == ADMIN_GROUP_NAME for g in new_groups)
  296. if user.is_admin and user.is_active and not (stays_active and stays_admin):
  297. if not await _other_active_admins(db, user.id):
  298. raise HTTPException(
  299. status_code=status.HTTP_400_BAD_REQUEST,
  300. detail="Cannot deactivate the last admin user"
  301. if not stays_active
  302. else "Cannot remove admin rights from the last admin user",
  303. )
  304. if user_data.username is not None:
  305. # Check if new username already exists (case-insensitive)
  306. existing_user = await db.execute(
  307. select(User).where(func.lower(User.username) == func.lower(user_data.username), User.id != user_id)
  308. )
  309. if existing_user.scalar_one_or_none():
  310. raise HTTPException(
  311. status_code=status.HTTP_400_BAD_REQUEST,
  312. detail="Username already exists",
  313. )
  314. if user_data.username != user.username:
  315. # The name passes on: a deleted user's still-valid JWTs under the new
  316. # name must not sign this user in, and what is pending under the old
  317. # one must not reach whoever is given it next. This user's own
  318. # sessions carry the old name and end anyway. A change of case counts
  319. # too: SQLite compares only ASCII letters without case, so 'Ärger'
  320. # and 'ärger' are two names there.
  321. await drop_pending_tokens(db, user.username)
  322. user.password_changed_at = utcnow_naive()
  323. close_sockets = True
  324. user.username = user_data.username
  325. if user_data.email is not None and not user_data.email.strip():
  326. # Empty removes the email; null leaves it as it is.
  327. if user.email:
  328. rows = await db.execute(
  329. select(Settings.key, Settings.value).where(
  330. Settings.key.in_(["advanced_auth_enabled", f"user_{user.id}_email_2fa_enabled"])
  331. )
  332. )
  333. flags = {key: (value or "").lower() == "true" for key, value in rows.all()}
  334. if flags.get("advanced_auth_enabled"):
  335. raise HTTPException(
  336. status_code=status.HTTP_400_BAD_REQUEST,
  337. detail="Email is required when advanced authentication is enabled",
  338. )
  339. # Their sign-in codes go to this address.
  340. if flags.get(f"user_{user.id}_email_2fa_enabled"):
  341. raise HTTPException(
  342. status_code=status.HTTP_400_BAD_REQUEST,
  343. detail="Email is required while the user has email two-factor authentication on",
  344. )
  345. user.email = None
  346. elif user_data.email is not None:
  347. # Check if new email already exists (case-insensitive)
  348. existing_email = await db.execute(
  349. select(User).where(func.lower(User.email) == func.lower(user_data.email), User.id != user_id)
  350. )
  351. if existing_email.scalar_one_or_none():
  352. raise HTTPException(
  353. status_code=status.HTTP_400_BAD_REQUEST,
  354. detail="Email already exists",
  355. )
  356. user.email = user_data.email
  357. if user_data.password is not None:
  358. if getattr(user, "auth_source", "local") == "ldap":
  359. raise HTTPException(
  360. status_code=status.HTTP_400_BAD_REQUEST,
  361. detail="Cannot set password for LDAP users",
  362. )
  363. user.password_hash = get_password_hash(user_data.password)
  364. # As a reset: sessions and pending tokens of the old password end (an
  365. # admin setting a password is often taking an account back).
  366. await drop_pending_tokens(db, user.username)
  367. user.password_changed_at = utcnow_naive()
  368. close_sockets = True
  369. if user_data.is_active is not None:
  370. if user.is_active and not user_data.is_active:
  371. # Deactivated: their printers go at the scope refresh below, but
  372. # events of no printer (inventory, SpoolBuddy tags, announcements)
  373. # would still reach their open dashboards, and their tokens would
  374. # open new ones. The same for their API keys' (a kiosk), which
  375. # REST already refuses for a deactivated owner.
  376. from backend.app.api.routes.api_keys import drop_api_key_tokens
  377. await drop_pending_tokens(db, user.username)
  378. deactivated_keys = list(
  379. (await db.execute(select(APIKey.id).where(APIKey.user_id == user_id))).scalars().all()
  380. )
  381. await drop_api_key_tokens(db, deactivated_keys)
  382. close_sockets = True
  383. user.is_active = user_data.is_active
  384. if new_groups is not None:
  385. user.groups = new_groups
  386. user.sync_role_to_groups()
  387. await ensure_user_finance_defaults(db, user)
  388. await db.commit()
  389. if deactivated_keys:
  390. await ws_manager.close_api_keys(deactivated_keys)
  391. if close_sockets:
  392. # Open dashboards are not signed in again. After a rename they keep the
  393. # name they connected with and look their printers up by it on every
  394. # scope refresh (the next user given it); after a password set they are
  395. # whoever held the account before.
  396. await ws_manager.close_user(user_id)
  397. if user_data.group_ids is not None or user_data.role is not None or user_data.is_active is not None:
  398. # Groups, admin role and deactivation all change which printers the
  399. # user's open dashboards may hear about (#1727)
  400. await ws_manager.refresh_printer_scopes()
  401. result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
  402. user = result.scalar_one()
  403. return _user_to_response(user)
  404. @router.get("/{user_id}/items-count")
  405. async def get_user_items_count(
  406. user_id: int,
  407. _: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_READ),
  408. db: AsyncSession = Depends(get_db, scope="function"),
  409. ):
  410. """Get count of items created by this user. Read-only — gated on
  411. ``USERS_READ`` only."""
  412. # Verify user exists
  413. result = await db.execute(select(User).where(User.id == user_id))
  414. if not result.scalar_one_or_none():
  415. raise HTTPException(
  416. status_code=status.HTTP_404_NOT_FOUND,
  417. detail="User not found",
  418. )
  419. # Count archives
  420. archives_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.created_by_id == user_id))
  421. archives_count = archives_result.scalar() or 0
  422. # Count queue items
  423. queue_result = await db.execute(
  424. select(func.count(PrintQueueItem.id)).where(PrintQueueItem.created_by_id == user_id)
  425. )
  426. queue_items_count = queue_result.scalar() or 0
  427. # Count library files
  428. library_result = await db.execute(
  429. select(func.count(LibraryFile.id)).where(
  430. LibraryFile.created_by_id == user_id,
  431. LibraryFile.deleted_at.is_(None),
  432. )
  433. )
  434. library_files_count = library_result.scalar() or 0
  435. return {
  436. "archives": archives_count,
  437. "queue_items": queue_items_count,
  438. "library_files": library_files_count,
  439. }
  440. @router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
  441. async def delete_user(
  442. user_id: int,
  443. delete_items: bool = Query(False, description="Delete all items created by this user"),
  444. _admin: User | None = RequireAdminIfAuthEnabled(),
  445. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_DELETE),
  446. db: AsyncSession = Depends(get_db, scope="function"),
  447. ):
  448. """Delete a user.
  449. If delete_items=True, all archives, queue items, and library files created by
  450. this user will also be deleted. Otherwise, these items will become "ownerless"
  451. (created_by_id set to NULL by the foreign key constraint).
  452. """
  453. result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
  454. user = result.scalar_one_or_none()
  455. if not user:
  456. raise HTTPException(
  457. status_code=status.HTTP_404_NOT_FOUND,
  458. detail="User not found",
  459. )
  460. # Prevent deleting the last admin
  461. if user.is_admin:
  462. # Count admins by role or Administrators group membership
  463. admin_count_result = await db.execute(select(User).where(User.role == "admin", User.id != user_id))
  464. other_role_admins = admin_count_result.scalars().all()
  465. # Also check for users in Administrators group
  466. admin_group_result = await db.execute(
  467. select(Group).where(Group.name == "Administrators").options(selectinload(Group.users))
  468. )
  469. admin_group = admin_group_result.scalar_one_or_none()
  470. other_group_admins = [u for u in (admin_group.users if admin_group else []) if u.id != user_id and u.is_active]
  471. # Combine unique admins
  472. all_other_admins = {u.id for u in other_role_admins} | {u.id for u in other_group_admins}
  473. if len(all_other_admins) == 0:
  474. raise HTTPException(
  475. status_code=status.HTTP_400_BAD_REQUEST,
  476. detail="Cannot delete the last admin user",
  477. )
  478. # Prevent deleting yourself (only if auth is enabled and we have a current user)
  479. if current_user and user.id == current_user.id:
  480. raise HTTPException(
  481. status_code=status.HTTP_400_BAD_REQUEST,
  482. detail="Cannot delete your own account",
  483. )
  484. # Photo directories of the library rows about to go, resolved while the
  485. # rows still exist to say which ids they belong to. Removed after the
  486. # commit, so a failed delete leaves the pictures alone (#3077).
  487. doomed_library_file_ids: list[int] = []
  488. if delete_items:
  489. doomed_library_file_ids = list(
  490. (await db.execute(select(LibraryFile.id).where(LibraryFile.created_by_id == user_id))).scalars().all()
  491. )
  492. # Delete all items created by this user. The print log stays, without
  493. # the archives it pointed at; archives of other users printed from
  494. # these library files lose that link (both SET NULL on PostgreSQL).
  495. from backend.app.services.library_trash import delete_dependent_variants, release_queue_references
  496. await delete_dependent_variants(db, doomed_library_file_ids)
  497. await release_queue_references(db, doomed_library_file_ids)
  498. # A print still running keeps what it needs to be billed when it
  499. # ends: its queue row and the user's archive it prints are detached
  500. # (no user), as without delete_items, rather than deleted. Deleted, the
  501. # completion found no queue row and charged the archive's creator
  502. # instead (for a reprint someone else, who never printed it), or found
  503. # no archive and billed nothing, its reservation held for good.
  504. from sqlalchemy import and_, or_
  505. from backend.app.models.finance import BudgetReservation
  506. running_rows = (
  507. await db.execute(
  508. select(PrintQueueItem.id, PrintQueueItem.archive_id).where(
  509. PrintQueueItem.created_by_id == user_id, PrintQueueItem.status == "printing"
  510. )
  511. )
  512. ).all()
  513. running_items = [row.id for row in running_rows]
  514. running_archives = [row.archive_id for row in running_rows if row.archive_id is not None]
  515. running_archives += (
  516. (
  517. await db.execute(
  518. select(PrintArchive.id).where(
  519. PrintArchive.created_by_id == user_id, PrintArchive.status == "printing"
  520. )
  521. )
  522. )
  523. .scalars()
  524. .all()
  525. )
  526. # Also one another user is printing (a reprint of this user's archive,
  527. # dispatched before the printer's start marks the archive printing):
  528. # deleted, it took their queue row with it and their print went unbilled.
  529. own_archives = select(PrintArchive.id).where(PrintArchive.created_by_id == user_id)
  530. running_archives += (
  531. (
  532. await db.execute(
  533. select(PrintQueueItem.archive_id).where(
  534. PrintQueueItem.status == "printing", PrintQueueItem.archive_id.in_(own_archives)
  535. )
  536. )
  537. )
  538. .scalars()
  539. .all()
  540. )
  541. if running_items:
  542. await db.execute(
  543. sql_update(PrintQueueItem).where(PrintQueueItem.id.in_(running_items)).values(created_by_id=None)
  544. )
  545. if running_archives:
  546. await db.execute(
  547. sql_update(PrintArchive)
  548. .where(PrintArchive.id.in_(running_archives), PrintArchive.created_by_id == user_id)
  549. .values(created_by_id=None)
  550. )
  551. # Budget held for the queue items and archives deleted here: no print
  552. # completion can settle it any more (it finds no archive), and an
  553. # active reservation held the cost centre's budget, and kept the cost
  554. # centre from being deleted, for good. Nothing is charged for those:
  555. # they go, as the admin chose. (A running print's was detached above.)
  556. await db.execute(
  557. sql_update(BudgetReservation)
  558. .where(
  559. BudgetReservation.status == "active",
  560. or_(
  561. and_(
  562. BudgetReservation.source_type == "print_queue",
  563. BudgetReservation.source_id.in_(
  564. select(PrintQueueItem.id).where(PrintQueueItem.created_by_id == user_id)
  565. ),
  566. ),
  567. BudgetReservation.print_archive_id.in_(
  568. select(PrintArchive.id).where(PrintArchive.created_by_id == user_id)
  569. ),
  570. ),
  571. )
  572. .values(status="released", released_at=datetime.now(timezone.utc))
  573. )
  574. await db.execute(delete(PrintArchive).where(PrintArchive.created_by_id == user_id))
  575. await db.execute(delete(PrintQueueItem).where(PrintQueueItem.created_by_id == user_id))
  576. await db.execute(delete(LibraryFile).where(LibraryFile.created_by_id == user_id))
  577. await db.execute(delete(PrintBatch).where(PrintBatch.created_by_id == user_id))
  578. else:
  579. # Explicitly set created_by_id to NULL for all items (ensures consistent behavior
  580. # across different database backends, including SQLite without foreign key support).
  581. # PrintBatch carries the same created_by_id FK with ondelete=SET NULL — admin-deleted
  582. # users would otherwise leave dangling created_by_id on SQLite (#1295 review nit).
  583. from sqlalchemy import update
  584. from backend.app.core.printer_scope import resolve_user_printer_scope
  585. # An ownerless "any <model>" job may run on any printer of that model;
  586. # the scheduler held it to this user's printers only while it was
  587. # theirs (#1727). Stage those jobs instead, so an admin decides where
  588. # they run rather than the job quietly spreading across the fleet.
  589. if not (await resolve_user_printer_scope(db, user)).is_unrestricted:
  590. await db.execute(
  591. update(PrintQueueItem)
  592. .where(
  593. PrintQueueItem.created_by_id == user_id,
  594. PrintQueueItem.printer_id.is_(None),
  595. PrintQueueItem.status == "pending",
  596. )
  597. .values(manual_start=True)
  598. )
  599. await db.execute(update(PrintArchive).where(PrintArchive.created_by_id == user_id).values(created_by_id=None))
  600. await db.execute(
  601. update(PrintQueueItem).where(PrintQueueItem.created_by_id == user_id).values(created_by_id=None)
  602. )
  603. await db.execute(update(LibraryFile).where(LibraryFile.created_by_id == user_id).values(created_by_id=None))
  604. await db.execute(update(PrintBatch).where(PrintBatch.created_by_id == user_id).values(created_by_id=None))
  605. # The print log keeps who started each run as long as the user exists, and
  606. # outlives them either way (ON DELETE SET NULL, which SQLite doesn't apply).
  607. # Every run of theirs, the one printing now too.
  608. await db.execute(
  609. sql_update(PrintLogEntry)
  610. .where(PrintLogEntry.created_by_id == user_id)
  611. .values(created_by_id=None)
  612. .execution_options(include_open_runs=True)
  613. )
  614. # Drop API keys owned by this user. The model declares ON DELETE CASCADE
  615. # so Postgres handles this automatically, but SQLite ships with FK
  616. # enforcement off (the project's existing pattern — same reason the
  617. # blocks above set created_by_id = NULL by hand). Without an explicit
  618. # DELETE here, deleting a user on SQLite would leave their API keys
  619. # with a dangling user_id and ``_user_from_api_key`` would return None,
  620. # silently degrading the keys to anonymous (and locking them out of
  621. # /cloud/* — but the rest of the API would still accept them, which is
  622. # exactly the orphan-key state the CASCADE was meant to prevent).
  623. from backend.app.api.routes.api_keys import drop_api_key_tokens
  624. key_ids = (await db.execute(select(APIKey.id).where(APIKey.user_id == user_id))).scalars().all()
  625. await drop_api_key_tokens(db, key_ids)
  626. await db.execute(delete(APIKey).where(APIKey.user_id == user_id))
  627. # Drop OIDC links, MFA state, and long-lived camera-stream tokens
  628. # owned by this user. Same SQLite/FK pattern as APIKey above. Without
  629. # these, deleting a user on SQLite leaves:
  630. # - UserOIDCLink: the OIDC callback finds the orphan link, fails to
  631. # resolve the (now missing) user, and falls through to
  632. # "account_inactive" instead of triggering auto_create (#1285).
  633. # - UserTOTP: MFA secrets persist in the DB after the owning user.
  634. # - UserOTPCode: pending email OTP codes linger.
  635. # - LongLivedToken: per-user camera-stream tokens whose secret_hash
  636. # is still valid — verify() would happily match them by lookup
  637. # prefix even though the user is gone.
  638. await db.execute(delete(UserOIDCLink).where(UserOIDCLink.user_id == user_id))
  639. await db.execute(delete(UserTOTP).where(UserTOTP.user_id == user_id))
  640. await db.execute(delete(UserOTPCode).where(UserOTPCode.user_id == user_id))
  641. await db.execute(delete(LongLivedToken).where(LongLivedToken.user_id == user_id))
  642. # Connected apps, same SQLite/FK pattern. A leftover consent row would
  643. # skip the consent screen for whoever is next given this user id.
  644. from sqlalchemy import update as _update
  645. await db.execute(delete(ConnectedAppGrant).where(ConnectedAppGrant.user_id == user_id))
  646. await drop_pending_tokens(db, user.username)
  647. await db.execute(_update(ConnectedApp).where(ConnectedApp.created_by_id == user_id).values(created_by_id=None))
  648. # Email 2FA is a settings key named after the id, which no foreign key covers.
  649. await db.execute(delete(Settings).where(Settings.key == f"user_{user_id}_email_2fa_enabled"))
  650. await db.delete(user)
  651. await db.commit()
  652. # What still runs for them must not be credited to whoever gets the id next
  653. # (SQLite reuses it): a print, a slice, an open dashboard.
  654. printer_manager.forget_user(user_id)
  655. from backend.app.main import forget_print_creator
  656. forget_print_creator(user_id)
  657. slice_dispatch.forget_owner(user_id)
  658. await ws_manager.close_user(user_id)
  659. await ws_manager.close_api_keys(key_ids)
  660. from backend.app.api.routes.notifications import forget_app_senders
  661. forget_app_senders(key_ids, [user_id])
  662. await ws_manager.refresh_printer_scopes()
  663. for file_id in doomed_library_file_ids:
  664. remove_library_photos_dir(file_id)
  665. @router.post("/me/change-password", response_model=dict)
  666. async def change_own_password(
  667. password_data: ChangePasswordRequest,
  668. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  669. current_user: User | None = Depends(get_current_user_optional),
  670. db: AsyncSession = Depends(get_db, scope="function"),
  671. ):
  672. """Change the current user's password. Requires current password verification."""
  673. if not current_user:
  674. raise HTTPException(
  675. status_code=status.HTTP_401_UNAUTHORIZED,
  676. detail="Authentication required to change password",
  677. )
  678. # Block password change for LDAP users
  679. if getattr(current_user, "auth_source", "local") == "ldap":
  680. raise HTTPException(
  681. status_code=status.HTTP_400_BAD_REQUEST,
  682. detail="Cannot change password for LDAP users — passwords are managed by the LDAP server",
  683. )
  684. # Verify current password
  685. if not current_user.password_hash:
  686. raise HTTPException(
  687. status_code=status.HTTP_400_BAD_REQUEST,
  688. detail="Account has no local password set",
  689. )
  690. # Rate-limit failed password-change attempts (H-R5-A)
  691. from backend.app.api.routes.mfa import MAX_2FA_ATTEMPTS, check_rate_limit, record_failed_attempt
  692. await check_rate_limit(db, current_user.username, event_type="password_change", max_attempts=MAX_2FA_ATTEMPTS)
  693. if not verify_password(password_data.current_password, current_user.password_hash):
  694. await record_failed_attempt(db, current_user.username, event_type="password_change")
  695. raise HTTPException(
  696. status_code=status.HTTP_400_BAD_REQUEST,
  697. detail="Current password is incorrect",
  698. )
  699. # Fetch user from this session to ensure changes are persisted
  700. result = await db.execute(select(User).where(User.id == current_user.id))
  701. user = result.scalar_one_or_none()
  702. if not user:
  703. raise HTTPException(
  704. status_code=status.HTTP_404_NOT_FOUND,
  705. detail="User not found",
  706. )
  707. # Update password
  708. user.password_hash = get_password_hash(password_data.new_password)
  709. user.password_changed_at = datetime.now(timezone.utc) # M-R7-B: invalidate all prior JWTs
  710. # The WebSocket and camera tokens too: reusable for an hour, they would
  711. # reconnect a closed dashboard straight away.
  712. await drop_pending_tokens(db, user.username)
  713. await db.commit()
  714. # Open dashboards are never signed in again: one someone else had open on
  715. # the account would keep receiving its printers. This tab signs in again
  716. # (the route revokes its JWT anyway).
  717. await ws_manager.close_user(user.id)
  718. # L-R6-A: Password verified successfully — reset the failure counter
  719. from backend.app.api.routes.mfa import clear_failed_attempts
  720. await clear_failed_attempts(db, user.username, event_type="password_change")
  721. # Revoke the current session token so the caller must re-authenticate (M-R5-A)
  722. if credentials is not None:
  723. try:
  724. payload = _jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
  725. jti = payload.get("jti")
  726. exp = payload.get("exp")
  727. if jti and exp:
  728. try:
  729. await revoke_jti(jti, datetime.fromtimestamp(exp, tz=timezone.utc), user.username)
  730. except Exception as exc:
  731. # B4: log so operators know revocation is broken; password was
  732. # already changed so the token will fail freshness checks anyway.
  733. import logging
  734. logging.getLogger(__name__).error(
  735. "Failed to revoke JTI after password change for user %s: %s", user.username, exc
  736. )
  737. except Exception:
  738. pass # Decode failure is harmless — token is already invalidated by password_changed_at
  739. return {"message": "Password changed successfully"}