vienalatina/apps/board/tokens.py
Claude 635372d7a2
Write the site from the members area instead of Decap
Decap looks like a different product because it cannot be made to look like
this one: its maintainer's answer is override the CSS and accept that class
names move between releases, or fork it and carry that forever. Neither is
worth building on, so editing moves into the app that already has the site's
design and this project's tests.

Posts are files in git, so the editor is a form that commits a file through
Gitea's contents API. No working copy, no queue, no new state, and no way for
the pipeline to tell which editor wrote the file — which is what makes running
both at once safe. Decap keeps working; nothing here removes it, and the
fallback if something is missing is switching tabs.

Filenames and frontmatter are not this module's to invent. They are the
contract scripts/translate.py reads: `<basename>.es.md` is what split_lang()
parses, the date prefix is what keeps two posts with one title off a single
URL, and the absence of `translated_from` is what marks a file as something a
person wrote. Several tests import translate.py and run its own parser over
what the editor produced, because a file it cannot parse publishes in Spanish
and is never translated, with nothing reported anywhere.

Commits carry the writer's own Gitea account rather than a bot's, so history
says who wrote each post and Gitea's permissions apply unchanged. That needs
their access token, which lives in the database and never in a cookie: Flask
signs cookies but does not encrypt them, and a token is enough to commit as its
owner. Gitea expires tokens after about an hour, so they refresh ahead of
expiry and retry once on rejection — without that, saving would start failing
partway through an afternoon for no reason the writer could see.

Publishing is admin-only. Posting to the internal board and publishing to the
public site are different permissions, and the second is the larger grant.

Listing caches frontmatter against the git blob sha, because the contents API
returns names without bodies: that turns one request per post on every page
load into one request in total, and needs no invalidation, since a sha changes
only when the file does.

Verified: 97 checks. The filename translate.py parses, an authored source that
is_generated() rejects, the freeze toggle round-tripping, a stale sha refused
with the other edit intact, six filename shapes that must 404 including a
generated sibling, plain members refused, an SVG rejected as an image, uploads
not colliding, the cache reading each file once and refreshing when it changes,
and a preview that renders markdown, escapes script tags and publishes nothing.
Smoke-tested live: routes register and gate correctly.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-09-25 15:07:31 +00:00

98 lines
3.1 KiB
Python

"""Keeping the member's Gitea token usable for as long as they are signed in.
Gitea's OAuth access tokens expire after about an hour. A writer who opened the
editor after lunch and saved at three would otherwise get a failure with no
explanation and no way to act on it, so this refreshes ahead of expiry and
retries once when Gitea rejects a token anyway.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from flask import g
from . import gitea
from .db import get_db
# Refresh this far before the stated expiry. A token that dies mid-request is
# indistinguishable to the writer from the app being broken.
EARLY = timedelta(minutes=5)
class NeedsSignIn(RuntimeError):
"""The token is gone or unrefreshable — send them through Gitea again."""
def _now() -> datetime:
return datetime.now(timezone.utc)
def save(member_id: int, payload: dict) -> None:
expires_in = payload.get("expires_in")
expires_at = (
(_now() + timedelta(seconds=int(expires_in))).isoformat()
if expires_in else None
)
get_db().execute(
"""INSERT INTO gitea_tokens (member_id, access_token, refresh_token, expires_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(member_id) DO UPDATE SET
access_token = excluded.access_token,
refresh_token = excluded.refresh_token,
expires_at = excluded.expires_at,
updated_at = datetime('now')""",
(member_id, payload["access_token"], payload.get("refresh_token", ""), expires_at),
)
def forget(member_id: int) -> None:
get_db().execute("DELETE FROM gitea_tokens WHERE member_id = ?", (member_id,))
def _stored(member_id: int):
return get_db().execute(
"SELECT * FROM gitea_tokens WHERE member_id = ?", (member_id,)
).fetchone()
def _refresh(row) -> str:
if not row["refresh_token"]:
raise NeedsSignIn()
try:
payload = gitea.refresh_token(row["refresh_token"])
except gitea.GiteaError as exc:
raise NeedsSignIn() from exc
save(row["member_id"], payload)
return payload["access_token"]
def access_token(member_id: int) -> str:
row = _stored(member_id)
if row is None:
raise NeedsSignIn()
if row["expires_at"]:
expires = datetime.fromisoformat(row["expires_at"])
if _now() + EARLY >= expires:
return _refresh(row)
return row["access_token"]
def with_token(call, *args, **kwargs):
"""Run a Gitea call with the current member's token, refreshing once if it
is rejected.
The retry exists because expiry is not the only reason a token stops
working — it can be revoked in Gitea, or invalidated by a password change —
and in those cases the clock says the token is still fine.
"""
member_id = g.member["id"]
token = access_token(member_id)
try:
return call(*args, token=token, **kwargs)
except PermissionError:
row = _stored(member_id)
if row is None:
raise NeedsSignIn()
return call(*args, token=_refresh(row), **kwargs)