From 28dd23e444628ded32d54546a62f7459f0939981 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 30 Sep 2026 14:39:14 +0000 Subject: [PATCH 1/2] Publishing has never worked: one line, two wrong answers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit gitea.py answered a 401 or 403 from the git server by raising PermissionError("gitea-unauthorised"), with a comment saying the caller would refresh and retry. That caller was tokens.py, deleted two phases ago when the members area took over its own logins. Nothing has caught it since, so a refused token arrived as a 500 on Contenido — Flask's own page, in English, saying nothing — and, when approving a submission, as "no se encontró la imagen en el disco", because PermissionError is a subclass of OSError and the approve path caught OSError to mean a missing file. The page was displaying the photograph two lines above the message. Underneath both: a site-admin token cannot write to a repository. Gitea's scopes are per category and `admin` does not contain `repository`, so the editor has never been able to commit and nothing written in the members area has ever reached the site. server-setup.md said the fallback to GITEA_ADMIN_TOKEN "keeps an existing install working", which was the sentence that hid it; it now says what that token can and cannot do. Fixed: 401/403 raises a GiteaError naming the scope to check; approve reads the picture before the try and catches only FileNotFoundError, so "the image is missing" is said only when it is; and a 500 handler renders the site's own page and logs the traceback with the request path. Then the three wall pieces: Every name — wall, thread, comment, private message, dashboard, directory — renders through templates/_person.html, which links to vienalatina.com/ only when that person has published a page. Both failure modes are silent, so the rule lives in one macro instead of nine templates. A profile also has one canonical address now: // redirects to /, which is what url_for had been quietly preferring. One 👍 per member per thread or comment, clicking again takes it back. The table is shaped like attachments — two nullable parents, a CHECK that exactly one is set — and uniqueness is two partial indexes, because UNIQUE across a NULL column would make every comment reaction unique by accident. The `back` field goes through auth.safe_next (renamed from _safe_next), since a redirect somebody can type is an open redirect. Miembros is a directory: a card per person with photo, username, role, the first line of their bio, somewhere to write from and a link to their page. Admin controls fold into a per-card Gestionar block. That is also the fix for the misaligned row in the screenshot — four forms in a column two inches wide was the cause, and the table is gone. Photos inside the members area are served by a login-gated route even when the public page is unpublished, and the profile form now says so. 404 tests pass. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn --- README.md | 5 + apps/board/app.py | 23 ++- apps/board/auth.py | 8 +- apps/board/board.py | 101 ++++++++++++- apps/board/gitea.py | 26 +++- apps/board/home.py | 7 +- apps/board/members.py | 9 +- apps/board/messages.py | 6 +- apps/board/profiles.py | 41 +++++- apps/board/schema.sql | 27 ++++ apps/board/static/board.css | 104 +++++++++++++ apps/board/submissions.py | 33 +++-- apps/board/templates/_person.html | 13 ++ apps/board/templates/_reaction.html | 20 +++ apps/board/templates/conversation.html | 5 +- apps/board/templates/home.html | 5 +- apps/board/templates/members.html | 194 +++++++++++++++---------- apps/board/templates/profile_edit.html | 5 + apps/board/templates/submission.html | 3 +- apps/board/templates/submissions.html | 3 +- apps/board/templates/thread.html | 12 +- apps/board/templates/threads.html | 9 +- apps/board/tests/test_content.py | 73 ++++++++++ apps/board/tests/test_members.py | 80 +++++++++- apps/board/tests/test_profiles.py | 44 ++++++ apps/board/tests/test_reactions.py | 150 +++++++++++++++++++ apps/board/tests/test_submissions.py | 51 +++++++ docs/server-setup.md | 36 ++++- 28 files changed, 971 insertions(+), 122 deletions(-) create mode 100644 apps/board/templates/_person.html create mode 100644 apps/board/templates/_reaction.html create mode 100644 apps/board/tests/test_reactions.py diff --git a/README.md b/README.md index 20a89cc..86f1ede 100644 --- a/README.md +++ b/README.md @@ -191,6 +191,11 @@ included. Removing a post is visible to its author, quietly rewriting it is not. The same line runs through moderation: a moderator approves or returns a proposal, and never rewrites it to publish under somebody else's name. +The wall carries one 👍 per member per post or comment, every name links to that +person's page when they have published one, and *Miembros* is a directory of +cards rather than an admin table — the controls are there, folded into each card +for admins. + Its SQLite database is the only state on the server that git does not hold. `scripts/backup-board.sh` takes a consistent snapshot nightly — see `docs/server-setup.md` §11. diff --git a/apps/board/app.py b/apps/board/app.py index 45a312b..15224f5 100644 --- a/apps/board/app.py +++ b/apps/board/app.py @@ -10,7 +10,7 @@ from __future__ import annotations import os from datetime import datetime, timezone -from flask import Flask, render_template +from flask import Flask, render_template, request from werkzeug.middleware.proxy_fix import ProxyFix from .db import close_db, init_db @@ -173,5 +173,26 @@ def create_app(overrides: dict | None = None) -> Flask: return render_template("error.html", code=413, message="El mensaje es demasiado largo."), 413 + @app.errorhandler(500) + def _crashed(error): + """The page an unexpected exception produces. + + Without this Flask prints its own, in English, with no way back into the + site — which is what a stray PermissionError from the git client looked + like for two phases: a white page reading "Internal Server Error", giving + no hint that the cause was a token scope. The traceback goes to the log + with the path beside it, and the member gets the site's own page. + + `original_exception` is what Flask hands the handler; logging it here + rather than relying on the default keeps the request path in the same + line, which is the difference between a searchable log and a pile of + tracebacks. + """ + app.logger.error("Unhandled error at %s: %s", request.path, + getattr(error, "original_exception", error), exc_info=True) + return render_template( + "error.html", code=500, + message="Algo falló de nuestro lado. Ya ha quedado anotado."), 500 + init_db(app) return app diff --git a/apps/board/auth.py b/apps/board/auth.py index d2b654e..7f9c489 100644 --- a/apps/board/auth.py +++ b/apps/board/auth.py @@ -54,13 +54,17 @@ def load_member() -> None: g.member = row -def _safe_next(target: str) -> str: +def safe_next(target: str) -> str: """Only ever inside this app. An absolute or protocol-relative URL here would make the login form an open redirect: a crafted link signs somebody in and drops them on a page somebody else controls, with the trust of having just arrived from their own community site. + + Public rather than private now, because the login form is not the only place + that sends somebody back where they came from: any form carrying a `back` + field has the same hole, and two copies of this rule is one copy too many. """ prefix = current_app.config["URL_PREFIX"] + "/" return target if target.startswith(prefix) else url_for("home.index") @@ -117,7 +121,7 @@ def login(): passwords.prune_attempts() get_db().execute("UPDATE members SET last_seen_at = datetime('now') WHERE id = ?", (member["id"],)) - return redirect(_safe_next(target)) + return redirect(safe_next(target)) def invite_url(token: str) -> str: diff --git a/apps/board/board.py b/apps/board/board.py index 7873592..e793907 100644 --- a/apps/board/board.py +++ b/apps/board/board.py @@ -18,7 +18,7 @@ from __future__ import annotations from flask import (Blueprint, abort, current_app, flash, g, redirect, render_template, request, url_for) -from . import uploads +from . import auth, uploads from .db import get_db from .render import excerpt, to_html from .security import admin_required, login_required @@ -75,6 +75,36 @@ def _clean(title: str, body: str) -> tuple[str, str] | None: return title, body +# --- reactions ------------------------------------------------------------ +# +# One 👍 per member per thread or comment, and clicking it again takes it back. +# Counted in one query per page rather than one per card: a wall of twenty +# posts should not be forty round trips to SQLite for a number beside a thumb. + +def _reactions(column: str, ids: list[int]) -> dict[int, dict]: + """{parent id: {"count": n, "mine": bool}} for a whole page at once.""" + if not ids: + return {} + marks = ",".join("?" * len(ids)) + rows = get_db().execute( + f"""SELECT {column} AS parent, COUNT(*) AS total, + MAX(member_id = ?) AS mine + FROM reactions WHERE {column} IN ({marks}) + GROUP BY {column}""", + (g.member["id"], *ids), + ).fetchall() + return {row["parent"]: {"count": row["total"], "mine": bool(row["mine"])} + for row in rows} + + +def reactions_for_threads(ids: list[int]) -> dict[int, dict]: + return _reactions("thread_id", ids) + + +def reactions_for_comments(ids: list[int]) -> dict[int, dict]: + return _reactions("comment_id", ids) + + def _thread_or_404(thread_id: int): row = get_db().execute( "SELECT * FROM threads WHERE id = ? AND deleted_at IS NULL", (thread_id,) @@ -104,6 +134,7 @@ def threads(): page = max(1, request.args.get("page", 1, type=int)) rows = get_db().execute( """SELECT t.*, m.display_name AS author, + m.gitea_login AS author_login, m.profile_published AS author_published, (SELECT COUNT(*) FROM comments c WHERE c.thread_id = t.id AND c.deleted_at IS NULL) AS replies FROM threads t JOIN members m ON m.id = t.author_id @@ -115,8 +146,10 @@ def threads(): # One row past the page size answers "is there a next page" without a # second COUNT(*) over the whole table. has_next = len(rows) > PER_PAGE - return render_template("threads.html", threads=rows[:PER_PAGE], page=page, - has_next=has_next, excerpt=excerpt) + shown = rows[:PER_PAGE] + return render_template("threads.html", threads=shown, page=page, + has_next=has_next, excerpt=excerpt, + reactions=reactions_for_threads([t["id"] for t in shown])) @bp.route("/tema/") @@ -124,21 +157,27 @@ def threads(): def thread(thread_id: int): row = _thread_or_404(thread_id) db = get_db() - author = db.execute("SELECT display_name FROM members WHERE id = ?", - (row["author_id"],)).fetchone() + author = db.execute( + """SELECT display_name, gitea_login, profile_published + FROM members WHERE id = ?""", + (row["author_id"],)).fetchone() comments = db.execute( - """SELECT c.*, m.display_name AS author + """SELECT c.*, m.display_name AS author, + m.gitea_login AS author_login, m.profile_published AS author_published FROM comments c JOIN members m ON m.id = c.author_id WHERE c.thread_id = ? AND c.deleted_at IS NULL ORDER BY c.created_at""", (thread_id,), ).fetchall() - return render_template("thread.html", thread=row, author=author["display_name"], + return render_template("thread.html", thread=row, author=author, comments=comments, body_html=to_html(row["body_md"]), to_html=to_html, may_edit=may_edit, may_delete=may_delete, is_admin=is_admin(), thread_images=uploads.for_threads([thread_id]).get(thread_id, []), - comment_images=uploads.for_comments([c["id"] for c in comments])) + comment_images=uploads.for_comments([c["id"] for c in comments]), + reactions=reactions_for_threads([thread_id]), + comment_reactions=reactions_for_comments( + [c["id"] for c in comments])) @bp.route("/nuevo", methods=["GET", "POST"]) @@ -265,6 +304,52 @@ def delete_comment(comment_id: int): return redirect(url_for("board.thread", thread_id=row["thread_id"])) +@bp.route("/reaccion", methods=["POST"]) +@login_required +def react(): + """Add my reaction, or take it back if it is already there. + + One route for both parents, because the form posts which kind it is and the + alternative is two routes that differ by a column name. `kind` is checked + against a fixed pair before it reaches the statement, so nothing a member + types gets near the SQL. + + The parent is checked for real: a thread that has been deleted, or an id + that never existed, is a 404 rather than a row pointing at nothing. + """ + kind = request.form.get("kind") + if kind not in ("thread", "comment"): + abort(400, "Campo desconocido.") + target_id = request.form.get("id", type=int) + if not target_id: + abort(400, "Falta el identificador.") + + if kind == "thread": + row = _thread_or_404(target_id) + column, anchor = "thread_id", url_for("board.thread", thread_id=row["id"]) + else: + row = _comment_or_404(target_id) + column = "comment_id" + anchor = url_for("board.thread", thread_id=row["thread_id"]) + f"#c{row['id']}" + + db = get_db() + existing = db.execute( + f"SELECT id FROM reactions WHERE {column} = ? AND member_id = ?", + (target_id, g.member["id"]), + ).fetchone() + if existing: + db.execute("DELETE FROM reactions WHERE id = ?", (existing["id"],)) + else: + db.execute(f"INSERT INTO reactions ({column}, member_id) VALUES (?, ?)", + (target_id, g.member["id"])) + + # Back where they were, including which comment: a reaction should not move + # the page, and there is no JavaScript here to stop the form navigating. + # Through safe_next, because a `back` field taken at face value is an open + # redirect — the same hole the login form's `next` is checked for. + return redirect(auth.safe_next(request.form.get("back") or anchor)) + + @bp.route("/tema//estado", methods=["POST"]) @admin_required def set_state(thread_id: int): diff --git a/apps/board/gitea.py b/apps/board/gitea.py index 2832cc6..82bcd44 100644 --- a/apps/board/gitea.py +++ b/apps/board/gitea.py @@ -22,7 +22,7 @@ from __future__ import annotations import base64 import secrets import string -from urllib.parse import quote, urlencode +from urllib.parse import quote import requests from flask import current_app @@ -59,8 +59,6 @@ def _branch() -> str: return current_app.config["CONTENT_BRANCH"] -# --- sign-in ------------------------------------------------------------- - # --- account creation (site-admin token) --------------------------------- def admin_configured() -> bool: @@ -204,6 +202,22 @@ def _identity(member) -> dict: def _content_request(method: str, url: str, token: str, **kwargs): + """Every content call goes through here, and every refusal comes back as a + GiteaError the caller already knows how to show. + + This used to raise `PermissionError("gitea-unauthorised")` on a 401 or 403, + with a comment saying the caller would refresh the token and retry. That + caller was `tokens.py`, which refreshed OAuth tokens and was deleted when + the members area took over its own logins — so for two phases the refusal + was an exception nothing caught. It escaped `content.index` as a 500, and + `submissions.approve` mistook it for a missing file, because PermissionError + is a subclass of OSError. One line, two wrong answers, and a whole feature + that had never worked: the token in .env was a site-admin token, and Gitea's + scopes are per category, so `admin` grants nothing over a repository. + + Hence the message: the thing to check is the token's scope, and it should + say so on the screen rather than in a traceback nobody reads. + """ response = requests.request( method, url, headers={"Authorization": f"Bearer {token}"}, @@ -211,7 +225,11 @@ def _content_request(method: str, url: str, token: str, **kwargs): **kwargs, ) if response.status_code in (401, 403): - raise PermissionError("gitea-unauthorised") # caller refreshes and retries + raise GiteaError( + "El servidor de git rechazó el token del editor. Comprueba que " + "CONTENT_TOKEN existe y tiene permiso de escritura sobre el " + "repositorio (repository: Read and Write), no sólo de administración." + ) return response diff --git a/apps/board/home.py b/apps/board/home.py index 1493b3f..29446e3 100644 --- a/apps/board/home.py +++ b/apps/board/home.py @@ -31,6 +31,7 @@ def index(): db = get_db() threads = db.execute( """SELECT t.id, t.title, t.body_md, t.created_at, m.display_name AS author, + m.gitea_login AS author_login, m.profile_published AS author_published, (SELECT COUNT(*) FROM comments c WHERE c.thread_id = t.id AND c.deleted_at IS NULL) AS replies FROM threads t JOIN members m ON m.id = t.author_id @@ -41,6 +42,8 @@ def index(): conversations = db.execute( """SELECT other.id AS other_id, other.display_name AS other_name, + other.gitea_login AS other_login, + other.profile_published AS other_published, (SELECT COUNT(*) FROM messages msg WHERE msg.conversation_id = c.id AND msg.author_id != mine.member_id AND msg.deleted_at IS NULL @@ -69,7 +72,9 @@ def index(): queue = [] if submissions.may_moderate(): queue = db.execute( - """SELECT s.id, s.title, s.created_at, m.display_name AS author + """SELECT s.id, s.title, s.created_at, m.display_name AS author, + m.gitea_login AS author_login, + m.profile_published AS author_published FROM submissions s JOIN members m ON m.id = s.author_id WHERE s.state = 'pending' AND s.author_id != ? ORDER BY s.created_at LIMIT ?""", diff --git a/apps/board/members.py b/apps/board/members.py index c961224..d535bfb 100644 --- a/apps/board/members.py +++ b/apps/board/members.py @@ -121,6 +121,10 @@ REMOVED_ON_ERASE = { ("messages", "author_id"), ("blocks", "blocker_id"), ("blocks", "blocked_id"), + # A reaction is a fact about a person, not about the post: the thread + # survives as "Miembro eliminado", the thumbs-up does not survive as + # somebody's thumbs-up. + ("reactions", "member_id"), # A submission is private writing until a moderator approves it, so it goes # with the rest of the private writing. The remainder of an approved one is # the published post in the site repository, which already carries this @@ -179,6 +183,7 @@ def erase_member(db: sqlite3.Connection, member_id: int) -> list[str]: ) db.execute("DELETE FROM blocks WHERE blocker_id = ? OR blocked_id = ?", (member_id, member_id)) + db.execute("DELETE FROM reactions WHERE member_id = ?", (member_id,)) orphaned += [row["photo_name"] for row in db.execute( "SELECT photo_name FROM submissions WHERE author_id = ? AND photo_name IS NOT NULL", (member_id,), @@ -217,7 +222,9 @@ def _load(member_id: int): @login_required def index(): rows = get_db().execute( - """SELECT m.*, c.display_name AS creator + """SELECT m.*, c.display_name AS creator, + (SELECT COUNT(*) FROM threads t + WHERE t.author_id = m.id AND t.deleted_at IS NULL) AS posts FROM members m LEFT JOIN members c ON c.id = m.created_by WHERE m.role != 'tombstone' diff --git a/apps/board/messages.py b/apps/board/messages.py index 4942ecb..5637d9f 100644 --- a/apps/board/messages.py +++ b/apps/board/messages.py @@ -96,6 +96,8 @@ def inbox(): """SELECT c.id, other.display_name AS other_name, other.id AS other_id, + other.gitea_login AS other_login, + other.profile_published AS other_published, (SELECT body_md FROM messages WHERE conversation_id = c.id AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 1) AS last_body, @@ -201,7 +203,9 @@ def talk(member_id: int): rows = [] if conversation_id is not None: rows = db.execute( - """SELECT m.*, a.display_name AS author + """SELECT m.*, a.display_name AS author, + a.gitea_login AS author_login, + a.profile_published AS author_published FROM messages m JOIN members a ON a.id = m.author_id WHERE m.conversation_id = ? AND m.deleted_at IS NULL ORDER BY m.created_at""", diff --git a/apps/board/profiles.py b/apps/board/profiles.py index 9d74dda..90c6189 100644 --- a/apps/board/profiles.py +++ b/apps/board/profiles.py @@ -92,8 +92,20 @@ def _published(login: str): # --- the public page ------------------------------------------------------ -@public_bp.route("/") @public_bp.route("//") +def show_with_slash(name: str): + """One canonical address per profile. + + Both spellings have always worked, but `url_for` picked whichever was + registered last, so links inside the members area pointed at `/maria/` + while everything written by hand said `/maria`. Two URLs for one page is a + small thing until a search engine indexes both. This one sends people to + the other and nothing renders here. + """ + return redirect(url_for("profiles_public.show", name=name), code=301) + + +@public_bp.route("/") def show(name: str): """404 for anything that is not a published profile. @@ -138,6 +150,33 @@ def photo(stored_name: str): return send_from_directory(uploads.directory(), stored_name) +@bp.route("/miembro/foto/") +@login_required +def member_photo(stored_name: str): + """The same picture, for the people inside. + + `profiles.photo` above serves only photos belonging to a *published* page, + which is right for the open internet and wrong for Miembros: somebody who + has not published a public page has still chosen a face for the community + they joined, and a directory of grey squares is not a directory. So this one + is behind the login and asks only that the member is active. + + The profile form says so in as many words, because a picture turning up + somewhere its owner did not expect is exactly the surprise a profile form + exists to prevent. + """ + if not uploads.STORED_NAME.match(stored_name): + abort(404) + row = get_db().execute( + """SELECT 1 FROM members + WHERE photo_name = ? AND active = 1 AND role != 'tombstone'""", + (stored_name,), + ).fetchone() + if row is None: + abort(404) + return send_from_directory(uploads.directory(), stored_name) + + # --- editing it ----------------------------------------------------------- @bp.route("/mi-perfil", methods=["GET", "POST"]) diff --git a/apps/board/schema.sql b/apps/board/schema.sql index 967cd8e..ade97ad 100644 --- a/apps/board/schema.sql +++ b/apps/board/schema.sql @@ -265,3 +265,30 @@ CREATE INDEX IF NOT EXISTS submissions_queue ON submissions(created_at) WHERE state = 'pending'; CREATE INDEX IF NOT EXISTS submissions_author ON submissions(author_id, created_at); + +-- A 👍 on a thread or a comment. +-- +-- Shaped like `attachments`: two nullable parents and a CHECK that exactly one +-- is set, so a reaction cannot belong to both or to neither, and both parents +-- keep real foreign keys. +-- +-- The uniqueness rule — one reaction per member per thing — cannot be a plain +-- UNIQUE(member_id, thread_id, comment_id), because SQLite treats NULLs as +-- distinct and every comment reaction would have a NULL thread_id, making every +-- row unique by accident. Two partial indexes say what is meant instead. +-- +-- There is one kind of reaction and no notifications. A count and a toggle is +-- the whole feature: anything more is a second inbox nobody asked for. +CREATE TABLE IF NOT EXISTS reactions ( + id INTEGER PRIMARY KEY, + thread_id INTEGER REFERENCES threads(id), + comment_id INTEGER REFERENCES comments(id), + member_id INTEGER NOT NULL REFERENCES members(id), + created_at TEXT NOT NULL DEFAULT (datetime('now')), + CHECK ((thread_id IS NOT NULL) + (comment_id IS NOT NULL) = 1) +); + +CREATE UNIQUE INDEX IF NOT EXISTS reactions_one_per_thread + ON reactions(member_id, thread_id) WHERE thread_id IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS reactions_one_per_comment + ON reactions(member_id, comment_id) WHERE comment_id IS NOT NULL; diff --git a/apps/board/static/board.css b/apps/board/static/board.css index a441922..6f1dbc6 100644 --- a/apps/board/static/board.css +++ b/apps/board/static/board.css @@ -336,6 +336,11 @@ input[type="file"] { border: 1px solid var(--border-light); } +/* A name that leads somewhere. Underlined only on hover, because on a busy + wall every name being a permanent link turns the page into a rash. */ +.who-link { color: inherit; text-decoration: none; border-bottom: 1px dotted var(--border); } +.who-link:hover { color: var(--brand-dark); border-bottom-color: var(--brand); } + /* --- the corner account menu ----------------------------------------- */ /* * A
element, because the Content-Security-Policy has no @@ -433,3 +438,102 @@ input[type="file"] { white-space: nowrap; border: 0; } + +/* --- 👍 ---------------------------------------------------------------- */ + +.reaction { margin: 0; } +.reaction__button { + display: inline-flex; + align-items: center; + gap: 0.3rem; + padding: 0.2rem 0.6rem; + border: 1px solid var(--border-light); + border-radius: 999px; + background: var(--surface); + color: var(--muted); + font-size: 0.85rem; + cursor: pointer; + line-height: 1.6; +} +.reaction__button:hover { border-color: var(--brand); color: var(--brand-dark); } +/* Mine: filled, so "did I already?" is answered at a glance rather than by + counting. */ +.reaction__button--mine { + background: var(--brand-soft); + border-color: var(--brand); + color: var(--brand-dark); +} +.reaction__count { font-variant-numeric: tabular-nums; } + +.card__foot { display: flex; align-items: center; gap: 0.75rem; } + +/* --- the member directory --------------------------------------------- */ + +.people { + list-style: none; + margin: 0; + padding: 0; + display: grid; + /* auto-fill with a minimum, so it is three across on a laptop and one on a + phone without a media query deciding where the breaks are. */ + grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); + gap: 1rem; +} +.person-card { + background: var(--surface); + border: 1px solid var(--border-light); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-sm); + padding: 1rem; +} +.person-card--off { opacity: 0.55; } +.person-card__head { display: flex; align-items: center; gap: 0.75rem; } +.person-card__photo { + width: 56px; + height: 56px; + flex: 0 0 56px; + border-radius: 50%; + object-fit: cover; + border: 1px solid var(--border-light); +} +.person-card__photo--none { + display: flex; + align-items: center; + justify-content: center; + background: var(--brand-soft); + color: var(--brand-dark); + font-size: 1.4rem; + font-weight: 700; +} +.person-card__who { min-width: 0; } /* so a long name wraps instead of pushing */ +.person-card__name { margin: 0; font-size: 1.05rem; } +.person-card__name .muted { font-weight: 400; } +.person-card__who p { margin: 0.15rem 0 0; } +.person-card__bio { + margin: 0.75rem 0 0; + color: var(--muted); + font-size: 0.9rem; +} +.person-card__foot { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + margin-top: 0.75rem; +} +.person-card__admin { margin-top: 0.75rem; border-top: 1px solid var(--border-light); padding-top: 0.5rem; } +.person-card__admin summary { + cursor: pointer; + color: var(--subtle); + font-size: 0.85rem; +} +/* The one place the old table went wrong: four forms in a column two inches + wide. Here they are one per line, with room for the words. */ +.person-card__actions { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.5rem; + margin-top: 0.5rem; +} +.person-card__actions form { margin: 0; } +.person-card__actions p { margin: 0; } diff --git a/apps/board/submissions.py b/apps/board/submissions.py index 0b85d45..547d9ff 100644 --- a/apps/board/submissions.py +++ b/apps/board/submissions.py @@ -70,7 +70,7 @@ def pending_count() -> int: def _load(submission_id: int): row = get_db().execute( """SELECT s.*, m.display_name AS author, m.email AS author_email, - m.gitea_login AS author_login, + m.gitea_login AS author_login, m.profile_published AS author_published, r.display_name AS reviewer FROM submissions s JOIN members m ON m.id = s.author_id @@ -127,7 +127,9 @@ def index(): queue = [] if may_moderate(): queue = db.execute( - """SELECT s.*, m.display_name AS author + """SELECT s.*, m.display_name AS author, + m.gitea_login AS author_login, + m.profile_published AS author_published FROM submissions s JOIN members m ON m.id = s.author_id WHERE s.state = 'pending' AND s.author_id != ? ORDER BY s.created_at""", @@ -308,19 +310,30 @@ def approve(submission_id: int): "image": "", "manual_translation": False, } + # Read the picture before the try, and catch only the error that means what + # it says. The first version wrapped everything in `except OSError`, which + # also catches PermissionError and every `requests` failure — so a git + # server refusing the token was reported as a missing photograph, on a page + # displaying that photograph. An except clause wide enough to catch the + # network is wide enough to lie. + picture = None + if row["photo_name"]: + try: + picture = (uploads.directory() / row["photo_name"]).read_bytes() + except FileNotFoundError: + current_app.logger.warning("submission %s: %s is not on disk", + submission_id, row["photo_name"]) + flash("No se encontró la imagen en el disco. Pide al autor que la " + "vuelva a subir.", "error") + return redirect(url_for("submissions.show", submission_id=submission_id)) + try: - if row["photo_name"]: - data = (uploads.directory() / row["photo_name"]).read_bytes() - fields["image"] = content.commit_picture(data, row["photo_name"], author) + if picture is not None: + fields["image"] = content.commit_picture(picture, row["photo_name"], author) path = content.publish("post", fields, row["body_md"], author) except gitea.GiteaError as exc: flash(str(exc), "error") return redirect(url_for("submissions.show", submission_id=submission_id)) - except OSError: - current_app.logger.exception("submission %s: picture missing on disk", submission_id) - flash("No se encontró la imagen en el disco. Pide al autor que la vuelva a subir.", - "error") - return redirect(url_for("submissions.show", submission_id=submission_id)) get_db().execute( """UPDATE submissions diff --git a/apps/board/templates/_person.html b/apps/board/templates/_person.html new file mode 100644 index 0000000..9044858 --- /dev/null +++ b/apps/board/templates/_person.html @@ -0,0 +1,13 @@ +{# A member's name, as a link to their page when they have one. + + The rule is in one place because it is easy to get wrong in two directions: + a name that never links makes the profiles invisible, and a name that always + links sends people to a 404 for everybody who has not published theirs. So + every screen calls this, and none of them has to remember. #} +{% macro person(name, login=None, published=False) %} +{%- if published and login -%} +{{ name }} +{%- else -%} +{{ name }} +{%- endif -%} +{% endmacro %} diff --git a/apps/board/templates/_reaction.html b/apps/board/templates/_reaction.html new file mode 100644 index 0000000..aed94b9 --- /dev/null +++ b/apps/board/templates/_reaction.html @@ -0,0 +1,20 @@ +{# The 👍 button, for a thread or a comment. + + A form rather than a link, because it changes something and a GET that + changes something is a thing a prefetching browser will do on its own. It + carries where it was pressed so the page does not jump to the top, and the + handler puts that through the same open-redirect check as the login form. #} +{% macro reaction(kind, target_id, state, back) %} +
+ + + + + +
+{% endmacro %} diff --git a/apps/board/templates/conversation.html b/apps/board/templates/conversation.html index 633ba3d..1fdb630 100644 --- a/apps/board/templates/conversation.html +++ b/apps/board/templates/conversation.html @@ -1,17 +1,18 @@ {% extends "base.html" %} +{% from "_person.html" import person %} {% from "_attachments.html" import attachments %} {% block title %}{{ other.display_name }}{% endblock %} {% block main %}
-

