fix: seed admin user on startup and run sync as background task
- Seed/update admin user from ADMIN_USERNAME/ADMIN_PASSWORD settings on startup (admin_users table was empty, login was impossible) - POST /api/admin/sync now returns immediately and runs the equipment sync via BackgroundTasks (full sync took minutes and hit nginx 504) - run_sync accepts optional sync_log_id to reuse a pre-created log entry - Adapt admin router test to background sync behavior
This commit is contained in:
+23
-1
@@ -9,6 +9,9 @@ from app.config import get_settings
|
||||
from app.database import engine, init_db, async_session
|
||||
from app.cache import cache
|
||||
from app.routers import equipment, health, admin, rental_requests, contact
|
||||
from app.models.admin_user import AdminUser
|
||||
from app.auth import get_password_hash
|
||||
from sqlalchemy import select
|
||||
from app.services.sync_service import SyncService
|
||||
from app.services.email_service import EmailService
|
||||
from app.mcp_server import get_mcp_app, mcp_session_manager
|
||||
@@ -36,10 +39,29 @@ async def run_email_retry() -> None:
|
||||
logger.info("Email retry complete: %d emails sent", sent)
|
||||
|
||||
|
||||
async def seed_admin_user() -> None:
|
||||
"""Ensure the admin user from settings exists (create or update password)."""
|
||||
async with async_session() as db:
|
||||
result = await db.execute(
|
||||
select(AdminUser).where(AdminUser.username == settings.admin_username)
|
||||
)
|
||||
user = result.scalar_one_or_none()
|
||||
if not user:
|
||||
db.add(AdminUser(
|
||||
username=settings.admin_username,
|
||||
password_hash=get_password_hash(settings.admin_password),
|
||||
))
|
||||
logger.info("Seeded admin user %s", settings.admin_username)
|
||||
else:
|
||||
user.password_hash = get_password_hash(settings.admin_password)
|
||||
await db.commit()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Application lifespan: init DB, start scheduler, connect cache."""
|
||||
"""Application lifespan: init DB, seed admin, start scheduler, connect cache."""
|
||||
await init_db()
|
||||
await seed_admin_user()
|
||||
await cache.connect()
|
||||
|
||||
_mcp_cm = mcp_session_manager.run()
|
||||
|
||||
Reference in New Issue
Block a user