vienalatina/apps/board/auth.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

141 lines
5.1 KiB
Python

"""Sign-in through Gitea.
The rule this module exists to enforce: **a Gitea account is not a membership.**
Gitea answers "who is this person"; the members table answers "may they be
here". Conflating the two would admit every account on the instance, including
the `vienalatina-translations` bot, and would mean anyone who ever gets a Gitea
account for an unrelated reason silently gains access to the board.
"""
from __future__ import annotations
import secrets
from flask import (Blueprint, current_app, flash, g, redirect, render_template,
request, session, url_for)
from . import gitea, tokens
from .db import get_db
bp = Blueprint("auth", __name__)
def redirect_uri() -> str:
return current_app.config["BASE_URL"].rstrip("/") + url_for("auth.callback")
def load_member() -> None:
"""Attach the signed-in member to `g`, or None. Runs on every request.
The role is read from the database each time rather than cached in the
session, so demoting or deactivating somebody takes effect on their next
click instead of whenever their cookie happens to expire.
"""
g.member = None
member_id = session.get("member_id")
if member_id is None:
return
row = get_db().execute(
"""SELECT * FROM members
WHERE id = ? AND active = 1 AND role IN ('owner', 'admin', 'user')""",
(member_id,),
).fetchone()
if row is None:
session.clear()
return
g.member = row
@bp.route("/login")
def login():
if g.member is not None:
return redirect(url_for("board.threads"))
return render_template("login.html", next=request.args.get("next", ""))
@bp.route("/login/start")
def start():
# State ties the callback to this browser session; without it, an attacker
# can feed you their own authorization code and log you into their account.
state = secrets.token_urlsafe(24)
session["oauth_state"] = state
session["oauth_next"] = request.args.get("next", "")
return redirect(gitea.authorize_url(state, redirect_uri()))
@bp.route("/auth/callback")
def callback():
expected = session.pop("oauth_state", None)
given = request.args.get("state")
if not expected or not given or not secrets.compare_digest(expected, given):
flash("El inicio de sesión no se pudo verificar. Inténtalo de nuevo.", "error")
return redirect(url_for("auth.login"))
code = request.args.get("code", "")
if not code:
flash("Gitea no devolvió un código de autorización.", "error")
return redirect(url_for("auth.login"))
try:
credentials = gitea.exchange_code(code, redirect_uri())
profile = gitea.fetch_user(credentials["access_token"])
except gitea.GiteaError as exc:
current_app.logger.warning("OAuth failed: %s", exc)
flash(str(exc), "error")
return redirect(url_for("auth.login"))
except Exception: # network trouble, malformed JSON, Gitea down
current_app.logger.exception("OAuth failed unexpectedly")
flash("No se pudo contactar con Gitea. Inténtalo más tarde.", "error")
return redirect(url_for("auth.login"))
login_name = (profile.get("login") or "").strip()
db = get_db()
member = db.execute(
"""SELECT * FROM members
WHERE gitea_login = ? AND active = 1 AND role IN ('owner', 'admin', 'user')""",
(login_name,),
).fetchone()
if member is None:
# Says nothing about whether the account exists, is inactive, or was
# never a member: an outsider who reaches this page learns only that
# they are not in.
current_app.logger.info("Rejected sign-in for non-member %r", login_name)
flash("Tu cuenta no tiene acceso a esta área. Pide a un administrador que te dé de alta.",
"error")
return redirect(url_for("auth.login"))
db.execute(
"""UPDATE members
SET display_name = ?, email = ?, last_seen_at = datetime('now')
WHERE id = ?""",
(profile.get("full_name") or login_name, profile.get("email") or "", member["id"]),
)
# A fresh session id on privilege change, so a cookie captured before login
# is not still valid after it.
session.clear()
session["member_id"] = member["id"]
# Kept so the editor can commit as this person rather than as a bot. Stored
# in the database, never in the cookie — see apps/board/tokens.py.
tokens.save(member["id"], credentials)
target = request.args.get("next") or session.pop("oauth_next", "") or ""
# Only ever redirect within this app: an absolute URL here would make the
# login page an open redirect that phishing can point anywhere.
if not target.startswith(current_app.config["URL_PREFIX"] + "/"):
target = url_for("board.threads")
return redirect(target)
@bp.route("/logout", methods=["POST"])
def logout():
# Drop the Gitea token too. Signing out should stop the server being able to
# act as you, not just stop the browser being able to ask it to.
if g.member is not None:
tokens.forget(g.member["id"])
session.clear()
flash("Sesión cerrada.", "ok")
return redirect(url_for("auth.login"))