auth.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  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 with provided settings (admin only when auth enabled)."""
  351. import logging
  352. logger = logging.getLogger(__name__)
  353. try:
  354. smtp_settings = SMTPSettings(
  355. smtp_host=test_request.smtp_host,
  356. smtp_port=test_request.smtp_port,
  357. smtp_username=test_request.smtp_username,
  358. smtp_password=test_request.smtp_password,
  359. smtp_security=test_request.smtp_security,
  360. smtp_auth_enabled=test_request.smtp_auth_enabled,
  361. smtp_from_email=test_request.smtp_from_email,
  362. )
  363. # Send test email
  364. send_email(
  365. smtp_settings=smtp_settings,
  366. to_email=test_request.test_recipient,
  367. subject="BamBuddy SMTP Test",
  368. body_text="This is a test email from BamBuddy. If you received this, your SMTP settings are working correctly!",
  369. 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>",
  370. )
  371. logger.info(f"Test email sent successfully to {test_request.test_recipient}")
  372. return TestSMTPResponse(success=True, message="Test email sent successfully")
  373. except Exception as e:
  374. logger.error(f"Failed to send test email: {e}")
  375. return TestSMTPResponse(success=False, message=f"Failed to send test email: {str(e)}")
  376. @router.get("/smtp", response_model=SMTPSettings | None)
  377. async def get_smtp_config(
  378. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_READ),
  379. db: AsyncSession = Depends(get_db),
  380. ):
  381. """Get SMTP settings (admin only when auth enabled). Password is not returned."""
  382. smtp_settings = await get_smtp_settings(db)
  383. if smtp_settings:
  384. # Don't return password in response
  385. smtp_settings.smtp_password = None
  386. return smtp_settings
  387. @router.post("/smtp", response_model=dict)
  388. async def save_smtp_config(
  389. smtp_settings: SMTPSettings,
  390. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  391. db: AsyncSession = Depends(get_db),
  392. ):
  393. """Save SMTP settings (admin only when auth enabled)."""
  394. import logging
  395. logger = logging.getLogger(__name__)
  396. try:
  397. await save_smtp_settings(db, smtp_settings)
  398. await db.commit()
  399. logger.info(f"SMTP settings updated by admin user: {current_user.username if current_user else 'anonymous'}")
  400. return {"message": "SMTP settings saved successfully"}
  401. except Exception as e:
  402. await db.rollback()
  403. logger.error(f"Failed to save SMTP settings: {e}")
  404. raise HTTPException(
  405. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  406. detail=f"Failed to save SMTP settings: {str(e)}",
  407. )
  408. @router.post("/advanced-auth/enable", response_model=dict)
  409. async def enable_advanced_auth(
  410. current_user: User = Depends(get_current_active_user),
  411. db: AsyncSession = Depends(get_db),
  412. ):
  413. """Enable advanced authentication (admin only).
  414. Requires SMTP settings to be configured and tested first.
  415. """
  416. import logging
  417. logger = logging.getLogger(__name__)
  418. # Reload user with groups for proper is_admin check
  419. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  420. user = result.scalar_one()
  421. if not user.is_admin:
  422. raise HTTPException(
  423. status_code=status.HTTP_403_FORBIDDEN,
  424. detail="Only admins can enable advanced authentication",
  425. )
  426. # Verify SMTP settings are configured
  427. smtp_settings = await get_smtp_settings(db)
  428. if not smtp_settings:
  429. raise HTTPException(
  430. status_code=status.HTTP_400_BAD_REQUEST,
  431. detail="SMTP settings must be configured before enabling advanced authentication",
  432. )
  433. try:
  434. await set_advanced_auth_enabled(db, True)
  435. await db.commit()
  436. logger.info(f"Advanced authentication enabled by admin user: {user.username}")
  437. return {"message": "Advanced authentication enabled successfully", "advanced_auth_enabled": True}
  438. except Exception as e:
  439. await db.rollback()
  440. logger.error(f"Failed to enable advanced authentication: {e}")
  441. raise HTTPException(
  442. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  443. detail=f"Failed to enable advanced authentication: {str(e)}",
  444. )
  445. @router.post("/advanced-auth/disable", response_model=dict)
  446. async def disable_advanced_auth(
  447. current_user: User = Depends(get_current_active_user),
  448. db: AsyncSession = Depends(get_db),
  449. ):
  450. """Disable advanced authentication (admin only)."""
  451. import logging
  452. logger = logging.getLogger(__name__)
  453. # Reload user with groups for proper is_admin check
  454. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  455. user = result.scalar_one()
  456. if not user.is_admin:
  457. raise HTTPException(
  458. status_code=status.HTTP_403_FORBIDDEN,
  459. detail="Only admins can disable advanced authentication",
  460. )
  461. try:
  462. await set_advanced_auth_enabled(db, False)
  463. await db.commit()
  464. logger.info(f"Advanced authentication disabled by admin user: {user.username}")
  465. return {"message": "Advanced authentication disabled successfully", "advanced_auth_enabled": False}
  466. except Exception as e:
  467. await db.rollback()
  468. logger.error(f"Failed to disable advanced authentication: {e}")
  469. raise HTTPException(
  470. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  471. detail=f"Failed to disable advanced authentication: {str(e)}",
  472. )
  473. @router.get("/advanced-auth/status")
  474. async def get_advanced_auth_status(db: AsyncSession = Depends(get_db)):
  475. """Get advanced authentication status."""
  476. advanced_auth_enabled = await is_advanced_auth_enabled(db)
  477. smtp_configured = await get_smtp_settings(db) is not None
  478. return {
  479. "advanced_auth_enabled": advanced_auth_enabled,
  480. "smtp_configured": smtp_configured,
  481. }
  482. @router.post("/forgot-password", response_model=ForgotPasswordResponse)
  483. async def forgot_password(request: ForgotPasswordRequest, db: AsyncSession = Depends(get_db)):
  484. """Request password reset via email (advanced auth only)."""
  485. import logging
  486. logger = logging.getLogger(__name__)
  487. # Check if advanced auth is enabled
  488. advanced_auth = await is_advanced_auth_enabled(db)
  489. if not advanced_auth:
  490. raise HTTPException(
  491. status_code=status.HTTP_400_BAD_REQUEST,
  492. detail="Advanced authentication is not enabled",
  493. )
  494. # Get SMTP settings
  495. smtp_settings = await get_smtp_settings(db)
  496. if not smtp_settings:
  497. raise HTTPException(
  498. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  499. detail="Email service is not configured",
  500. )
  501. # Find user by email
  502. user = await get_user_by_email(db, request.email)
  503. # Always return success message to prevent email enumeration
  504. # but only send email if user exists
  505. if user and user.is_active:
  506. try:
  507. # Generate new password
  508. new_password = generate_secure_password()
  509. user.password_hash = get_password_hash(new_password)
  510. await db.commit()
  511. login_url = await get_external_login_url(db)
  512. # Send password reset email
  513. subject, text_body, html_body = await create_password_reset_email_from_template(
  514. db, user.username, new_password, login_url
  515. )
  516. send_email(smtp_settings, user.email, subject, text_body, html_body)
  517. logger.info(f"Password reset email sent to {user.email}")
  518. except Exception as e:
  519. logger.error(f"Failed to send password reset email: {e}")
  520. # Don't reveal error to user for security
  521. return ForgotPasswordResponse(
  522. message="If the email address is associated with an account, a password reset email has been sent."
  523. )
  524. @router.post("/reset-password", response_model=ResetPasswordResponse)
  525. async def reset_user_password(
  526. request: ResetPasswordRequest,
  527. current_user: User = Depends(get_current_active_user),
  528. db: AsyncSession = Depends(get_db),
  529. ):
  530. """Reset a user's password and send them an email (admin only, advanced auth only)."""
  531. import logging
  532. logger = logging.getLogger(__name__)
  533. # Reload user with groups for proper is_admin check
  534. result = await db.execute(select(User).where(User.id == current_user.id).options(selectinload(User.groups)))
  535. admin_user = result.scalar_one()
  536. if not admin_user.is_admin:
  537. raise HTTPException(
  538. status_code=status.HTTP_403_FORBIDDEN,
  539. detail="Only admins can reset user passwords",
  540. )
  541. # Check if advanced auth is enabled
  542. advanced_auth = await is_advanced_auth_enabled(db)
  543. if not advanced_auth:
  544. raise HTTPException(
  545. status_code=status.HTTP_400_BAD_REQUEST,
  546. detail="Advanced authentication is not enabled",
  547. )
  548. # Get SMTP settings
  549. smtp_settings = await get_smtp_settings(db)
  550. if not smtp_settings:
  551. raise HTTPException(
  552. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  553. detail="Email service is not configured",
  554. )
  555. # Find user to reset
  556. result = await db.execute(select(User).where(User.id == request.user_id))
  557. user = result.scalar_one_or_none()
  558. if not user:
  559. raise HTTPException(
  560. status_code=status.HTTP_404_NOT_FOUND,
  561. detail="User not found",
  562. )
  563. if not user.email:
  564. raise HTTPException(
  565. status_code=status.HTTP_400_BAD_REQUEST,
  566. detail="User does not have an email address configured",
  567. )
  568. try:
  569. # Generate new password
  570. new_password = generate_secure_password()
  571. user.password_hash = get_password_hash(new_password)
  572. await db.commit()
  573. login_url = await get_external_login_url(db)
  574. # Send password reset email
  575. subject, text_body, html_body = await create_password_reset_email_from_template(
  576. db, user.username, new_password, login_url
  577. )
  578. send_email(smtp_settings, user.email, subject, text_body, html_body)
  579. logger.info(f"Password reset by admin {admin_user.username} for user {user.username}")
  580. return ResetPasswordResponse(message=f"Password reset email sent to {user.email}")
  581. except Exception as e:
  582. await db.rollback()
  583. logger.error(f"Failed to reset password for user {user.username}: {e}")
  584. raise HTTPException(
  585. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  586. detail=f"Failed to reset password: {str(e)}",
  587. )