auth.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. from datetime import timedelta
  2. from typing import Annotated
  3. from fastapi import APIRouter, Depends, Header, HTTPException, status
  4. from fastapi.security import HTTPAuthorizationCredentials
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from sqlalchemy.orm import selectinload
  8. from backend.app.api.routes.settings import get_external_login_url
  9. from backend.app.core.auth import (
  10. ACCESS_TOKEN_EXPIRE_MINUTES,
  11. ALGORITHM,
  12. SECRET_KEY,
  13. Permission,
  14. RequirePermissionIfAuthEnabled,
  15. _validate_api_key,
  16. authenticate_user,
  17. authenticate_user_by_email,
  18. create_access_token,
  19. get_current_active_user,
  20. get_password_hash,
  21. get_user_by_email,
  22. get_user_by_username,
  23. security,
  24. )
  25. from backend.app.core.database import get_db
  26. from backend.app.core.permissions import ALL_PERMISSIONS
  27. from backend.app.models.group import Group
  28. from backend.app.models.settings import Settings
  29. from backend.app.models.user import User
  30. from backend.app.schemas.auth import (
  31. ForgotPasswordRequest,
  32. ForgotPasswordResponse,
  33. GroupBrief,
  34. LoginRequest,
  35. LoginResponse,
  36. ResetPasswordRequest,
  37. ResetPasswordResponse,
  38. SetupRequest,
  39. SetupResponse,
  40. SMTPSettings,
  41. TestSMTPRequest,
  42. TestSMTPResponse,
  43. UserResponse,
  44. )
  45. from backend.app.services.email_service import (
  46. create_password_reset_email_from_template,
  47. generate_secure_password,
  48. get_smtp_settings,
  49. save_smtp_settings,
  50. send_email,
  51. )
  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. groups=[GroupBrief(id=g.id, name=g.name) for g in user.groups],
  62. permissions=sorted(user.get_permissions()),
  63. created_at=user.created_at.isoformat(),
  64. )
  65. def _api_key_to_user_response(api_key) -> UserResponse:
  66. """Create a synthetic admin UserResponse for a valid API key."""
  67. return UserResponse(
  68. id=0,
  69. username=f"api-key:{api_key.key_prefix}",
  70. email=None,
  71. role="admin",
  72. is_active=True,
  73. is_admin=True,
  74. groups=[],
  75. permissions=sorted(ALL_PERMISSIONS),
  76. created_at=api_key.created_at.isoformat(),
  77. )
  78. router = APIRouter(prefix="/auth", tags=["authentication"])
  79. async def is_auth_enabled(db: AsyncSession) -> bool:
  80. """Check if authentication is enabled."""
  81. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  82. setting = result.scalar_one_or_none()
  83. if setting is None:
  84. return False
  85. return setting.value.lower() == "true"
  86. async def is_advanced_auth_enabled(db: AsyncSession) -> bool:
  87. """Check if advanced authentication is enabled."""
  88. result = await db.execute(select(Settings).where(Settings.key == "advanced_auth_enabled"))
  89. setting = result.scalar_one_or_none()
  90. if setting is None:
  91. return False
  92. return setting.value.lower() == "true"
  93. async def set_advanced_auth_enabled(db: AsyncSession, enabled: bool) -> None:
  94. """Set advanced authentication enabled status."""
  95. from sqlalchemy import func
  96. from sqlalchemy.dialects.sqlite import insert as sqlite_insert
  97. stmt = sqlite_insert(Settings).values(key="advanced_auth_enabled", value="true" if enabled else "false")
  98. stmt = stmt.on_conflict_do_update(
  99. index_elements=["key"], set_={"value": "true" if enabled else "false", "updated_at": func.now()}
  100. )
  101. await db.execute(stmt)
  102. async def set_auth_enabled(db: AsyncSession, enabled: bool) -> None:
  103. """Set authentication enabled status."""
  104. from sqlalchemy import func
  105. from sqlalchemy.dialects.sqlite import insert as sqlite_insert
  106. stmt = sqlite_insert(Settings).values(key="auth_enabled", value="true" if enabled else "false")
  107. stmt = stmt.on_conflict_do_update(
  108. index_elements=["key"], set_={"value": "true" if enabled else "false", "updated_at": func.now()}
  109. )
  110. await db.execute(stmt)
  111. # Note: Don't commit here - let get_db handle it or commit explicitly in the route
  112. async def is_setup_completed(db: AsyncSession) -> bool:
  113. """Check if setup has been completed."""
  114. result = await db.execute(select(Settings).where(Settings.key == "setup_completed"))
  115. setting = result.scalar_one_or_none()
  116. return setting and setting.value.lower() == "true"
  117. async def set_setup_completed(db: AsyncSession, completed: bool) -> None:
  118. """Set setup completed status."""
  119. from sqlalchemy import func
  120. from sqlalchemy.dialects.sqlite import insert as sqlite_insert
  121. stmt = sqlite_insert(Settings).values(key="setup_completed", value="true" if completed else "false")
  122. stmt = stmt.on_conflict_do_update(
  123. index_elements=["key"], set_={"value": "true" if completed else "false", "updated_at": func.now()}
  124. )
  125. await db.execute(stmt)
  126. # Note: Don't commit here - let get_db handle it or commit explicitly in the route
  127. @router.post("/setup", response_model=SetupResponse)
  128. async def setup_auth(request: SetupRequest, db: AsyncSession = Depends(get_db)):
  129. """First-time setup: enable/disable authentication and create admin user."""
  130. import logging
  131. logger = logging.getLogger(__name__)
  132. try:
  133. # If auth_enabled is true but no users exist, allow re-setup (recovery scenario)
  134. admin_created = False
  135. if request.auth_enabled:
  136. # Check if admin users already exist
  137. admin_users_result = await db.execute(select(User).where(User.role == "admin"))
  138. existing_admin_users = list(admin_users_result.scalars().all())
  139. has_admin_users = len(existing_admin_users) > 0
  140. if has_admin_users:
  141. # Admin users already exist, just enable auth (don't create new admin)
  142. logger.info(
  143. f"Admin users already exist ({len(existing_admin_users)} found), enabling authentication without creating new admin"
  144. )
  145. admin_created = False
  146. else:
  147. # No admin users exist, require admin credentials to create first admin
  148. if not request.admin_username or not request.admin_password:
  149. raise HTTPException(
  150. status_code=status.HTTP_400_BAD_REQUEST,
  151. detail="Admin username and password are required when enabling authentication (no admin users exist)",
  152. )
  153. # Check if username already exists (shouldn't happen if no admin users exist, but check anyway)
  154. existing_user = await get_user_by_username(db, request.admin_username)
  155. if existing_user:
  156. raise HTTPException(
  157. status_code=status.HTTP_400_BAD_REQUEST,
  158. detail="User with this username already exists",
  159. )
  160. # Create admin user FIRST (before enabling auth)
  161. try:
  162. logger.info("Creating admin user: %s", request.admin_username)
  163. admin_user = User(
  164. username=request.admin_username,
  165. password_hash=get_password_hash(request.admin_password),
  166. role="admin",
  167. is_active=True,
  168. )
  169. # Try to add user to Administrators group if it exists
  170. admin_group_result = await db.execute(select(Group).where(Group.name == "Administrators"))
  171. admin_group = admin_group_result.scalar_one_or_none()
  172. if admin_group:
  173. admin_user.groups.append(admin_group)
  174. logger.info("Added new admin user to Administrators group")
  175. db.add(admin_user)
  176. logger.info("Admin user added to session: %s", request.admin_username)
  177. admin_created = True
  178. except Exception as e:
  179. await db.rollback()
  180. logger.error("Failed to create admin user: %s", e, exc_info=True)
  181. raise HTTPException(
  182. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  183. detail=f"Failed to create admin user: {str(e)}",
  184. )
  185. # Set auth enabled and mark setup as completed
  186. await set_auth_enabled(db, request.auth_enabled)
  187. await set_setup_completed(db, True)
  188. await db.commit()
  189. if admin_created:
  190. await db.refresh(admin_user)
  191. logger.info("Admin user created successfully: %s", admin_user.id)
  192. logger.info("Setup completed: auth_enabled=%s, admin_created=%s", request.auth_enabled, admin_created)
  193. return SetupResponse(auth_enabled=request.auth_enabled, admin_created=admin_created)
  194. except HTTPException:
  195. raise
  196. except Exception as e:
  197. logger.error("Setup error: %s", e, exc_info=True)
  198. await db.rollback()
  199. raise HTTPException(
  200. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  201. detail=f"Setup failed: {str(e)}",
  202. )
  203. @router.get("/status")
  204. async def get_auth_status(db: AsyncSession = Depends(get_db)):
  205. """Get authentication status (public endpoint)."""
  206. auth_enabled = await is_auth_enabled(db)
  207. setup_completed = await is_setup_completed(db)
  208. # Only require setup if it hasn't been completed yet
  209. requires_setup = not setup_completed
  210. return {"auth_enabled": auth_enabled, "requires_setup": requires_setup}
  211. @router.post("/disable", response_model=dict)
  212. async def disable_auth(
  213. current_user: User = Depends(get_current_active_user),
  214. db: AsyncSession = Depends(get_db),
  215. ):
  216. """Disable authentication (admin only)."""
  217. import logging
  218. logger = logging.getLogger(__name__)
  219. # Reload user with groups for proper is_admin check
  220. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  221. user = result.scalar_one()
  222. # Only admins can disable authentication
  223. if not user.is_admin:
  224. raise HTTPException(
  225. status_code=status.HTTP_403_FORBIDDEN,
  226. detail="Only admins can disable authentication",
  227. )
  228. try:
  229. await set_auth_enabled(db, False)
  230. await db.commit()
  231. logger.info("Authentication disabled by admin user: %s", user.username)
  232. return {"message": "Authentication disabled successfully", "auth_enabled": False}
  233. except Exception as e:
  234. await db.rollback()
  235. logger.error("Failed to disable authentication: %s", e, exc_info=True)
  236. raise HTTPException(
  237. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  238. detail=f"Failed to disable authentication: {str(e)}",
  239. )
  240. @router.post("/login", response_model=LoginResponse)
  241. async def login(request: LoginRequest, db: AsyncSession = Depends(get_db)):
  242. """Login and get access token.
  243. Supports username or email-based login. Username lookup is case-insensitive.
  244. """
  245. # Check if auth is enabled
  246. auth_enabled = await is_auth_enabled(db)
  247. if not auth_enabled:
  248. raise HTTPException(
  249. status_code=status.HTTP_400_BAD_REQUEST,
  250. detail="Authentication is not enabled",
  251. )
  252. # Try username-based authentication first
  253. user = await authenticate_user(db, request.username, request.password)
  254. # If username auth failed and advanced auth is enabled, try email-based authentication
  255. if not user:
  256. advanced_auth = await is_advanced_auth_enabled(db)
  257. if advanced_auth:
  258. user = await authenticate_user_by_email(db, request.username, request.password)
  259. if not user:
  260. raise HTTPException(
  261. status_code=status.HTTP_401_UNAUTHORIZED,
  262. detail="Incorrect username or password",
  263. headers={"WWW-Authenticate": "Bearer"},
  264. )
  265. # Reload user with groups for proper permission calculation
  266. result = await db.execute(select(User).where(User.id == user.id).options(selectinload(User.groups)))
  267. user = result.scalar_one()
  268. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  269. access_token = create_access_token(data={"sub": user.username}, expires_delta=access_token_expires)
  270. return LoginResponse(
  271. access_token=access_token,
  272. token_type="bearer",
  273. user=_user_to_response(user),
  274. )
  275. @router.get("/me", response_model=UserResponse)
  276. async def get_current_user_info(
  277. credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)] = None,
  278. x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
  279. db: AsyncSession = Depends(get_db),
  280. ):
  281. """Get current user information.
  282. Accepts JWT tokens (via Authorization: Bearer header) and API keys
  283. (via X-API-Key header or Authorization: Bearer bb_xxx).
  284. API keys return a synthetic admin user with all permissions.
  285. """
  286. import jwt
  287. from jwt.exceptions import PyJWTError as JWTError
  288. # Check for API key via X-API-Key header
  289. if x_api_key:
  290. api_key = await _validate_api_key(db, x_api_key)
  291. if api_key:
  292. return _api_key_to_user_response(api_key)
  293. # Check for Bearer token (could be JWT or API key)
  294. if credentials is not None:
  295. token = credentials.credentials
  296. # Check if it's an API key (starts with bb_)
  297. if token.startswith("bb_"):
  298. api_key = await _validate_api_key(db, token)
  299. if api_key:
  300. return _api_key_to_user_response(api_key)
  301. raise HTTPException(
  302. status_code=status.HTTP_401_UNAUTHORIZED,
  303. detail="Invalid API key",
  304. headers={"WWW-Authenticate": "Bearer"},
  305. )
  306. # Otherwise treat as JWT
  307. try:
  308. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  309. username: str = payload.get("sub")
  310. if username is None:
  311. raise HTTPException(
  312. status_code=status.HTTP_401_UNAUTHORIZED,
  313. detail="Could not validate credentials",
  314. headers={"WWW-Authenticate": "Bearer"},
  315. )
  316. except JWTError:
  317. raise HTTPException(
  318. status_code=status.HTTP_401_UNAUTHORIZED,
  319. detail="Could not validate credentials",
  320. headers={"WWW-Authenticate": "Bearer"},
  321. )
  322. user = await get_user_by_username(db, username)
  323. if user is None or not user.is_active:
  324. raise HTTPException(
  325. status_code=status.HTTP_401_UNAUTHORIZED,
  326. detail="Could not validate credentials",
  327. headers={"WWW-Authenticate": "Bearer"},
  328. )
  329. # Reload with groups for proper permission calculation
  330. result = await db.execute(select(User).where(User.id == user.id).options(selectinload(User.groups)))
  331. user = result.scalar_one()
  332. return _user_to_response(user)
  333. # No credentials provided
  334. raise HTTPException(
  335. status_code=status.HTTP_401_UNAUTHORIZED,
  336. detail="Authentication required",
  337. headers={"WWW-Authenticate": "Bearer"},
  338. )
  339. @router.post("/logout")
  340. async def logout():
  341. """Logout (client should discard token)."""
  342. return {"message": "Logged out successfully"}
  343. # Advanced Authentication Endpoints
  344. @router.post("/smtp/test", response_model=TestSMTPResponse)
  345. async def test_smtp_connection(
  346. test_request: TestSMTPRequest,
  347. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  348. db: AsyncSession = Depends(get_db),
  349. ):
  350. """Test SMTP connection using saved settings (admin only when auth enabled)."""
  351. import logging
  352. logger = logging.getLogger(__name__)
  353. try:
  354. smtp_settings = await get_smtp_settings(db)
  355. if not smtp_settings:
  356. return TestSMTPResponse(success=False, message="SMTP settings not configured. Save SMTP settings first.")
  357. # Send test email
  358. send_email(
  359. smtp_settings=smtp_settings,
  360. to_email=test_request.test_recipient,
  361. subject="BamBuddy SMTP Test",
  362. body_text="This is a test email from BamBuddy. If you received this, your SMTP settings are working correctly!",
  363. body_html="<p>This is a test email from <strong>BamBuddy</strong>.</p><p>If you received this, your SMTP settings are working correctly!</p>",
  364. )
  365. logger.info(f"Test email sent successfully to {test_request.test_recipient}")
  366. return TestSMTPResponse(success=True, message="Test email sent successfully")
  367. except Exception as e:
  368. logger.error(f"Failed to send test email: {e}")
  369. return TestSMTPResponse(success=False, message=f"Failed to send test email: {str(e)}")
  370. @router.get("/smtp", response_model=SMTPSettings | None)
  371. async def get_smtp_config(
  372. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  373. db: AsyncSession = Depends(get_db),
  374. ):
  375. """Get SMTP settings (admin only when auth enabled). Password is not returned."""
  376. smtp_settings = await get_smtp_settings(db)
  377. if smtp_settings:
  378. # Don't return password in response
  379. smtp_settings.smtp_password = None
  380. return smtp_settings
  381. @router.post("/smtp", response_model=dict)
  382. async def save_smtp_config(
  383. smtp_settings: SMTPSettings,
  384. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  385. db: AsyncSession = Depends(get_db),
  386. ):
  387. """Save SMTP settings (admin only when auth enabled)."""
  388. import logging
  389. logger = logging.getLogger(__name__)
  390. try:
  391. await save_smtp_settings(db, smtp_settings)
  392. await db.commit()
  393. logger.info(f"SMTP settings updated by admin user: {current_user.username if current_user else 'anonymous'}")
  394. return {"message": "SMTP settings saved successfully"}
  395. except Exception as e:
  396. await db.rollback()
  397. logger.error(f"Failed to save SMTP settings: {e}")
  398. raise HTTPException(
  399. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  400. detail=f"Failed to save SMTP settings: {str(e)}",
  401. )
  402. @router.post("/advanced-auth/enable", response_model=dict)
  403. async def enable_advanced_auth(
  404. current_user: User = Depends(get_current_active_user),
  405. db: AsyncSession = Depends(get_db),
  406. ):
  407. """Enable advanced authentication (admin only).
  408. Requires SMTP settings to be configured and tested first.
  409. """
  410. import logging
  411. logger = logging.getLogger(__name__)
  412. # Reload user with groups for proper is_admin check
  413. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  414. user = result.scalar_one()
  415. if not user.is_admin:
  416. raise HTTPException(
  417. status_code=status.HTTP_403_FORBIDDEN,
  418. detail="Only admins can enable advanced authentication",
  419. )
  420. # Verify SMTP settings are configured
  421. smtp_settings = await get_smtp_settings(db)
  422. if not smtp_settings:
  423. raise HTTPException(
  424. status_code=status.HTTP_400_BAD_REQUEST,
  425. detail="SMTP settings must be configured before enabling advanced authentication",
  426. )
  427. try:
  428. await set_advanced_auth_enabled(db, True)
  429. await db.commit()
  430. logger.info(f"Advanced authentication enabled by admin user: {user.username}")
  431. return {"message": "Advanced authentication enabled successfully", "advanced_auth_enabled": True}
  432. except Exception as e:
  433. await db.rollback()
  434. logger.error(f"Failed to enable advanced authentication: {e}")
  435. raise HTTPException(
  436. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  437. detail=f"Failed to enable advanced authentication: {str(e)}",
  438. )
  439. @router.post("/advanced-auth/disable", response_model=dict)
  440. async def disable_advanced_auth(
  441. current_user: User = Depends(get_current_active_user),
  442. db: AsyncSession = Depends(get_db),
  443. ):
  444. """Disable advanced authentication (admin only)."""
  445. import logging
  446. logger = logging.getLogger(__name__)
  447. # Reload user with groups for proper is_admin check
  448. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  449. user = result.scalar_one()
  450. if not user.is_admin:
  451. raise HTTPException(
  452. status_code=status.HTTP_403_FORBIDDEN,
  453. detail="Only admins can disable advanced authentication",
  454. )
  455. try:
  456. await set_advanced_auth_enabled(db, False)
  457. await db.commit()
  458. logger.info(f"Advanced authentication disabled by admin user: {user.username}")
  459. return {"message": "Advanced authentication disabled successfully", "advanced_auth_enabled": False}
  460. except Exception as e:
  461. await db.rollback()
  462. logger.error(f"Failed to disable advanced authentication: {e}")
  463. raise HTTPException(
  464. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  465. detail=f"Failed to disable advanced authentication: {str(e)}",
  466. )
  467. @router.get("/advanced-auth/status")
  468. async def get_advanced_auth_status(db: AsyncSession = Depends(get_db)):
  469. """Get advanced authentication status."""
  470. advanced_auth_enabled = await is_advanced_auth_enabled(db)
  471. smtp_configured = await get_smtp_settings(db) is not None
  472. return {
  473. "advanced_auth_enabled": advanced_auth_enabled,
  474. "smtp_configured": smtp_configured,
  475. }
  476. @router.post("/forgot-password", response_model=ForgotPasswordResponse)
  477. async def forgot_password(request: ForgotPasswordRequest, db: AsyncSession = Depends(get_db)):
  478. """Request password reset via email (advanced auth only)."""
  479. import logging
  480. logger = logging.getLogger(__name__)
  481. # Check if advanced auth is enabled
  482. advanced_auth = await is_advanced_auth_enabled(db)
  483. if not advanced_auth:
  484. raise HTTPException(
  485. status_code=status.HTTP_400_BAD_REQUEST,
  486. detail="Advanced authentication is not enabled",
  487. )
  488. # Get SMTP settings
  489. smtp_settings = await get_smtp_settings(db)
  490. if not smtp_settings:
  491. raise HTTPException(
  492. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  493. detail="Email service is not configured",
  494. )
  495. # Find user by email
  496. user = await get_user_by_email(db, request.email)
  497. # Always return success message to prevent email enumeration
  498. # but only send email if user exists
  499. if user and user.is_active:
  500. try:
  501. # Generate new password
  502. new_password = generate_secure_password()
  503. user.password_hash = get_password_hash(new_password)
  504. await db.commit()
  505. login_url = await get_external_login_url(db)
  506. # Send password reset email
  507. subject, text_body, html_body = await create_password_reset_email_from_template(
  508. db, user.username, new_password, login_url
  509. )
  510. send_email(smtp_settings, user.email, subject, text_body, html_body)
  511. logger.info(f"Password reset email sent to {user.email}")
  512. except Exception as e:
  513. logger.error(f"Failed to send password reset email: {e}")
  514. # Don't reveal error to user for security
  515. return ForgotPasswordResponse(
  516. message="If the email address is associated with an account, a password reset email has been sent."
  517. )
  518. @router.post("/reset-password", response_model=ResetPasswordResponse)
  519. async def reset_user_password(
  520. request: ResetPasswordRequest,
  521. current_user: User = Depends(get_current_active_user),
  522. db: AsyncSession = Depends(get_db),
  523. ):
  524. """Reset a user's password and send them an email (admin only, advanced auth only)."""
  525. import logging
  526. logger = logging.getLogger(__name__)
  527. # Reload user with groups for proper is_admin check
  528. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  529. admin_user = result.scalar_one()
  530. if not admin_user.is_admin:
  531. raise HTTPException(
  532. status_code=status.HTTP_403_FORBIDDEN,
  533. detail="Only admins can reset user passwords",
  534. )
  535. # Check if advanced auth is enabled
  536. advanced_auth = await is_advanced_auth_enabled(db)
  537. if not advanced_auth:
  538. raise HTTPException(
  539. status_code=status.HTTP_400_BAD_REQUEST,
  540. detail="Advanced authentication is not enabled",
  541. )
  542. # Get SMTP settings
  543. smtp_settings = await get_smtp_settings(db)
  544. if not smtp_settings:
  545. raise HTTPException(
  546. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  547. detail="Email service is not configured",
  548. )
  549. # Find user to reset
  550. result = await db.execute(select(User).where(User.id == request.user_id))
  551. user = result.scalar_one_or_none()
  552. if not user:
  553. raise HTTPException(
  554. status_code=status.HTTP_404_NOT_FOUND,
  555. detail="User not found",
  556. )
  557. if not user.email:
  558. raise HTTPException(
  559. status_code=status.HTTP_400_BAD_REQUEST,
  560. detail="User does not have an email address configured",
  561. )
  562. try:
  563. # Generate new password
  564. new_password = generate_secure_password()
  565. user.password_hash = get_password_hash(new_password)
  566. await db.commit()
  567. login_url = await get_external_login_url(db)
  568. # Send password reset email
  569. subject, text_body, html_body = await create_password_reset_email_from_template(
  570. db, user.username, new_password, login_url
  571. )
  572. send_email(smtp_settings, user.email, subject, text_body, html_body)
  573. logger.info(f"Password reset by admin {admin_user.username} for user {user.username}")
  574. return ResetPasswordResponse(message=f"Password reset email sent to {user.email}")
  575. except Exception as e:
  576. await db.rollback()
  577. logger.error(f"Failed to reset password for user {user.username}: {e}")
  578. raise HTTPException(
  579. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  580. detail=f"Failed to reset password: {str(e)}",
  581. )