users.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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
  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.models.api_key import APIKey
  25. from backend.app.models.archive import PrintArchive
  26. from backend.app.models.group import Group
  27. from backend.app.models.library import LibraryFile
  28. from backend.app.models.long_lived_token import LongLivedToken
  29. from backend.app.models.oidc_provider import UserOIDCLink
  30. from backend.app.models.print_batch import PrintBatch
  31. from backend.app.models.print_queue import PrintQueueItem
  32. from backend.app.models.settings import Settings
  33. from backend.app.models.user import User
  34. from backend.app.models.user_otp_code import UserOTPCode
  35. from backend.app.models.user_totp import UserTOTP
  36. from backend.app.schemas.auth import (
  37. ChangePasswordRequest,
  38. GroupBrief,
  39. UserCreate,
  40. UserResponse,
  41. UserSlim,
  42. UserUpdate,
  43. )
  44. from backend.app.services.email_service import (
  45. create_welcome_email_from_template,
  46. generate_secure_password,
  47. get_smtp_settings,
  48. send_email,
  49. )
  50. from backend.app.services.finance_defaults import ensure_user_finance_defaults
  51. router = APIRouter(prefix="/users", tags=["users"])
  52. def _user_to_response(user: User) -> UserResponse:
  53. """Convert a User model to UserResponse schema."""
  54. return UserResponse(
  55. id=user.id,
  56. username=user.username,
  57. email=user.email,
  58. role=user.role,
  59. is_active=user.is_active,
  60. is_admin=user.is_admin,
  61. auth_source=getattr(user, "auth_source", "local"),
  62. groups=[GroupBrief(id=g.id, name=g.name) for g in user.groups],
  63. permissions=sorted(user.get_permissions()),
  64. created_at=user.created_at.isoformat(),
  65. )
  66. @router.get("", response_model=list[UserResponse])
  67. @router.get("/", response_model=list[UserResponse])
  68. async def list_users(
  69. _: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_READ),
  70. db: AsyncSession = Depends(get_db),
  71. ):
  72. """List all users.
  73. Read-only — gated on ``USERS_READ`` only. Operator-visible UIs
  74. (Stats filter-by-user, Archives Print Log username column, File
  75. Manager username autocomplete) consume this endpoint via custom-
  76. group ``users:read`` grants without admin role. The admin-only
  77. boundary lives on the write endpoints below."""
  78. result = await db.execute(select(User).options(selectinload(User.groups)).order_by(User.created_at))
  79. users = result.scalars().all()
  80. return [_user_to_response(user) for user in users]
  81. @router.post("", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
  82. @router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
  83. async def create_user(
  84. user_data: UserCreate,
  85. _admin: User | None = RequireAdminIfAuthEnabled(),
  86. _: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_CREATE),
  87. db: AsyncSession = Depends(get_db),
  88. ):
  89. """Create a new user.
  90. When advanced authentication is enabled:
  91. - Email is required
  92. - Password is auto-generated and emailed to user
  93. - Admin cannot set or see the password
  94. """
  95. import logging
  96. logger = logging.getLogger(__name__)
  97. # Check if advanced auth is enabled
  98. result = await db.execute(select(Settings).where(Settings.key == "advanced_auth_enabled"))
  99. advanced_auth_setting = result.scalar_one_or_none()
  100. advanced_auth_enabled = advanced_auth_setting and advanced_auth_setting.value.lower() == "true"
  101. # Check if username already exists (case-insensitive)
  102. existing_user = await db.execute(select(User).where(func.lower(User.username) == func.lower(user_data.username)))
  103. if existing_user.scalar_one_or_none():
  104. raise HTTPException(
  105. status_code=status.HTTP_400_BAD_REQUEST,
  106. detail="Username already exists",
  107. )
  108. # Validate role
  109. if user_data.role not in ["admin", "user"]:
  110. raise HTTPException(
  111. status_code=status.HTTP_400_BAD_REQUEST,
  112. detail="Role must be 'admin' or 'user'",
  113. )
  114. # Advanced auth validation
  115. if advanced_auth_enabled:
  116. if not user_data.email:
  117. raise HTTPException(
  118. status_code=status.HTTP_400_BAD_REQUEST,
  119. detail="Email is required when advanced authentication is enabled",
  120. )
  121. # Check if email already exists (case-insensitive)
  122. existing_email = await db.execute(select(User).where(func.lower(User.email) == func.lower(user_data.email)))
  123. if existing_email.scalar_one_or_none():
  124. raise HTTPException(
  125. status_code=status.HTTP_400_BAD_REQUEST,
  126. detail="Email already exists",
  127. )
  128. # Generate password if advanced auth enabled, otherwise require password
  129. if advanced_auth_enabled:
  130. password = generate_secure_password()
  131. else:
  132. if not user_data.password:
  133. raise HTTPException(
  134. status_code=status.HTTP_400_BAD_REQUEST,
  135. detail="Password is required when advanced authentication is disabled",
  136. )
  137. password = user_data.password
  138. new_user = User(
  139. username=user_data.username,
  140. email=user_data.email,
  141. password_hash=get_password_hash(password),
  142. role=user_data.role,
  143. is_active=True,
  144. )
  145. # Handle group assignments
  146. if user_data.group_ids:
  147. groups_result = await db.execute(select(Group).where(Group.id.in_(user_data.group_ids)))
  148. groups = groups_result.scalars().all()
  149. if len(groups) != len(user_data.group_ids):
  150. raise HTTPException(
  151. status_code=status.HTTP_400_BAD_REQUEST,
  152. detail="One or more group IDs are invalid",
  153. )
  154. new_user.groups = list(groups)
  155. db.add(new_user)
  156. await db.flush()
  157. await ensure_user_finance_defaults(db, new_user)
  158. await db.commit()
  159. await db.refresh(new_user)
  160. # Send welcome email if advanced auth enabled
  161. if advanced_auth_enabled and new_user.email:
  162. try:
  163. smtp_settings = await get_smtp_settings(db)
  164. if smtp_settings:
  165. login_url = await get_external_login_url(db)
  166. subject, text_body, html_body = await create_welcome_email_from_template(
  167. db, new_user.username, password, login_url
  168. )
  169. send_email(smtp_settings, new_user.email, subject, text_body, html_body)
  170. logger.info(f"Welcome email sent to {new_user.email}")
  171. else:
  172. logger.warning(f"SMTP not configured, could not send welcome email to {new_user.email}")
  173. except Exception as e:
  174. logger.error(f"Failed to send welcome email: {e}")
  175. # Don't fail user creation if email fails
  176. return _user_to_response(new_user)
  177. @router.get("/slim", response_model=list[UserSlim])
  178. async def list_users_slim(
  179. _: User | None = RequireAnyPermissionIfAuthEnabled(Permission.USERS_READ_SLIM, Permission.USERS_READ),
  180. db: AsyncSession = Depends(get_db),
  181. ):
  182. """List users as ``{id, username}`` only (#1894).
  183. Exists so an API key -- or a group that should not see emails, roles and
  184. permission sets -- can turn the ``created_by_id`` values it already gets
  185. back from archives, stats and the queue into names.
  186. ``USERS_READ`` is accepted alongside ``USERS_READ_SLIM`` because it is
  187. strictly broader; groups that already hold it keep working without a
  188. permission backfill. For API keys only the slim permission resolves (the
  189. full one is unmapped = administrative), so a key reaches this and not the
  190. listing above.
  191. Declared before ``/{user_id}`` on purpose: FastAPI matches in declaration
  192. order, and the reverse order would parse "slim" as the int path parameter
  193. and answer 422.
  194. """
  195. result = await db.execute(select(User.id, User.username).order_by(User.username))
  196. return [UserSlim(id=row.id, username=row.username) for row in result.all()]
  197. @router.get("/{user_id}", response_model=UserResponse)
  198. async def get_user(
  199. user_id: int,
  200. _: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_READ),
  201. db: AsyncSession = Depends(get_db),
  202. ):
  203. """Get a user by ID. Read-only — gated on ``USERS_READ`` only."""
  204. result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
  205. user = result.scalar_one_or_none()
  206. if not user:
  207. raise HTTPException(
  208. status_code=status.HTTP_404_NOT_FOUND,
  209. detail="User not found",
  210. )
  211. return _user_to_response(user)
  212. @router.patch("/{user_id}", response_model=UserResponse)
  213. async def update_user(
  214. user_id: int,
  215. user_data: UserUpdate,
  216. _admin: User | None = RequireAdminIfAuthEnabled(),
  217. _: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_UPDATE),
  218. db: AsyncSession = Depends(get_db),
  219. ):
  220. """Update a user."""
  221. result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
  222. user = result.scalar_one_or_none()
  223. if not user:
  224. raise HTTPException(
  225. status_code=status.HTTP_404_NOT_FOUND,
  226. detail="User not found",
  227. )
  228. # Prevent deactivating the last admin
  229. if user_data.is_active is False and user.is_admin:
  230. # Count admins by role or Administrators group membership
  231. admin_count_result = await db.execute(select(User).where(User.role == "admin", User.is_active.is_(True)))
  232. role_admins = admin_count_result.scalars().all()
  233. # Also check for users in Administrators group
  234. admin_group_result = await db.execute(
  235. select(Group).where(Group.name == "Administrators").options(selectinload(Group.users))
  236. )
  237. admin_group = admin_group_result.scalar_one_or_none()
  238. group_admins = [u for u in (admin_group.users if admin_group else []) if u.is_active]
  239. # Combine unique admins
  240. all_admins = {u.id for u in role_admins} | {u.id for u in group_admins}
  241. if len(all_admins) <= 1 and user.id in all_admins:
  242. raise HTTPException(
  243. status_code=status.HTTP_400_BAD_REQUEST,
  244. detail="Cannot deactivate the last admin user",
  245. )
  246. # Prevent changing role of last admin
  247. if user_data.role and user_data.role != "admin" and user.role == "admin":
  248. admin_count_result = await db.execute(select(User).where(User.role == "admin", User.is_active.is_(True)))
  249. admin_count = len(admin_count_result.scalars().all())
  250. if admin_count <= 1:
  251. raise HTTPException(
  252. status_code=status.HTTP_400_BAD_REQUEST,
  253. detail="Cannot change role of the last admin user",
  254. )
  255. if user_data.username is not None:
  256. # Check if new username already exists (case-insensitive)
  257. existing_user = await db.execute(
  258. select(User).where(func.lower(User.username) == func.lower(user_data.username), User.id != user_id)
  259. )
  260. if existing_user.scalar_one_or_none():
  261. raise HTTPException(
  262. status_code=status.HTTP_400_BAD_REQUEST,
  263. detail="Username already exists",
  264. )
  265. user.username = user_data.username
  266. if user_data.email is not None:
  267. # Check if new email already exists (case-insensitive)
  268. existing_email = await db.execute(
  269. select(User).where(func.lower(User.email) == func.lower(user_data.email), User.id != user_id)
  270. )
  271. if existing_email.scalar_one_or_none():
  272. raise HTTPException(
  273. status_code=status.HTTP_400_BAD_REQUEST,
  274. detail="Email already exists",
  275. )
  276. user.email = user_data.email
  277. if user_data.password is not None:
  278. if getattr(user, "auth_source", "local") == "ldap":
  279. raise HTTPException(
  280. status_code=status.HTTP_400_BAD_REQUEST,
  281. detail="Cannot set password for LDAP users",
  282. )
  283. user.password_hash = get_password_hash(user_data.password)
  284. if user_data.role is not None:
  285. if user_data.role not in ["admin", "user"]:
  286. raise HTTPException(
  287. status_code=status.HTTP_400_BAD_REQUEST,
  288. detail="Role must be 'admin' or 'user'",
  289. )
  290. user.role = user_data.role
  291. if user_data.is_active is not None:
  292. user.is_active = user_data.is_active
  293. # Handle group assignments
  294. if user_data.group_ids is not None:
  295. groups_result = await db.execute(select(Group).where(Group.id.in_(user_data.group_ids)))
  296. groups = groups_result.scalars().all()
  297. if len(groups) != len(user_data.group_ids):
  298. raise HTTPException(
  299. status_code=status.HTTP_400_BAD_REQUEST,
  300. detail="One or more group IDs are invalid",
  301. )
  302. user.groups = list(groups)
  303. await ensure_user_finance_defaults(db, user)
  304. await db.commit()
  305. result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
  306. user = result.scalar_one()
  307. return _user_to_response(user)
  308. @router.get("/{user_id}/items-count")
  309. async def get_user_items_count(
  310. user_id: int,
  311. _: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_READ),
  312. db: AsyncSession = Depends(get_db),
  313. ):
  314. """Get count of items created by this user. Read-only — gated on
  315. ``USERS_READ`` only."""
  316. # Verify user exists
  317. result = await db.execute(select(User).where(User.id == user_id))
  318. if not result.scalar_one_or_none():
  319. raise HTTPException(
  320. status_code=status.HTTP_404_NOT_FOUND,
  321. detail="User not found",
  322. )
  323. # Count archives
  324. archives_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.created_by_id == user_id))
  325. archives_count = archives_result.scalar() or 0
  326. # Count queue items
  327. queue_result = await db.execute(
  328. select(func.count(PrintQueueItem.id)).where(PrintQueueItem.created_by_id == user_id)
  329. )
  330. queue_items_count = queue_result.scalar() or 0
  331. # Count library files
  332. library_result = await db.execute(
  333. select(func.count(LibraryFile.id)).where(
  334. LibraryFile.created_by_id == user_id,
  335. LibraryFile.deleted_at.is_(None),
  336. )
  337. )
  338. library_files_count = library_result.scalar() or 0
  339. return {
  340. "archives": archives_count,
  341. "queue_items": queue_items_count,
  342. "library_files": library_files_count,
  343. }
  344. @router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
  345. async def delete_user(
  346. user_id: int,
  347. delete_items: bool = Query(False, description="Delete all items created by this user"),
  348. _admin: User | None = RequireAdminIfAuthEnabled(),
  349. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.USERS_DELETE),
  350. db: AsyncSession = Depends(get_db),
  351. ):
  352. """Delete a user.
  353. If delete_items=True, all archives, queue items, and library files created by
  354. this user will also be deleted. Otherwise, these items will become "ownerless"
  355. (created_by_id set to NULL by the foreign key constraint).
  356. """
  357. result = await db.execute(select(User).where(User.id == user_id).options(selectinload(User.groups)))
  358. user = result.scalar_one_or_none()
  359. if not user:
  360. raise HTTPException(
  361. status_code=status.HTTP_404_NOT_FOUND,
  362. detail="User not found",
  363. )
  364. # Prevent deleting the last admin
  365. if user.is_admin:
  366. # Count admins by role or Administrators group membership
  367. admin_count_result = await db.execute(select(User).where(User.role == "admin", User.id != user_id))
  368. other_role_admins = admin_count_result.scalars().all()
  369. # Also check for users in Administrators group
  370. admin_group_result = await db.execute(
  371. select(Group).where(Group.name == "Administrators").options(selectinload(Group.users))
  372. )
  373. admin_group = admin_group_result.scalar_one_or_none()
  374. other_group_admins = [u for u in (admin_group.users if admin_group else []) if u.id != user_id and u.is_active]
  375. # Combine unique admins
  376. all_other_admins = {u.id for u in other_role_admins} | {u.id for u in other_group_admins}
  377. if len(all_other_admins) == 0:
  378. raise HTTPException(
  379. status_code=status.HTTP_400_BAD_REQUEST,
  380. detail="Cannot delete the last admin user",
  381. )
  382. # Prevent deleting yourself (only if auth is enabled and we have a current user)
  383. if current_user and user.id == current_user.id:
  384. raise HTTPException(
  385. status_code=status.HTTP_400_BAD_REQUEST,
  386. detail="Cannot delete your own account",
  387. )
  388. if delete_items:
  389. # Delete all items created by this user
  390. await db.execute(delete(PrintArchive).where(PrintArchive.created_by_id == user_id))
  391. await db.execute(delete(PrintQueueItem).where(PrintQueueItem.created_by_id == user_id))
  392. await db.execute(delete(LibraryFile).where(LibraryFile.created_by_id == user_id))
  393. await db.execute(delete(PrintBatch).where(PrintBatch.created_by_id == user_id))
  394. else:
  395. # Explicitly set created_by_id to NULL for all items (ensures consistent behavior
  396. # across different database backends, including SQLite without foreign key support).
  397. # PrintBatch carries the same created_by_id FK with ondelete=SET NULL — admin-deleted
  398. # users would otherwise leave dangling created_by_id on SQLite (#1295 review nit).
  399. from sqlalchemy import update
  400. await db.execute(update(PrintArchive).where(PrintArchive.created_by_id == user_id).values(created_by_id=None))
  401. await db.execute(
  402. update(PrintQueueItem).where(PrintQueueItem.created_by_id == user_id).values(created_by_id=None)
  403. )
  404. await db.execute(update(LibraryFile).where(LibraryFile.created_by_id == user_id).values(created_by_id=None))
  405. await db.execute(update(PrintBatch).where(PrintBatch.created_by_id == user_id).values(created_by_id=None))
  406. # Drop API keys owned by this user. The model declares ON DELETE CASCADE
  407. # so Postgres handles this automatically, but SQLite ships with FK
  408. # enforcement off (the project's existing pattern — same reason the
  409. # blocks above set created_by_id = NULL by hand). Without an explicit
  410. # DELETE here, deleting a user on SQLite would leave their API keys
  411. # with a dangling user_id and ``_user_from_api_key`` would return None,
  412. # silently degrading the keys to anonymous (and locking them out of
  413. # /cloud/* — but the rest of the API would still accept them, which is
  414. # exactly the orphan-key state the CASCADE was meant to prevent).
  415. await db.execute(delete(APIKey).where(APIKey.user_id == user_id))
  416. # Drop OIDC links, MFA state, and long-lived camera-stream tokens
  417. # owned by this user. Same SQLite/FK pattern as APIKey above. Without
  418. # these, deleting a user on SQLite leaves:
  419. # - UserOIDCLink: the OIDC callback finds the orphan link, fails to
  420. # resolve the (now missing) user, and falls through to
  421. # "account_inactive" instead of triggering auto_create (#1285).
  422. # - UserTOTP: MFA secrets persist in the DB after the owning user.
  423. # - UserOTPCode: pending email OTP codes linger.
  424. # - LongLivedToken: per-user camera-stream tokens whose secret_hash
  425. # is still valid — verify() would happily match them by lookup
  426. # prefix even though the user is gone.
  427. await db.execute(delete(UserOIDCLink).where(UserOIDCLink.user_id == user_id))
  428. await db.execute(delete(UserTOTP).where(UserTOTP.user_id == user_id))
  429. await db.execute(delete(UserOTPCode).where(UserOTPCode.user_id == user_id))
  430. await db.execute(delete(LongLivedToken).where(LongLivedToken.user_id == user_id))
  431. await db.delete(user)
  432. await db.commit()
  433. @router.post("/me/change-password", response_model=dict)
  434. async def change_own_password(
  435. password_data: ChangePasswordRequest,
  436. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  437. current_user: User | None = Depends(get_current_user_optional),
  438. db: AsyncSession = Depends(get_db),
  439. ):
  440. """Change the current user's password. Requires current password verification."""
  441. if not current_user:
  442. raise HTTPException(
  443. status_code=status.HTTP_401_UNAUTHORIZED,
  444. detail="Authentication required to change password",
  445. )
  446. # Block password change for LDAP users
  447. if getattr(current_user, "auth_source", "local") == "ldap":
  448. raise HTTPException(
  449. status_code=status.HTTP_400_BAD_REQUEST,
  450. detail="Cannot change password for LDAP users — passwords are managed by the LDAP server",
  451. )
  452. # Verify current password
  453. if not current_user.password_hash:
  454. raise HTTPException(
  455. status_code=status.HTTP_400_BAD_REQUEST,
  456. detail="Account has no local password set",
  457. )
  458. # Rate-limit failed password-change attempts (H-R5-A)
  459. from backend.app.api.routes.mfa import MAX_2FA_ATTEMPTS, check_rate_limit, record_failed_attempt
  460. await check_rate_limit(db, current_user.username, event_type="password_change", max_attempts=MAX_2FA_ATTEMPTS)
  461. if not verify_password(password_data.current_password, current_user.password_hash):
  462. await record_failed_attempt(db, current_user.username, event_type="password_change")
  463. raise HTTPException(
  464. status_code=status.HTTP_400_BAD_REQUEST,
  465. detail="Current password is incorrect",
  466. )
  467. # Fetch user from this session to ensure changes are persisted
  468. result = await db.execute(select(User).where(User.id == current_user.id))
  469. user = result.scalar_one_or_none()
  470. if not user:
  471. raise HTTPException(
  472. status_code=status.HTTP_404_NOT_FOUND,
  473. detail="User not found",
  474. )
  475. # Update password
  476. user.password_hash = get_password_hash(password_data.new_password)
  477. user.password_changed_at = datetime.now(timezone.utc) # M-R7-B: invalidate all prior JWTs
  478. await db.commit()
  479. # L-R6-A: Password verified successfully — reset the failure counter
  480. from backend.app.api.routes.mfa import clear_failed_attempts
  481. await clear_failed_attempts(db, user.username, event_type="password_change")
  482. # Revoke the current session token so the caller must re-authenticate (M-R5-A)
  483. if credentials is not None:
  484. try:
  485. payload = _jwt.decode(credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM])
  486. jti = payload.get("jti")
  487. exp = payload.get("exp")
  488. if jti and exp:
  489. try:
  490. await revoke_jti(jti, datetime.fromtimestamp(exp, tz=timezone.utc), user.username)
  491. except Exception as exc:
  492. # B4: log so operators know revocation is broken; password was
  493. # already changed so the token will fail freshness checks anyway.
  494. import logging
  495. logging.getLogger(__name__).error(
  496. "Failed to revoke JTI after password change for user %s: %s", user.username, exc
  497. )
  498. except Exception:
  499. pass # Decode failure is harmless — token is already invalidated by password_changed_at
  500. return {"message": "Password changed successfully"}