Merge branch 'claude/relaxed-faraday-h4zd09' of https://github.com/pablovolenski/vienalatina

This commit is contained in:
admin 2026-09-29 13:59:07 +00:00
commit e5b312b323
11 changed files with 652 additions and 3 deletions

View File

@ -94,13 +94,18 @@ def create_app(overrides: dict | None = None) -> Flask:
# restart, which is a confusing way to find out the variable is unset. # restart, which is a confusing way to find out the variable is unset.
raise RuntimeError("BOARD_SECRET_KEY is required (generate one with `openssl rand -hex 32`).") raise RuntimeError("BOARD_SECRET_KEY is required (generate one with `openssl rand -hex 32`).")
from . import auth, board, content, members, messages, uploads from . import auth, board, content, members, messages, profiles, uploads
app.register_blueprint(auth.bp, url_prefix=URL_PREFIX) app.register_blueprint(auth.bp, url_prefix=URL_PREFIX)
app.register_blueprint(members.bp, url_prefix=URL_PREFIX) app.register_blueprint(members.bp, url_prefix=URL_PREFIX)
app.register_blueprint(content.bp, url_prefix=URL_PREFIX) app.register_blueprint(content.bp, url_prefix=URL_PREFIX)
app.register_blueprint(uploads.bp, url_prefix=URL_PREFIX) app.register_blueprint(uploads.bp, url_prefix=URL_PREFIX)
app.register_blueprint(messages.bp, url_prefix=URL_PREFIX) app.register_blueprint(messages.bp, url_prefix=URL_PREFIX)
app.register_blueprint(board.bp, url_prefix=URL_PREFIX) app.register_blueprint(board.bp, url_prefix=URL_PREFIX)
app.register_blueprint(profiles.bp, url_prefix=URL_PREFIX)
# No prefix: a public profile lives at the top level of the
# site. Caddy only forwards a single-segment path that Hugo
# has not built, so this never competes with the static site.
app.register_blueprint(profiles.public_bp)
app.teardown_appcontext(close_db) app.teardown_appcontext(close_db)
app.jinja_env.globals["csrf_token"] = csrf_token app.jinja_env.globals["csrf_token"] = csrf_token

View File

