auth.py 9.9 KB

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