from __future__ import annotations import os import secrets from sqlalchemy import select from app.core.config import settings from app.db.engine import get_session from app.db.models import User from app.security.audit import log_event from app.security.auth import hash_password def bootstrap_admin() -> None: if not settings.bootstrap_admin_generate: return db = get_session() try: existing = db.scalar(select(User).where(User.is_superuser.is_(True))) if existing: return password = secrets.token_urlsafe(16) user = User( username=settings.bootstrap_admin_username, password_hash=hash_password(password), is_active=True, is_superuser=True, is_ldap=False, ) db.add(user) db.commit() db.refresh(user) pass_path = settings.bootstrap_admin_pass_path os.makedirs(os.path.dirname(pass_path), exist_ok=True) with open(pass_path, "w", encoding="utf-8") as f: f.write(password + "\n") log_event(db, action="bootstrap.admin.created", target=user.username, detail={}, request=None, actor=user) finally: db.close()