Bootstrap initial admin via env and add compose profiles

This commit is contained in:
2026-03-17 19:16:25 +03:00
parent 3b22133d7a
commit 78f1e6803f
4 changed files with 88 additions and 9 deletions

View File

@@ -12,6 +12,7 @@
# @SIDE_EFFECT: Starts background scheduler and binds network ports for HTTP/WS traffic.
# @DATA_CONTRACT: [HTTP Request | WS Message] -> [HTTP Response | JSON Log Stream]
import os
from pathlib import Path
# project_root is used for static files mounting
@@ -28,6 +29,9 @@ from .dependencies import get_task_manager, get_scheduler_service
from .core.encryption_key import ensure_encryption_key
from .core.utils.network import NetworkError
from .core.logger import logger, belief_scope
from .core.database import AuthSessionLocal
from .core.auth.security import get_password_hash
from .models.auth import User, Role
from .api.routes import plugins, tasks, settings, environments, mappings, migration, connections, git, storage, admin, llm, dashboards, datasets, reports, assistant, clean_release, clean_release_v2, profile, health, dataset_review
from .api import auth
@@ -42,6 +46,54 @@ app = FastAPI(
)
# [/DEF:App:Global]
# [DEF:ensure_initial_admin_user:Function]
# @COMPLEXITY: 3
# @PURPOSE: Ensures initial admin user exists when bootstrap env flags are enabled.
def ensure_initial_admin_user() -> None:
raw_flag = os.getenv("INITIAL_ADMIN_CREATE", "false").strip().lower()
if raw_flag not in {"1", "true", "yes", "on"}:
return
username = os.getenv("INITIAL_ADMIN_USERNAME", "").strip()
password = os.getenv("INITIAL_ADMIN_PASSWORD", "").strip()
if not username or not password:
logger.warning(
"INITIAL_ADMIN_CREATE is enabled but INITIAL_ADMIN_USERNAME/INITIAL_ADMIN_PASSWORD is missing; skipping bootstrap."
)
return
db = AuthSessionLocal()
try:
admin_role = db.query(Role).filter(Role.name == "Admin").first()
if not admin_role:
admin_role = Role(name="Admin", description="System Administrator")
db.add(admin_role)
db.commit()
db.refresh(admin_role)
existing_user = db.query(User).filter(User.username == username).first()
if existing_user:
logger.info("Initial admin bootstrap skipped: user '%s' already exists.", username)
return
new_user = User(
username=username,
email=None,
password_hash=get_password_hash(password),
auth_source="LOCAL",
is_active=True,
)
new_user.roles.append(admin_role)
db.add(new_user)
db.commit()
logger.info("Initial admin user '%s' created from environment bootstrap.", username)
except Exception as exc:
db.rollback()
logger.error("Failed to bootstrap initial admin user: %s", exc)
raise
finally:
db.close()
# [/DEF:ensure_initial_admin_user:Function]
# [DEF:startup_event:Function]
# @COMPLEXITY: 3
# @PURPOSE: Handles application startup tasks, such as starting the scheduler.
@@ -53,6 +105,7 @@ app = FastAPI(
async def startup_event():
with belief_scope("startup_event"):
ensure_encryption_key()
ensure_initial_admin_user()
scheduler = get_scheduler_service()
scheduler.start()
# [/DEF:startup_event:Function]