84 lines
3.0 KiB
Python
84 lines
3.0 KiB
Python
"""Management commands.
|
|
|
|
python -m app.cli create-admin --email you@example.com --name "Your Name" [--role super_admin]
|
|
|
|
The password is read from the ADMIN_PASSWORD environment variable if set,
|
|
otherwise prompted for interactively (never passed on the command line).
|
|
"""
|
|
|
|
import argparse
|
|
import asyncio
|
|
import getpass
|
|
import os
|
|
import sys
|
|
|
|
from pydantic import TypeAdapter, ValidationError
|
|
from sqlalchemy import func, select
|
|
|
|
from app.core.database import SessionLocal, engine
|
|
from app.core.security import hash_password
|
|
from app.models import Admin, AdminRole
|
|
from app.schemas.auth import AdminCreate
|
|
|
|
|
|
def _read_password() -> str:
|
|
if pw := os.environ.get("ADMIN_PASSWORD"):
|
|
return pw
|
|
if not sys.stdin.isatty():
|
|
sys.exit("Set ADMIN_PASSWORD or run interactively to enter a password.")
|
|
pw = getpass.getpass("Password (min 10 chars, letters + numbers): ")
|
|
if pw != getpass.getpass("Repeat password: "):
|
|
sys.exit("Passwords do not match.")
|
|
return pw
|
|
|
|
|
|
async def create_admin(email: str, name: str, role: str, update_existing: bool) -> None:
|
|
try:
|
|
data = TypeAdapter(AdminCreate).validate_python(
|
|
{"email": email, "full_name": name, "password": _read_password(), "role": role}
|
|
)
|
|
except ValidationError as exc:
|
|
sys.exit("Invalid input:\n" + "\n".join(f" - {e['loc'][-1]}: {e['msg']}" for e in exc.errors()))
|
|
|
|
async with SessionLocal() as db:
|
|
existing = await db.scalar(select(Admin).where(func.lower(Admin.email) == data.email.lower()))
|
|
if existing and not update_existing:
|
|
sys.exit(f"Admin {data.email} already exists (use --update to reset password/role).")
|
|
if existing:
|
|
existing.hashed_password = hash_password(data.password)
|
|
existing.role = data.role
|
|
existing.full_name = data.full_name
|
|
existing.is_active = True
|
|
action = "Updated"
|
|
else:
|
|
db.add(
|
|
Admin(
|
|
email=data.email.lower(),
|
|
full_name=data.full_name,
|
|
hashed_password=hash_password(data.password),
|
|
role=data.role,
|
|
)
|
|
)
|
|
action = "Created"
|
|
await db.commit()
|
|
await engine.dispose()
|
|
print(f"{action} {data.role.value} account: {data.email.lower()}")
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(prog="python -m app.cli")
|
|
sub = parser.add_subparsers(dest="command", required=True)
|
|
ca = sub.add_parser("create-admin", help="Create (or update) an admin account")
|
|
ca.add_argument("--email", required=True)
|
|
ca.add_argument("--name", required=True)
|
|
ca.add_argument("--role", default=AdminRole.SUPER_ADMIN.value, choices=[r.value for r in AdminRole])
|
|
ca.add_argument("--update", action="store_true", help="Update the account if it already exists")
|
|
args = parser.parse_args()
|
|
|
|
if args.command == "create-admin":
|
|
asyncio.run(create_admin(args.email, args.name, args.role, args.update))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|