KaartechUK_SLM / scripts /create_admin_user.py
G Rohit Sudarsen
Claude Sonnet 5
Add real per-user login (auth protection for the whole app)
003b799
Raw History Blame Contribute Delete
2.78 kB
"""
Run this locally to create (or reset the password for) a real login
account - the only way accounts get created, deliberately. There is no
POST /auth/register endpoint: entering the password here, on your own
machine, via getpass (hidden input, never echoed) means the plaintext
value never crosses the network or lands in any request log, unlike a
signup form would.
Usage:
pip install psycopg2-binary bcrypt
export DATABASE_URL="postgres://...same value as the Space secret..."
python scripts/create_admin_user.py
Safe to re-run for the same email - it updates the password/display name
of an existing account (ON CONFLICT DO UPDATE) rather than erroring.
"""
import getpass
import os
import sys
import bcrypt
import psycopg2
_SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
id BIGSERIAL PRIMARY KEY,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
display_name TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_login_at TIMESTAMPTZ
);
"""
def main():
database_url = os.environ.get("DATABASE_URL")
if not database_url:
print("DATABASE_URL is not set in this shell - export the same value you set as the", file=sys.stderr)
print("Space's DATABASE_URL secret, then re-run this script.", file=sys.stderr)
sys.exit(1)
email = input("Email: ").strip().lower()
if not email or "@" not in email:
print("That doesn't look like a real email address - aborting.", file=sys.stderr)
sys.exit(1)
display_name = input("Display name: ").strip()
if not display_name:
print("Display name can't be empty - aborting.", file=sys.stderr)
sys.exit(1)
password = getpass.getpass("Password (hidden): ")
confirm = getpass.getpass("Confirm password: ")
if password != confirm:
print("Passwords didn't match - aborting.", file=sys.stderr)
sys.exit(1)
if len(password) < 8:
print("Password must be at least 8 characters - aborting.", file=sys.stderr)
sys.exit(1)
password_hash = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
conn = psycopg2.connect(database_url)
conn.autocommit = True
with conn.cursor() as cur:
cur.execute(_SCHEMA)
cur.execute(
"""
INSERT INTO users (email, password_hash, display_name)
VALUES (%s, %s, %s)
ON CONFLICT (email) DO UPDATE
SET password_hash = EXCLUDED.password_hash,
display_name = EXCLUDED.display_name
""",
(email, password_hash, display_name),
)
conn.close()
print(f"\nDone - {email} can now log in with the password you just entered.")
if __name__ == "__main__":
main()