auth.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. from datetime import timedelta
  2. from fastapi import APIRouter, Depends, HTTPException, status
  3. from sqlalchemy import select
  4. from sqlalchemy.ext.asyncio import AsyncSession
  5. from backend.app.core.auth import (
  6. ACCESS_TOKEN_EXPIRE_MINUTES,
  7. authenticate_user,
  8. create_access_token,
  9. get_current_active_user,
  10. get_password_hash,
  11. get_user_by_username,
  12. )
  13. from backend.app.core.database import get_db
  14. from backend.app.models.settings import Settings
  15. from backend.app.models.user import User
  16. from backend.app.schemas.auth import LoginRequest, LoginResponse, SetupRequest, SetupResponse, UserResponse
  17. router = APIRouter(prefix="/auth", tags=["authentication"])
  18. async def is_auth_enabled(db: AsyncSession) -> bool:
  19. """Check if authentication is enabled."""
  20. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  21. setting = result.scalar_one_or_none()
  22. return setting and setting.value.lower() == "true"
  23. async def set_auth_enabled(db: AsyncSession, enabled: bool) -> None:
  24. """Set authentication enabled status."""
  25. from sqlalchemy import func
  26. from sqlalchemy.dialects.sqlite import insert as sqlite_insert
  27. stmt = sqlite_insert(Settings).values(key="auth_enabled", value="true" if enabled else "false")
  28. stmt = stmt.on_conflict_do_update(
  29. index_elements=["key"], set_={"value": "true" if enabled else "false", "updated_at": func.now()}
  30. )
  31. await db.execute(stmt)
  32. # Note: Don't commit here - let get_db handle it or commit explicitly in the route
  33. @router.post("/setup", response_model=SetupResponse)
  34. async def setup_auth(request: SetupRequest, db: AsyncSession = Depends(get_db)):
  35. """First-time setup: enable/disable authentication and create admin user."""
  36. import logging
  37. logger = logging.getLogger(__name__)
  38. try:
  39. # Check if auth is already configured (prevent re-setup)
  40. result = await db.execute(select(Settings).where(Settings.key == "auth_enabled"))
  41. existing_setting = result.scalar_one_or_none()
  42. # Check if users exist
  43. user_count_result = await db.execute(select(User))
  44. user_count = len(user_count_result.scalars().all())
  45. if existing_setting and user_count > 0:
  46. # Auth already configured and users exist - prevent re-setup
  47. raise HTTPException(
  48. status_code=status.HTTP_400_BAD_REQUEST,
  49. detail="Authentication is already configured. Use user management to modify users.",
  50. )
  51. # If auth_enabled is true but no users exist, allow re-setup (recovery scenario)
  52. admin_created = False
  53. if request.auth_enabled:
  54. if not request.admin_username or not request.admin_password:
  55. raise HTTPException(
  56. status_code=status.HTTP_400_BAD_REQUEST,
  57. detail="Admin username and password are required when enabling authentication",
  58. )
  59. # Check if admin already exists
  60. existing_admin = await get_user_by_username(db, request.admin_username)
  61. if existing_admin:
  62. raise HTTPException(
  63. status_code=status.HTTP_400_BAD_REQUEST,
  64. detail="Admin user already exists",
  65. )
  66. # Create admin user FIRST (before enabling auth)
  67. try:
  68. logger.info(f"Creating admin user: {request.admin_username}")
  69. admin_user = User(
  70. username=request.admin_username,
  71. password_hash=get_password_hash(request.admin_password),
  72. role="admin",
  73. is_active=True,
  74. )
  75. db.add(admin_user)
  76. logger.info(f"Admin user added to session: {request.admin_username}")
  77. admin_created = True
  78. except Exception as e:
  79. await db.rollback()
  80. logger.error(f"Failed to create admin user: {e}", exc_info=True)
  81. raise HTTPException(
  82. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  83. detail=f"Failed to create admin user: {str(e)}",
  84. )
  85. # Set auth enabled and commit everything together
  86. await set_auth_enabled(db, request.auth_enabled)
  87. await db.commit()
  88. if admin_created:
  89. await db.refresh(admin_user)
  90. logger.info(f"Admin user created successfully: {admin_user.id}")
  91. return SetupResponse(auth_enabled=request.auth_enabled, admin_created=admin_created)
  92. except HTTPException:
  93. raise
  94. except Exception as e:
  95. logger.error(f"Setup error: {e}", exc_info=True)
  96. await db.rollback()
  97. raise HTTPException(
  98. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  99. detail=f"Setup failed: {str(e)}",
  100. )
  101. @router.get("/status")
  102. async def get_auth_status(db: AsyncSession = Depends(get_db)):
  103. """Get authentication status (public endpoint)."""
  104. auth_enabled = await is_auth_enabled(db)
  105. return {"auth_enabled": auth_enabled, "requires_setup": not auth_enabled}
  106. @router.post("/disable", response_model=dict)
  107. async def disable_auth(
  108. current_user: User = Depends(get_current_active_user),
  109. db: AsyncSession = Depends(get_db),
  110. ):
  111. """Disable authentication (admin only)."""
  112. import logging
  113. logger = logging.getLogger(__name__)
  114. # Only admins can disable authentication
  115. if current_user.role != "admin":
  116. raise HTTPException(
  117. status_code=status.HTTP_403_FORBIDDEN,
  118. detail="Only admins can disable authentication",
  119. )
  120. try:
  121. await set_auth_enabled(db, False)
  122. await db.commit()
  123. logger.info(f"Authentication disabled by admin user: {current_user.username}")
  124. return {"message": "Authentication disabled successfully", "auth_enabled": False}
  125. except Exception as e:
  126. await db.rollback()
  127. logger.error(f"Failed to disable authentication: {e}", exc_info=True)
  128. raise HTTPException(
  129. status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
  130. detail=f"Failed to disable authentication: {str(e)}",
  131. )
  132. @router.post("/login", response_model=LoginResponse)
  133. async def login(request: LoginRequest, db: AsyncSession = Depends(get_db)):
  134. """Login and get access token."""
  135. # Check if auth is enabled
  136. auth_enabled = await is_auth_enabled(db)
  137. if not auth_enabled:
  138. raise HTTPException(
  139. status_code=status.HTTP_400_BAD_REQUEST,
  140. detail="Authentication is not enabled",
  141. )
  142. user = await authenticate_user(db, request.username, request.password)
  143. if not user:
  144. raise HTTPException(
  145. status_code=status.HTTP_401_UNAUTHORIZED,
  146. detail="Incorrect username or password",
  147. headers={"WWW-Authenticate": "Bearer"},
  148. )
  149. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  150. access_token = create_access_token(data={"sub": user.username}, expires_delta=access_token_expires)
  151. return LoginResponse(
  152. access_token=access_token,
  153. token_type="bearer",
  154. user=UserResponse(
  155. id=user.id,
  156. username=user.username,
  157. role=user.role,
  158. is_active=user.is_active,
  159. created_at=user.created_at.isoformat(),
  160. ),
  161. )
  162. @router.get("/me", response_model=UserResponse)
  163. async def get_current_user_info(current_user: User = Depends(get_current_active_user)):
  164. """Get current user information."""
  165. return UserResponse(
  166. id=current_user.id,
  167. username=current_user.username,
  168. role=current_user.role,
  169. is_active=current_user.is_active,
  170. created_at=current_user.created_at.isoformat(),
  171. )
  172. @router.post("/logout")
  173. async def logout():
  174. """Logout (client should discard token)."""
  175. return {"message": "Logged out successfully"}