@ -21,7 +21,7 @@ import sqlite3
from flask import (Blueprint, Response, abort, current_app, flash, g, redirect, from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
render_template, request, url_for) render_template, request, url_for)
from . import auth, invites, mail, uploads from . import auth, invites, mail, profiles, uploads
from .db import TOMBSTONE_LOGIN, get_db from .db import TOMBSTONE_LOGIN, get_db
from .security import admin_required, login_required, owner_required from .security import admin_required, login_required, owner_required
@ -127,7 +127,10 @@ def erase_member(db: sqlite3.Connection, member_id: int) -> list[str]:
try: try:
# Read before deleting: once the conversations are gone there is # Read before deleting: once the conversations are gone there is
# nothing left to work out which files they carried. # nothing left to work out which files they carried.
orphaned = [row["stored_name"] for row in db.execute( photo = db.execute("SELECT photo_name FROM members WHERE id = ?",
(member_id,)).fetchone()
orphaned = [photo["photo_name"]] if photo and photo["photo_name"] else []
orphaned += [row["stored_name"] for row in db.execute(
f"""SELECT a.stored_name FROM attachments a f"""SELECT a.stored_name FROM attachments a
JOIN messages m ON m.id = a.message_id JOIN messages m ON m.id = a.message_id
WHERE m.conversation_id IN ({_conversations_of(member_id)})""", WHERE m.conversation_id IN ({_conversations_of(member_id)})""",
@ -210,6 +213,13 @@ def new():
if not LOGIN_RE.match(login): if not LOGIN_RE.match(login):
flash("El usuario solo puede tener letras, números, punto, guion y guion bajo.", "error") flash("El usuario solo puede tener letras, números, punto, guion y guion bajo.", "error")
return redirect(url_for("members.new")) return redirect(url_for("members.new"))
if not profiles.name_is_available(login):
# The name would collide with a path the site already serves. The
# routing gives the static site every collision, so nothing breaks —
# their public page would simply never load. Refused here so nobody
# finds that out months later.
flash(f"«{login}» coincide con una dirección del sitio. Elige otro.", "error")
return redirect(url_for("members.new"))
if "@" not in email: if "@" not in email:
# Required now, not optional: the address is how the invitation gets # Required now, not optional: the address is how the invitation gets
# there, and a member with no way to set a password is a row that can # there, and a member with no way to set a password is a row that can

View File

@ -104,11 +104,30 @@ def _members_own_their_passwords(db: sqlite3.Connection) -> None:
db.execute("DROP TABLE IF EXISTS gitea_tokens") db.execute("DROP TABLE IF EXISTS gitea_tokens")
def _members_get_a_public_page(db: sqlite3.Connection) -> None:
"""Columns for the profile at vienalatina.com/<name>.
Plain ADD COLUMNs. `profile_published` carries a default so the existing
rows are valid the moment it appears — and the default is 0, so nobody
wakes up with a public page they did not ask for.
"""
existing = _columns(db, "members")
for column, definition in (
("profile_published", "INTEGER NOT NULL DEFAULT 0"),
("bio", "TEXT"),
("links", "TEXT"),
("photo_name", "TEXT"),
):
if column not in existing:
db.execute(f"ALTER TABLE members ADD COLUMN {column} {definition}")
# (number, description, function). The number is the value written to # (number, description, function). The number is the value written to
# user_version once the step succeeds. # user_version once the step succeeds.
STEPS = [ STEPS = [
(1, "attachments can belong to a private message", _attachments_accept_messages), (1, "attachments can belong to a private message", _attachments_accept_messages),
(2, "members keep their own password", _members_own_their_passwords), (2, "members keep their own password", _members_own_their_passwords),
(3, "members can have a public page", _members_get_a_public_page),
] ]

188
apps/board/profiles.py Normal file
View File

@ -0,0 +1,188 @@
"""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 IN ('owner', 'admin', 'user')""",
(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"))

View File

@ -13,6 +13,13 @@ CREATE TABLE IF NOT EXISTS members (
display_name TEXT NOT NULL DEFAULT '', display_name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '', email TEXT NOT NULL DEFAULT '',
password_hash TEXT, password_hash TEXT,
-- Public profile at vienalatina.com/<gitea_login>. Opt-in: a member has no
-- page until they publish one, because "public" should be something somebody
-- did on purpose rather than a consequence of being added to a board.
profile_published INTEGER NOT NULL DEFAULT 0 CHECK (profile_published IN (0, 1)),
bio TEXT,
links TEXT, -- JSON array of {label, url}
photo_name TEXT,
role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')), role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')),
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)), active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
created_at TEXT NOT NULL DEFAULT (datetime('now')), created_at TEXT NOT NULL DEFAULT (datetime('now')),

View File

@ -36,6 +36,7 @@
The badge is only drawn when there is something to see. #} The badge is only drawn when there is something to see. #}
<a href="{{ url_for('messages.inbox') }}">Privados{% set pending = unread_private() %}{% if pending %} <span class="tag">{{ pending }}</span>{% endif %}</a> <a href="{{ url_for('messages.inbox') }}">Privados{% set pending = unread_private() %}{% if pending %} <span class="tag">{{ pending }}</span>{% endif %}</a>
</li> </li>
<li><a href="{{ url_for('profiles.edit') }}">Mi perfil</a></li>
<li><a href="{{ url_for('content.index') }}">Contenido</a></li> <li><a href="{{ url_for('content.index') }}">Contenido</a></li>
{% endif %} {% endif %}
<li><a href="{{ url_for('members.index') }}">Miembros</a></li> <li><a href="{{ url_for('members.index') }}">Miembros</a></li>

View File

@ -0,0 +1,67 @@
{# A page on the PUBLIC site, so it does not extend base.html — that is the
members-area chrome, with its navigation and its "Área privada" footer.
The colours are repeated here rather than shared. Hugo fingerprints its
stylesheet, so the app cannot link to it and get a stable URL; this is the
same problem the Gitea theme has. Source of truth is
themes/vienalatina/assets/css/main.css — if the brand changes there, change
it here too. A deliberate duplicate, said out loud. #}
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ member.display_name }} — Viena Latina</title>
<meta name="description" content="{{ (member.bio or '')[:150] }}">
<style>
:root { --brand:#c0391c; --ink:#2b2320; --muted:#6b5f59;
--surface:#fffaf6; --line:#e7dcd4; --radius:12px; }
* { box-sizing:border-box; }
body { margin:0; background:var(--surface); color:var(--ink);
font:1rem/1.65 system-ui,-apple-system,"Segoe UI",sans-serif; }
.wrap { max-width:42rem; margin:0 auto; padding:2.5rem 1rem 4rem; }
a { color:var(--brand); }
.home { display:inline-block; margin-bottom:2rem; font-size:.9rem;
text-decoration:none; }
.head { display:flex; gap:1.25rem; align-items:center; flex-wrap:wrap; }
.photo { width:104px; height:104px; border-radius:50%; object-fit:cover;
border:1px solid var(--line); }
h1 { margin:0; font-size:1.7rem; line-height:1.2; }
.bio { margin-top:1.75rem; }
.bio :first-child { margin-top:0; }
.bio img { max-width:100%; height:auto; border-radius:var(--radius); }
ul.links { list-style:none; padding:0; margin:1.75rem 0 0;
display:flex; flex-wrap:wrap; gap:.5rem; }
ul.links a { display:inline-block; padding:.4rem .8rem; background:#fff;
border:1px solid var(--line); border-radius:999px;
text-decoration:none; font-size:.9rem; }
footer { margin-top:3rem; padding-top:1.25rem; border-top:1px solid var(--line);
color:var(--muted); font-size:.85rem; }
</style>
</head>
<body>
<div class="wrap">
<a class="home" href="/">← Viena Latina</a>
<div class="head">
{% if photo %}<img class="photo" src="{{ photo }}" alt="{{ member.display_name }}">{% endif %}
<h1>{{ member.display_name }}</h1>
</div>
{% if member.bio %}<div class="bio">{{ bio_html }}</div>{% endif %}
{% if links %}
<ul class="links">
{# nofollow + noopener: these are addresses somebody typed into a form,
and the page they point at should gain neither our ranking nor a
handle on the window it was opened from. #}
{% for link in links %}
<li><a href="{{ link.url }}" rel="nofollow noopener">{{ link.label }}</a></li>
{% endfor %}
</ul>
{% endif %}
<footer>Miembro de <a href="/">Viena Latina</a>.</footer>
</div>
</body>
</html>

View File

@ -0,0 +1,57 @@
{% extends "base.html" %}
{% block title %}Mi perfil{% endblock %}
{% block main %}
<form class="card" method="post" enctype="multipart/form-data"
action="{{ url_for('profiles.edit') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<h1>Mi perfil público</h1>
{% if not available %}
{# The routing gives the static site every collision, so this page would
simply never load. Better said here than discovered by a friend who
cannot open the link. #}
<p class="flash flash--error">
Tu usuario coincide con una dirección que ya usa el sitio, así que tu
página no se podría abrir. Pide a un administrador que te cambie el
nombre de usuario.
</p>
{% endif %}
<label for="bio">Sobre ti</label>
<textarea id="bio" name="bio" rows="8"
placeholder="Se puede usar Markdown.">{{ g.member.bio or '' }}</textarea>
<label for="links">Enlaces</label>
<textarea id="links" name="links" rows="5"
placeholder="Instagram|https://instagram.com/tu-cuenta">{{ links_text }}</textarea>
<p class="muted small">
Uno por línea, con el formato <span class="mono">Nombre|dirección</span>.
Sólo direcciones que empiecen por http:// o https://.
</p>
<label for="photo">Foto</label>
<input id="photo" name="photo" type="file" accept="image/*">
{% if g.member.photo_name %}
<p class="muted small">Ya tienes una. Subir otra la reemplaza.</p>
{% endif %}
<label class="check">
<input type="checkbox" name="published" {{ 'checked' if g.member.profile_published }}>
Publicar mi página
</label>
<p class="muted small">
Mientras esté publicada, cualquiera puede verla en
<span class="mono">vienalatina.com{{ address }}</span> y los buscadores
pueden indexarla. Puedes dejar de publicarla cuando quieras: la página y
la foto desaparecen en el momento.
</p>
<div class="actions">
<button class="btn" type="submit">Guardar</button>
{% if g.member.profile_published %}
<a class="linkish" href="{{ address }}">Ver mi página</a>
{% endif %}
</div>
</form>
{% endblock %}

View File

@ -0,0 +1,217 @@
"""Public pages at vienalatina.com/su-nombre.
Two things are being defended. One is the member: their page appears only
because they published it, and disappears the moment they stop.
The other is the public site, which shares this namespace. That defence lives
in the Caddyfile and cannot be tested from here — what can be tested is the
half that backs it up, which is that a name colliding with the site is refused
before anybody relies on it.
"""
from __future__ import annotations
import io
import json
from pathlib import Path
import pytest
from apps.board import profiles
PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
@pytest.fixture
def published(db, make_member):
def _published(login="maria", **columns):
member_id = make_member(login)
columns.setdefault("profile_published", 1)
columns.setdefault("bio", "Vivo en Viena desde 2019.")
sets = ", ".join(f"{name} = ?" for name in columns)
db.execute(f"UPDATE members SET {sets} WHERE id = ?",
(*columns.values(), member_id))
return member_id
return _published
# --- what the public sees -------------------------------------------------
def test_a_published_profile_is_public(client, published):
published()
page = client.get("/maria")
assert page.status_code == 200
body = page.get_data(as_text=True)
assert "Maria" in body and "Vivo en Viena desde 2019." in body
def test_an_unpublished_profile_is_not(client, published):
published(profile_published=0)
assert client.get("/maria").status_code == 404
def test_an_unknown_name_and_an_unpublished_one_look_the_same(client, published):
"""Both 404, so a visitor cannot tell a member who has not published from
somebody who was never here. Caddy turns either into the site's own 404."""
published(profile_published=0)
assert client.get("/maria").status_code == client.get("/nadie").status_code == 404
def test_a_suspended_member_has_no_page(client, db, published):
member_id = published()
db.execute("UPDATE members SET active = 0 WHERE id = ?", (member_id,))
assert client.get("/maria").status_code == 404
def test_the_page_does_not_wear_the_members_area_chrome(client, published):
"""It is a page on the public site. Rendering it inside the private
navigation would put "Área privada" and a Salir button on something
anybody can read."""
published()
body = client.get("/maria").get_data(as_text=True)
assert "Área privada" not in body
assert "Salir" not in body
# --- links, which is where a public page gets dangerous -------------------
@pytest.mark.parametrize("url", [
"javascript:alert(1)",
"data:text/html,<script>alert(1)</script>",
"vbscript:msgbox(1)",
" javascript:alert(1)",
])
def test_a_script_link_is_dropped(url):
"""An href beginning javascript: is a script running on vienalatina.com,
published by whoever typed it into the form."""
assert profiles.clean_links(f"Malo|{url}") == []
def test_ordinary_links_survive():
links = profiles.clean_links(
"Instagram|https://instagram.com/maria\nhttp://ejemplo.com\n\n")
assert links == [
{"label": "Instagram", "url": "https://instagram.com/maria"},
{"label": "http://ejemplo.com", "url": "http://ejemplo.com"},
]
def test_the_number_of_links_is_capped():
many = "\n".join(f"Uno|https://ejemplo.com/{n}" for n in range(50))
assert len(profiles.clean_links(many)) == profiles.LINKS_MAX
def test_links_are_rendered_without_passing_on_our_ranking(client, db, published):
published(links=json.dumps([{"label": "Web", "url": "https://ejemplo.com"}]))
body = client.get("/maria").get_data(as_text=True)
assert 'rel="nofollow noopener"' in body
def test_the_bio_cannot_smuggle_html(client, published):
"""Same markdown renderer as the board, where html=False is the whole
defence — worth asserting on the one page that is public."""
published(bio="<script>alert(1)</script> y **negrita**")
body = client.get("/maria").get_data(as_text=True)
assert "<script>alert(1)</script>" not in body
assert "<strong>negrita</strong>" in body
# --- names that would never work ------------------------------------------
@pytest.mark.parametrize("name", ["de", "pt-br", "categories", "admin",
"comunidad", "robots", "DE"])
def test_a_name_the_site_already_uses_is_refused(client, db, post, owner_id,
sign_in, name, monkeypatch):
"""Not because it would break the site — Caddy gives the static site every
collision — but because their page would never load and nobody would know
why."""
monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None)
sign_in(owner_id)
post("/comunidad/miembros/nuevo", {
"login": name, "display_name": "X", "email": "x@example.com", "role": "user",
})
assert db.execute("SELECT 1 FROM members WHERE gitea_login = ? COLLATE NOCASE",
(name,)).fetchone() is None
# --- the photo, which is public and must stop being public ----------------
def test_the_photo_is_public_while_the_page_is(app, client, db, post, make_member,
sign_in, published):
member_id = published()
sign_in(member_id)
post("/comunidad/mi-perfil", {"published": "on", "bio": "Hola",
"photo": (io.BytesIO(PNG), "yo.png")},
content_type="multipart/form-data")
name = db.execute("SELECT photo_name FROM members WHERE id = ?",
(member_id,)).fetchone()["photo_name"]
assert name
with client.session_transaction() as session:
session.clear() # a stranger, not signed in
assert client.get(f"/comunidad/foto/{name}").status_code == 200
def test_unpublishing_takes_the_photo_down_too(app, client, db, post, sign_in,
published):
member_id = published()
sign_in(member_id)
post("/comunidad/mi-perfil", {"published": "on", "bio": "Hola",
"photo": (io.BytesIO(PNG), "yo.png")},
content_type="multipart/form-data")
name = db.execute("SELECT photo_name FROM members WHERE id = ?",
(member_id,)).fetchone()["photo_name"]
post("/comunidad/mi-perfil", {"bio": "Hola"}) # checkbox unticked
assert client.get("/maria").status_code == 404
assert client.get(f"/comunidad/foto/{name}").status_code == 404
def test_a_board_picture_cannot_be_served_as_a_profile_photo(
app, client, db, post, make_member, sign_in):
"""The profile photo route is public, so it must only ever serve a file
that a published profile points at — never anything else in the same
directory, which is where the private board images live."""
member = make_member("maria")
sign_in(member)
post("/comunidad/nuevo", {"title": "Privado", "body": "Texto",
"pictures": (io.BytesIO(PNG), "foto.png")},
content_type="multipart/form-data")
name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"]
with client.session_transaction() as session:
session.clear()
assert client.get(f"/comunidad/foto/{name}").status_code == 404
def test_erasing_a_member_takes_the_photo_off_disk(
app, client, db, post, owner_id, sign_in, published):
member_id = published()
sign_in(member_id)
post("/comunidad/mi-perfil", {"published": "on", "bio": "Hola",
"photo": (io.BytesIO(PNG), "yo.png")},
content_type="multipart/form-data")
name = db.execute("SELECT photo_name FROM members WHERE id = ?",
(member_id,)).fetchone()["photo_name"]
assert (Path(app.config["UPLOAD_DIR"]) / name).exists()
sign_in(owner_id)
post(f"/comunidad/miembros/{member_id}/eliminar")
assert not (Path(app.config["UPLOAD_DIR"]) / name).exists()
# --- publishing is a decision ---------------------------------------------
def test_a_new_member_has_no_page(client, make_member):
make_member("nueva")
assert client.get("/nueva").status_code == 404
def test_the_form_says_what_publishing_means(client, make_member, sign_in):
sign_in(make_member("maria"))
body = client.get("/comunidad/mi-perfil").get_data(as_text=True)
assert "cualquiera puede verla" in body
assert "buscadores" in body

View File

@ -655,6 +655,51 @@ the one case it was never needed for.
the proof the rebuild kept real rows. Back up first — `scripts/backup-board.sh` the proof the rebuild kept real rows. Back up first — `scripts/backup-board.sh`
— as with any migration. — as with any migration.
### 11.13 Public profiles at `vienalatina.com/su-nombre`
A member fills in *Mi perfil* and ticks *Publicar mi página*. Until they do,
there is no page: `profile_published` starts at 0 and an unpublished profile
404s exactly like a name that was never a member.
**The routing is the part to understand before changing anything.** A profile
sits at the top level, sharing a namespace with the whole static site. Caddy
forwards a request to the app only when all three hold:
- the path is **one segment** — `/page/acerca/` never reaches the app
- it is not `/comunidad`
- **Hugo has built nothing there** (`not file` with `try_files`)
That last one is what makes it safe, and why there is no reserved-path list in
the Caddyfile: the question is answered by the filesystem, so it stays correct
when the site grows a page nobody remembered. A member called `de` shadows
nothing — `/de/` is a real directory, so it is served, and their profile is
merely unreachable. The app refuses such names at sign-up for that reason.
An unknown name 404s from the app, and `handle_response` turns that into the
site's own `404.html`, so a visitor never sees the members area's error page.
**After reloading Caddy, check the public site first**, before looking at any
profile:
```sh
sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy
for path in / /de/ /pt-br/ /page/acerca/ /categories/ /robots.txt /comunidad/ /noexiste; do
printf '%-20s %s\n' "$path" "$(curl -s -o /dev/null -w '%{http_code}' https://vienalatina.com$path)"
done
```
Everything but the last should be 200 (or 301). `/noexiste` should be 404 and
should look like the site's own 404 page. A routing change that shadows the
public site is worse than having no profiles, so if anything there is wrong,
revert the Caddyfile and reload before investigating.
**The profile page repeats the brand colours** instead of sharing them. Hugo
fingerprints its stylesheet, so the app cannot link to it with a stable URL —
the same problem the Gitea theme has. If the colours change in
`themes/vienalatina/assets/css/main.css`, change them in
`apps/board/templates/profile.html` too.
## 12. Make Gitea look like the site ## 12. Make Gitea look like the site
Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its

View File

@ -37,6 +37,39 @@ vienalatina.com {
@board path /comunidad /comunidad/* @board path /comunidad /comunidad/*
reverse_proxy @board 127.0.0.1:8080 reverse_proxy @board 127.0.0.1:8080
# Public profiles at vienalatina.com/su-nombre.
#
# This shares a namespace with the entire static site, so the rule is that
# the static site always wins — decided by asking the disk, not by keeping
# a list of reserved paths that would be wrong the first time Hugo grows
# one. Three conditions, each load-bearing:
#
# path_regexp one segment only, so /page/acerca/ never comes here
# not path /comunidad is the members area, matched above
# not file if Hugo built anything at this path, Hugo serves it
#
# A member called "de" therefore shadows nothing: /de/ is a real directory,
# so it is served, and their profile is simply unreachable. The app refuses
# such names at sign-up for that reason, but the site is safe either way.
#
# handle_response turns the app's 404 for an unknown name into the site's
# own 404 page, so a visitor sees the public site's error, not the members
# area's, and the app never needs a public-facing error template.
@profile {
path_regexp ^/([A-Za-z0-9][A-Za-z0-9._-]{0,38})/?$
not path /comunidad /comunidad/*
not file {
try_files {path} {path}/index.html
}
}
reverse_proxy @profile 127.0.0.1:8080 {
@nobody status 404
handle_response @nobody {
rewrite * /404.html
file_server
}
}
# llms.txt is markdown (matches the old WP behaviour) # llms.txt is markdown (matches the old WP behaviour)
header /llms.txt Content-Type "text/markdown; charset=utf-8" header /llms.txt Content-Type "text/markdown; charset=utf-8"