db: enroll() accepts github profile; no longer returns edit_token

This commit is contained in:
shay
2026-04-19 18:45:26 -04:00
parent 57b782ceaf
commit 22483aea19
2 changed files with 38 additions and 35 deletions
+24 -22
View File
@@ -152,44 +152,46 @@ def settings_hash(settings: dict) -> str:
# ---- settings / enrollment ----
def enroll(username: str, defaults: dict) -> dict:
"""Insert a settings row + increment daily counter + enqueue build.
def enroll(username: str, defaults: dict,
github_id: int | None = None,
github_avatar_url: str | None = None) -> dict:
"""Insert a settings row if missing, bump the daily counter, enqueue a build.
Returns {"job_id", "edit_token"}. The edit_token is the bearer token the
caller must present on future settings mutations for this user. We only
store its SHA-256 hash, so the plaintext here is the one and only chance
to surface it to the client. Subsequent enroll() calls for an existing
user return `edit_token=None` to avoid leaking tokens issued to earlier
registrants — settings cannot be taken over by re-enrolling.
Idempotent: calling again for an existing user refreshes github_avatar_url
(so login keeps the avatar fresh) and enqueues a rebuild. Always returns
{"job_id": int}. No token is returned — auth is handled by the signed
session cookie.
"""
sh = settings_hash(defaults)
now = _now()
token = secrets.token_urlsafe(32)
token_hash = _hash_edit_token(token)
with _settings_conn() as c:
cur_ins = c.execute(
"""INSERT INTO users(username, settings_json, settings_hash, enrolled_at,
last_requested_at, edit_token_hash)
VALUES (?, ?, ?, ?, ?, ?)
last_requested_at, github_id, github_avatar_url)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(username) DO NOTHING""",
(username, json.dumps(defaults), sh, now, now, token_hash),
(username, json.dumps(defaults), sh, now, now, github_id, github_avatar_url),
)
inserted = cur_ins.rowcount == 1
c.execute(
"""INSERT INTO enrollments_daily(day, count) VALUES (?, 1)
ON CONFLICT(day) DO UPDATE SET count = count + 1""",
(_today(),),
)
if not inserted and (github_id is not None or github_avatar_url is not None):
c.execute(
"UPDATE users SET github_id=COALESCE(?, github_id), "
"github_avatar_url=COALESCE(?, github_avatar_url) WHERE username=?",
(github_id, github_avatar_url, username),
)
if inserted:
c.execute(
"""INSERT INTO enrollments_daily(day, count) VALUES (?, 1)
ON CONFLICT(day) DO UPDATE SET count = count + 1""",
(_today(),),
)
cur = c.execute(
"""INSERT INTO jobs(kind, username, status, created_at, updated_at)
VALUES ('build', ?, 'pending', ?, ?)""",
(username, now, now),
)
c.commit()
return {
"job_id": cur.lastrowid,
"edit_token": token if inserted else None,
}
return {"job_id": cur.lastrowid}
def enrollments_today() -> int: