61 lines
1.9 KiB
Python
61 lines
1.9 KiB
Python
"""建管理员账号(幂等):已存在则重置口令并提权。
|
|
|
|
用法(在 server/ 下):
|
|
../.venv/bin/python scripts/create_admin.py --account admin@nexbuddy.com --password 'NexBuddy2026'
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
|
|
from sqlalchemy import select # noqa: E402
|
|
|
|
from app.core.security import hash_password # noqa: E402
|
|
from app.db.session import SessionLocal, dispose_engine # noqa: E402
|
|
from app.models import User # noqa: E402
|
|
|
|
|
|
async def main() -> None:
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--account", required=True, help="邮箱或手机号")
|
|
ap.add_argument("--password", required=True)
|
|
ap.add_argument("--nickname", default="管理员")
|
|
args = ap.parse_args()
|
|
|
|
account = args.account.strip()
|
|
is_email = "@" in account
|
|
field = User.email if is_email else User.phone
|
|
value = account.lower() if is_email else account
|
|
|
|
async with SessionLocal() as db:
|
|
user = await db.scalar(select(User).where(field == value))
|
|
if user is None:
|
|
user = User(
|
|
email=value if is_email else None,
|
|
phone=None if is_email else value,
|
|
password_hash=hash_password(args.password),
|
|
nickname=args.nickname,
|
|
role="admin",
|
|
status="active",
|
|
)
|
|
db.add(user)
|
|
action = "created"
|
|
else:
|
|
user.password_hash = hash_password(args.password)
|
|
user.role = "admin"
|
|
user.status = "active"
|
|
action = "updated"
|
|
await db.commit()
|
|
print(f"{action}: {value} (role=admin)")
|
|
|
|
await dispose_engine()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|