"""Create (or promote) an administrator account. Usage (inside the backend container or with the backend venv):: ADMIN_USERNAME=admin ADMIN_PASSWORD='secret' python seed_admin.py Reads ``ADMIN_USERNAME`` and ``ADMIN_PASSWORD`` from the environment (see ``.env.example``). When the user already exists the account is promoted to admin and its password is reset to ``ADMIN_PASSWORD``. Safe to re-run. """ from __future__ import annotations import os import sys from core import auth from db.session import SessionLocal from models import User def main() -> int: username = os.getenv("ADMIN_USERNAME", "").strip() password = os.getenv("ADMIN_PASSWORD", "") if not username or not password: print( "error: set ADMIN_USERNAME and ADMIN_PASSWORD " "(see .env.example), e.g.\n" " ADMIN_USERNAME=admin ADMIN_PASSWORD='secret' python seed_admin.py", file=sys.stderr, ) return 1 db = SessionLocal() try: user = db.query(User).filter(User.username == username).first() if user is None: user = User( username=username, password_hash=auth.hash_password(password), is_admin=True, ) db.add(user) db.commit() print(f"Created admin user '{username}'.") else: user.is_admin = True user.password_hash = auth.hash_password(password) db.commit() print(f"Promoted existing user '{username}' to admin (password reset).") return 0 finally: db.close() if __name__ == "__main__": raise SystemExit(main())