vienalatina/apps/board/profiles.py
Claude 5ea6b1ac98
One dashboard, five sections, and a moderation queue
The members area had grown one navigation entry per phase, and three of the
five were inside an admin-only block in base.html — so an ordinary member
signed in to a wall and a member list, with their own profile, their own
private messages and the content editor all invisible. Everything worked and
nothing was reachable. That is the bug this starts from.

The navigation is now Inicio · Muro · Privados · Publicaciones, plus Gestión
for admins, and the account items (Mi perfil, Descargar mis datos, Salir) moved
to a menu under the member's own name — a <details> element, because the CSP has
no 'unsafe-inline' and a menu needing onclick="" silently never opens. Inicio is
a new dashboard; the wall moved from /comunidad/ to /comunidad/muro and kept its
thread URLs. test_navigation.py asserts the navigation per role from the
rendered page, so this cannot come back quietly.

Public posts are now curated. A member proposes one and it waits in a new
`submissions` table; a moderator or admin approves it — which commits it
through content.publish, the same function the editor uses, with the author
named per commit so git history says who wrote it, not who approved it — or
returns it with a reason the author reads. Moderators and admins do not queue.
Nothing a member writes reaches the repository before approval, because a
commit to it *is* publication: the webhook starts the pipeline. A proposal's
picture stays private in /data/uploads until then, and the private copy goes
when the public one is committed. There is deliberately no way to promote a wall
thread into a proposal.

The moderator role needed the role CHECK widened, and SQLite has no DROP
CONSTRAINT, so migration 4 rebuilds `members` — eight tables reference it, the
one-owner index has to be recreated by hand, and PRAGMA foreign_key_check runs
before the commit. One trap worth recording: the allowed roles can only be read
back out of sqlite_master's verbatim CREATE TABLE text, comments included, so
schema.sql's own comment explaining the rebuild made the step decide it had
already run. The start-up test caught it; comments are stripped now.

A moderator curates content and has no power over people: no creating,
suspending, promoting or erasing anybody. set_role moved from owner-only to
admin-level so moderators can be appointed routinely, and checks may_create on
the new role as well, so admins still cannot mint admins. content.py splits per
collection — posts need a moderator, the site's static pages need an admin.

Also: erasure deletes a member's submissions and their pictures and clears
reviewed_by, which the existing foreign-key guard forced; deploy-board.sh takes
a backup before restarting, since two migrations now rebuild a table in place
and one of them holds your own account; README and docs/server-setup.md updated
for the roles, the sections and migration 4.

370 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-09-30 11:09:55 +00:00

189 lines
6.7 KiB
Python