{{ other.display_name }}

+

{{ person(other.display_name, other.gitea_login, other.profile_published) }}

Volver
{% for m in messages %}
- {{ m.author }} · + {{ person(m.author, m.author_login, m.author_published) }} ·
{{ to_html(m.body_md) }}
{{ attachments(images.get(m.id, [])) }} diff --git a/apps/board/templates/home.html b/apps/board/templates/home.html index 597f362..fd36208 100644 --- a/apps/board/templates/home.html +++ b/apps/board/templates/home.html @@ -1,4 +1,5 @@ {% extends "base.html" %} +{% from "_person.html" import person %} {% block title %}Inicio{% endblock %} {% block main %} @@ -18,7 +19,7 @@ {% for item in queue %}

{{ item.title }} - {{ item.author }} · {{ item.created_at }} + {{ person(item.author, item.author_login, item.author_published) }} · {{ item.created_at }}

{% endfor %} @@ -52,7 +53,7 @@ {% for t in threads %}

{{ t.title }} - {{ t.author }} · {{ t.replies }} respuesta{{ '' if t.replies == 1 else 's' }} + {{ person(t.author, t.author_login, t.author_published) }} · {{ t.replies }} respuesta{{ '' if t.replies == 1 else 's' }}

{% endfor %} diff --git a/apps/board/templates/members.html b/apps/board/templates/members.html index d1535d7..7dba1b8 100644 --- a/apps/board/templates/members.html +++ b/apps/board/templates/members.html @@ -1,4 +1,5 @@ {% extends "base.html" %} +{% from "_person.html" import person %} {% block title %}Miembros{% endblock %} {% set me = g.member %} @@ -13,86 +14,127 @@ {% endif %} - - - {% if is_admin %}{% endif %} - - +{# People, not rows. This was a five-column table whose last column held four + forms, which is how the actions ended up wrapping on top of each other in a + column two inches wide. A card has room for a face and somewhere to write + from, and the admin controls fold away into a
so that the page is + a directory first and a control panel second. #} +
    {% for m in members %} -
- - - - - {% if is_admin %} - +
  • +
    + {% if m.photo_name %} + + {% else %} + {# Their initial rather than a silhouette: a placeholder that is at + least theirs. #} + {% endif %} -
  • - {% endfor %} - -
    NombreUsuarioRolEstado
    {{ m.display_name }}{% if m.id == me.id %} (tú){% endif %}{{ m.gitea_login }}{{ labels[m.role] }}{{ 'Activo' if m.active else 'Suspendido' }} - {# The owner is untouchable, so the row shows nothing rather than - buttons that would only produce a 403. #} - {% if m.role != 'owner' %} -
    - - - -
    - - {# Any admin can re-send, not just the owner: the usual reason - somebody needs this is that the admin who added them made - the account by hand, and waiting for the owner to be - around defeats the point. Hidden without an address, - because the handler would only refuse. #} - {% if m.email and m.active %} -
    - - -
    - {% endif %} - - {# A toggle worked while there were two roles. With three it has to - be a choice, and the options are the ones this person may - actually grant — the handler checks the same thing. #} - {% if is_owner or m.role != 'admin' %} -
    - - - - -
    - {% endif %} - - {% if is_owner %} - {% if m.role == 'admin' and m.active %} -
    - - -
    - {% endif %} - -
    - - -
    - {% endif %} - {% endif %} -
    +
    +

    + {{ person(m.display_name, m.gitea_login, m.profile_published) }} + {% if m.id == me.id %}(tú){% endif %} +

    + {# The username is shown to everyone: it is not a secret, it is + their address — vienalatina.com/ — and somebody + looking for a person's page needs to know how it is spelled. + The email stays inside the admin block. #} +

    + {{ m.gitea_login }} · {{ labels[m.role] }} + {% if not m.active %} · Suspendido{% endif %} + {% if m.posts %} · {{ m.posts }} en el muro{% endif %} +

    +
    + + + {% if m.bio %}

    {{ m.bio.split('\n')[0][:160] }}

    {% endif %} + +
    + {% if m.id != me.id and m.active %} + Escribir + {% endif %} + {% if m.profile_published %} + Su página + {% elif m.id == me.id %} + Editar mi perfil + {% endif %} +
    + + {% if is_admin and m.role != 'owner' %} + {# A
    , not a script: the CSP has no 'unsafe-inline'. Closed by + default, so the directory reads as a directory. #} +
    + Gestionar +
    +
    + + + +
    + + {# Any admin can re-send, not just the owner: the usual reason + somebody needs this is that the admin who added them made the + account by hand, and waiting for the owner defeats the point. + Hidden without an address, because the handler would refuse. #} + {% if m.email and m.active %} +
    + + +
    + {% endif %} + + {% if is_owner or m.role != 'admin' %} +
    + + + + +
    + {% endif %} + + {% if is_owner %} + {% if m.role == 'admin' and m.active %} +
    + + +
    + {% endif %} + +
    + + +
    + {% endif %} + + {% if m.email %}

    {{ m.email }}

    {% endif %} +
    +
    + {% endif %} + + {% endfor %} + + +{% if is_admin %}

    Hay un solo responsable. El responsable da de alta administradores; los - administradores dan de alta usuarios. Nadie puede suspender ni degradar al - responsable: para dejar el cargo hay que transferirlo a un administrador. + administradores dan de alta miembros y moderadores. Nadie puede suspender ni + degradar al responsable: para dejar el cargo hay que transferirlo a un + administrador.

    +{% endif %} {% endblock %} diff --git a/apps/board/templates/profile_edit.html b/apps/board/templates/profile_edit.html index 64142ab..5988c6d 100644 --- a/apps/board/templates/profile_edit.html +++ b/apps/board/templates/profile_edit.html @@ -35,6 +35,11 @@ {% if g.member.photo_name %}

    Ya tienes una. Subir otra la reemplaza.

    {% endif %} +

    + Tu foto aparece en Miembros, + que sólo ven las personas que han entrado. Fuera del sitio sólo se ve si + publicas tu página, abajo. +