Files
celtic-life-science/scripts/create_superadmin.py
T
Shubhankar45 4e5e95775d --
2026-10-27 12:03:31 +00:00

60 lines
2.3 KiB
Python

"""Create (or rotate the password of) the protected super admin.
python -m scripts.create_superadmin --email owner@example.com --password 'S3cret-...'
The super admin has the ADMIN role, so it can do everything an administrator can, but no
one can edit, deactivate, re-role or delete it afterwards (API and DB trigger both refuse).
Re-running with the same email only resets its password and clears any lockout.
"""
import argparse
import asyncio
import sys
from sqlalchemy import select
from app.auth.security import hash_password
from app.common.enums import Role
from app.database.session import AsyncSessionLocal
from app.organization.models import Company
from app.users.models import User
async def run(email: str, password: str, name: str, code: str) -> None:
async with AsyncSessionLocal() as db:
existing = (
await db.execute(select(User).where(User.is_superadmin.is_(True)))
).scalar_one_or_none()
if existing is not None:
if existing.email != email.lower():
sys.exit(f"A super admin already exists ({existing.email}); only one is allowed.")
existing.password_hash = hash_password(password)
existing.failed_login_attempts = 0
await db.commit()
print(f"Super admin {existing.email}: password reset.")
return
company = (await db.execute(select(Company).order_by(Company.created_at))).scalars().first()
if company is None:
sys.exit("No company exists yet — seed or create one first.")
db.add(
User(
company_id=company.id, email=email.lower(), password_hash=hash_password(password),
full_name=name, employee_code=code, role=Role.ADMIN, is_superadmin=True,
)
)
await db.commit()
print(f"Super admin created: {email.lower()}")
if __name__ == "__main__":
p = argparse.ArgumentParser()
p.add_argument("--email", required=True)
p.add_argument("--password", required=True)
p.add_argument("--name", default="Super Admin")
p.add_argument("--code", default="SUPERADMIN")
a = p.parse_args()
if len(a.password) < 12:
sys.exit("Use a password of at least 12 characters.")
asyncio.run(run(a.email, a.password, a.name, a.code))