mirror of
https://gitverse.ru/kpa39l/md2vk.git
synced 2026-09-29 01:50:04 +00:00
70 lines
2.3 KiB
Python
70 lines
2.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Создание пользователя и API-ключа md2vk.
|
|
|
|
Пример:
|
|
TOKEN_ENCRYPTION_KEY_FILE=secrets/token_encryption_key \
|
|
./scripts/create_user.py --name estorozhenko \
|
|
--api-key-out secrets/estorozhenko_api_key.txt
|
|
|
|
Ключ показывается один раз и (опционально) сохраняется в файл (не в git!).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import asyncio
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# Даём импортировать app при запуске из любой директории
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
|
|
from app.database import init_db, async_session_factory # noqa: E402
|
|
from app.models import User # noqa: E402
|
|
from app.security import generate_api_key # noqa: E402
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description="Create md2vk user")
|
|
parser.add_argument("--name", required=True, help="display name")
|
|
parser.add_argument("--email", default=None, help="optional email")
|
|
parser.add_argument(
|
|
"--api-key-out",
|
|
default=None,
|
|
help="save API key to this file (NOT committed to git)",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
async def create() -> None:
|
|
await init_db()
|
|
async with async_session_factory() as session:
|
|
key, key_hash = generate_api_key()
|
|
user = User(
|
|
name=args.name,
|
|
email=args.email,
|
|
api_key_hash=key_hash,
|
|
api_key_prefix=key[:12],
|
|
is_active=True,
|
|
)
|
|
session.add(user)
|
|
await session.commit()
|
|
print(f"User created: id={user.id} name={user.name}")
|
|
print(f"API key: {key}")
|
|
print(f"prefix: {key[:12]}")
|
|
if args.api_key_out:
|
|
out = Path(args.api_key_out)
|
|
out.parent.mkdir(parents=True, exist_ok=True)
|
|
out.write_text(key + "\n", encoding="utf-8")
|
|
out.chmod(0o600)
|
|
print(f"API key saved to {out}")
|
|
|
|
try:
|
|
asyncio.run(create())
|
|
except Exception as exc: # noqa: BLE001
|
|
print(f"ERROR: {exc}", file=sys.stderr)
|
|
return 1
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main()) |