users.py 26 KB

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