Spaces:
Sleeping

File size: 2,059 Bytes
69d639b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""Idempotent dashboard-user seed.

Reads ``SEED_USERS`` (JSON array of ``{"username", "password"}`` objects) and
inserts any usernames that don't already exist in the ``users`` table. Existing
rows are left alone — rotate passwords by deleting the row first (or by running
your own one-off update). Safe to call on every container start.

Usage:
    uv run python scripts/seed_users.py
"""

from __future__ import annotations

import json
import os
import sys

from opportunity_tracker.dashboard.users import hash_password
from opportunity_tracker.db import SessionLocal
from opportunity_tracker.models import User


def main() -> int:
    raw = os.environ.get("SEED_USERS", "").strip()
    if not raw:
        print("[seed_users] SEED_USERS not set; nothing to do.")
        return 0

    try:
        entries = json.loads(raw)
    except json.JSONDecodeError as exc:
        print(f"[seed_users] SEED_USERS is not valid JSON: {exc}", file=sys.stderr)
        return 2

    if not isinstance(entries, list):
        print("[seed_users] SEED_USERS must be a JSON array.", file=sys.stderr)
        return 2

    inserted = skipped = 0
    with SessionLocal() as db:
        for entry in entries:
            if not isinstance(entry, dict):
                print(f"[seed_users] skipping non-object entry: {entry!r}", file=sys.stderr)
                continue
            username = entry.get("username")
            password = entry.get("password")
            if not username or not password:
                print(
                    f"[seed_users] skipping entry missing username/password: {entry!r}",
                    file=sys.stderr,
                )
                continue
            if db.get(User, username) is not None:
                skipped += 1
                continue
            db.add(User(username=username, password_hash=hash_password(password)))
            inserted += 1
        db.commit()

    print(f"[seed_users] inserted={inserted} skipped_existing={skipped}")
    return 0


if __name__ == "__main__":
    sys.exit(main())