auth.py 7.8 KB

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