| |
| import os, sqlite3 |
| from datetime import datetime |
|
|
| |
| DB_PATH = os.environ.get("API_DB_PATH", "/data/api_keys.sqlite3") |
|
|
| |
| DEFAULT_KEY = os.environ.get("DEFAULT_API_KEY", "sk-1234") |
| BOOTSTRAP_KEY = "sk-bootstrap-1234" |
|
|
| os.makedirs(os.path.dirname(DB_PATH), exist_ok=True) |
|
|
| with sqlite3.connect(DB_PATH) as conn: |
| cur = conn.cursor() |
| cur.execute(""" |
| CREATE TABLE IF NOT EXISTS api_keys( |
| id INTEGER PRIMARY KEY AUTOINCREMENT, |
| api_key TEXT UNIQUE, |
| label TEXT, |
| created_at TEXT NOT NULL, |
| last_used TEXT, |
| active INTEGER NOT NULL DEFAULT 1 |
| ) |
| """) |
|
|
| now = datetime.utcnow().isoformat(timespec="seconds") |
|
|
| def upsert(key: str, label: str): |
| key = (key or "").strip() |
| if not key: |
| return |
| |
| cur.execute( |
| """ |
| INSERT INTO api_keys(api_key, label, created_at, last_used, active) |
| VALUES (?, ?, ?, ?, 1) |
| ON CONFLICT(api_key) DO UPDATE SET |
| label = excluded.label, |
| last_used = excluded.last_used, |
| active = 1 |
| """, |
| (key, label, now, now), |
| ) |
|
|
| upsert(DEFAULT_KEY, "default") |
| upsert(BOOTSTRAP_KEY, "bootstrap") |
|
|
| conn.commit() |
|
|
|
|