"""Public pages at vienalatina.com/su-nombre.
Two blueprints, because these live at opposite ends of the site: the page
itself sits at the top level of the public site, and the form that edits it
sits inside the members area behind the login.
**The top level is shared with the whole static site**, which is what makes
this the riskiest thing in the app. The protection is in the Caddyfile and it
is worth understanding from here: a request only reaches this module when the
path is a single segment *and* Hugo has built nothing there. The static site
always wins, decided by asking the filesystem rather than by a list of reserved
paths that would be wrong the first time somebody adds a page to the site.
So a member whose name collides with `/de/` does not shadow anything — they get
a page nobody can reach. That is why RESERVED exists as well: not to protect
the site, which the routing already does, but to stop somebody choosing a name
that will quietly never work.
"""
from __future__ import annotations
import json
from urllib.parse import urlparse
from flask import (Blueprint, abort, flash, g, redirect, render_template,
request, send_from_directory, url_for)
from . import uploads
from .db import get_db
from .render import to_html
from .security import login_required
# The page itself, at the root of the public site.
public_bp = Blueprint("profiles_public", __name__)
# Editing it, inside /comunidad/.
bp = Blueprint("profiles", __name__)
BIO_MAX = 2_000
LINKS_MAX = 8
# Names that Hugo already uses, or plausibly will. The routing makes a
# collision harmless rather than dangerous — Hugo wins and the profile is
# simply unreachable — so this exists to stop somebody discovering months later
# that their page has never loaded for anybody.
RESERVED = {
"de", "pt-br", "es", "en", # language trees
"page", "post", "posts", "categories", "tags", "category", "tag",
"admin", "uploads", "comunidad", "static", "assets",
"css", "js", "img", "images", "fonts", "media",
"index", "sitemap", "robots", "feed", "rss", "atom", "404", "llms",
"api", "search", "login", "logout", "register", "signup",
}
def name_is_available(login: str) -> bool:
return login.lower() not in RESERVED
def clean_links(raw: str) -> list[dict]:
"""One `label|url` per line, keeping only what is safe to render.
The scheme check is the point. An `href` beginning `javascript:` is a
script running on vienalatina.com, published by whoever typed it, so
anything that is not http or https is dropped rather than shown.
"""
links = []
for line in raw.splitlines():
line = line.strip()
if not line:
continue
label, _, url = line.partition("|")
label, url = label.strip()[:60], url.strip()
if not url:
label, url = "", label
if urlparse(url).scheme not in ("http", "https"):
continue
links.append({"label": label or url, "url": url[:500]})
if len(links) >= LINKS_MAX:
break
return links
def _published(login: str):
return get_db().execute(
"""SELECT * FROM members
WHERE gitea_login = ? COLLATE NOCASE
AND profile_published = 1 AND active = 1
AND role != 'tombstone'""",
(login,),
).fetchone()
# --- the public page ------------------------------------------------------
@public_bp.route("/<name>")
@public_bp.route("/<name>/")
def show(name: str):
"""404 for anything that is not a published profile.
Caddy turns that 404 into the site's own 404 page, so an unknown name
reaching here looks to a visitor exactly like any other missing page —
which also means an unpublished profile is indistinguishable from a member
who does not exist.
"""
member = _published(name)
if member is None:
abort(404)
try:
links = json.loads(member["links"] or "[]")
except ValueError:
links = []
return render_template(
"profile.html", member=member, links=links,
bio_html=to_html(member["bio"] or ""),
photo=(url_for("profiles.photo", stored_name=member["photo_name"])
if member["photo_name"] else None),
)
@bp.route("/foto/<stored_name>")
def photo(stored_name: str):
"""Deliberately public, unlike /comunidad/media/<name>.
A profile photo is part of a page anyone can read, so it cannot sit behind
the login. It is still tied to a published profile: unpublishing the page
takes the picture down with it rather than leaving it reachable to anybody
who noted the URL.
"""
if not uploads.STORED_NAME.match(stored_name):
abort(404)
row = get_db().execute(
"""SELECT 1 FROM members
WHERE photo_name = ? AND profile_published = 1 AND active = 1""",
(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"])
@login_required
def edit():
db = get_db()
if request.method == "GET":
try:
links = json.loads(g.member["links"] or "[]")
except ValueError:
links = []
return render_template(
"profile_edit.html",
links_text="\n".join(f"{item['label']}|{item['url']}" for item in links),
available=name_is_available(g.member["gitea_login"]),
address=url_for("profiles_public.show", name=g.member["gitea_login"]),
)
bio = request.form.get("bio", "").strip()[:BIO_MAX]
links = clean_links(request.form.get("links", ""))
published = 1 if request.form.get("published") == "on" else 0
photo_name = g.member["photo_name"]
try:
staged = uploads.stage(request.files.getlist("photo"))
except uploads.RejectedUpload as exc:
flash(str(exc), "error")
return redirect(url_for("profiles.edit"))
if staged:
# Saved with no parent id: a profile photo hangs off the member row,
# not off a thread or a message, so it is written to disk here and the
# filename is kept on the member.
item = staged[0]
uploads.directory().joinpath(item["stored_name"]).write_bytes(item["data"])
if photo_name:
uploads.remove(photo_name)
photo_name = item["stored_name"]
db.execute(
"""UPDATE members
SET bio = ?, links = ?, profile_published = ?, photo_name = ?
WHERE id = ?""",
(bio, json.dumps(links, ensure_ascii=False), published, photo_name,
g.member["id"]),
)
flash("Perfil guardado." if published else "Perfil guardado y sin publicar.",
"ok")
return redirect(url_for("profiles.edit"))