auth.py 26 KB

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