Compare commits

...

14 Commits

Author SHA1 Message Date
028b7f3269 Merge branch 'main' of https://git.vienalatina.com/pablo/vienalatina
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2026-10-03 09:07:33 +00:00
2f79b0da9d Merge branch 'claude/relaxed-faraday-h4zd09' of https://github.com/pablovolenski/vienalatina 2026-10-03 08:40:36 +00:00
Claude
c84a996eef
The bar, the share card, the writing box and subpages
**A signed-in member sees the members area from anywhere.** A slim bar above the
public header, with the same five sections /comunidad/ has. Those pages are
files on disk and get cached, so it is drawn in the browser: memberbar.js asks
/comunidad/sesion.json who is reading, and that endpoint is the only thing that
decides — a visitor is told `{"signed_in": false}` and the answer is never
cached. Sign-in also sets vl_sesion=1, a cookie holding one digit that scripts
can read, and without it the script makes no request at all: a stranger reading
one article costs the app nothing. It is a hint, never a credential — the
session cookie stays HttpOnly and signed, and a forged hint earns a reply saying
you are not signed in. Comunidad is now in the public menu in all three
languages, signed in or not.

**The public menu is built from the pages.** It was three names per language in
config.yaml, so a page published through Contenido never appeared on the site at
all and the German and Portuguese menus had to be kept in step by hand. Pages
carry `parent` (another page's basename — the one translate.py already uses to
pair siblings, so it holds in all three languages) and `weight`, both chosen in
the editor, and header.html builds two levels from them. URLs do not change: a
subpage is still /page/<slug>/, only the menu nests, so nothing in the Caddyfile
or the pipeline learns about folders. The dropdown is the theme's own, ported
from WordPress — hover, focus-within, inline on a phone, no script. A parent that
has been deleted is kept and labelled rather than silently dropped on the next
save.

**Sharing and the rest of SEO/GEO.** The groundwork was already here — hreflang,
Open Graph, Twitter card, BlogPosting, llms.txt, robots.txt naming the AI
crawlers — so this closes the gaps. Static pages had *none* of it and shared as
bare links; they now carry WebPage schema and the full set of tags. Both branches
gain og:image with an alt and a twitter:image, falling back to params.defaultImage
(empty until there is a logo, which is the one line to fill in then). The home
page gains Organization with areaServed Wien and a sameAs list; posts and pages
gain BreadcrumbList, and an article's structured data now carries the author's
profile URL. An optional FAQ — `pregunta|respuesta` per line — renders at the
foot of the page and as FAQPage schema, because current guidance for generative
engines puts exactly that shape at the top of what gets quoted, and schema
describing something invisible is what search engines penalise. translate.py
carries both new fields: image_alt joins the translated keys, and faq is
translated half by half so the separator survives.

**The writing boxes.** A markdown toolbar and a Vista previa on every box where
somebody writes prose, opted in with data-markdown. The preview POSTs to
/comunidad/previsualizar and renders with render.to_html — the same function the
board and the site use, so it cannot promise something publishing will not
deliver; a markdown parser in the browser would be a second opinion about what
somebody's text means. Choosing a picture now shows a thumbnail with its name and
size before anything is uploaded, which is the only reason `blob:` joins img-src:
a handle to bytes already in the page, reaching no network.

All of it ours, no dependency added, under a policy that loads scripts from this
origin only. Verified by building the site with Hugo 0.135, the version the
pipeline runs: the nested menu, the page's share tags, the FAQ schema matching
the rendered section, and llms.txt listing the pages.

463 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-10-02 15:21:35 +00:00
62904a8c35 Merge branch 'claude/relaxed-faraday-h4zd09' of https://github.com/pablovolenski/vienalatina 2026-10-02 13:19:39 +00:00
Claude
e52c1e4d49
A byline, a way in, and the cell that was not a cell
Three things from a round of looking at the deployed site.

**The staggered table rows.** content_list.html had `<td class="actions
actions--row">`, and `.actions` is display:flex. A <td> told to be a flex
container stops being a table cell: it leaves the row's layout and draws its
bottom border at its own content height, so the columns' rules no longer meet.
Nothing errors and the page renders, which is how it survived two rounds of
somebody looking straight at it — including mine, when I blamed the wrapping on
the Miembros table and rebuilt that page as cards. The flex row moves into a
<div> inside the cell, and test_templates.py now fails on any <td> carrying the
class, beside the guards for the things the CSP silently drops.

**A published post did not say who wrote it.** The commit has named the author
since the editor was built; the page never did, so a reader could not tell whose
article it was. frontmatter_for writes `author`, and `author_url` only when that
member has published their own page — a byline linking to a 404 is worse than
one that does not link. publish() fills it from whoever wrote the thing, which
for an approved proposal is the member and not the moderator; edit() deliberately
does not, so fixing a typo in somebody's article never re-signs it. The hidden
field carrying the URL back is checked against a path on this site, because a
hidden field is a convention and not a promise.

scripts/translate.py needed no change, which I checked rather than assumed: it
copies the whole frontmatter and translates only the title and description, so
an author reaches the German and Portuguese siblings untranslated, as a name
should. The theme's single.html renders it, verified by building the site with
Hugo 0.135 — `por <a href="/salvador">Salvador Dalí</a>` with the link, `por
Salvador Dalí` without.

**Contenido had no way in.** The page worked and nothing linked to it: Gestión
offered only the static pages, and the Artículos tab exists only once you are
already on that screen — so a moderator, who cannot open Gestión at all, had no
route to the published articles. Gestión gains an Artículos card, Publicaciones
gains *Ya publicado* beside its button, and the button that read "Nuevo página"
now reads "Nueva página", since Spanish gives the article a gender and
"Nuevo " + the singular cannot be right for both.

439 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-10-02 12:19:08 +00:00
157c2abb73 Merge branch 'claude/relaxed-faraday-h4zd09' of https://github.com/pablovolenski/vienalatina 2026-10-02 12:01:23 +00:00
Claude
cb034120e0
The deploy names what your .env has that nothing reads
A screenshot of /srv/board/.env showed the whole diagnosis at once: no
CONTENT_TOKEN line, so the app falls back to the admin token and Gitea answers
403 — and two live OAuth credentials for a login flow deleted two phases ago,
sitting there because the deploy never touches .env and never will.

So it names them. The check is the mirror of the one already there: settings in
.env that .env.example no longer documents, found with `comm -13` over the same
two sorted lists. A commented-out line in the example counts as undocumented,
which is how a setting is retired — comment it there, and the next deploy says
it is still on the server. Nothing is rewritten; deleting a line from a file
holding secrets is a decision, not a cleanup.

The "missing" warning also grew consequences. It has been listing CONTENT_TOKEN
as one bare name among several since it was added, which is easy to scroll past;
it now reads "CONTENT_TOKEN — el editor no puede publicar nada en el sitio",
sharing one note_for helper with the empty-value warning below it so the two
cannot drift.

And .env.example stops describing a job GITEA_ADMIN_TOKEN no longer has. It says
what is true now: members have no accounts on the git server, nothing in the
members area calls it, and it CANNOT publish, because Gitea's scopes are per
category and `admin` does not contain `repository`. That sentence is the one
that was missing while the editor sat unable to commit and looking configured.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-09-30 14:53:00 +00:00
Claude
28dd23e444
Publishing has never worked: one line, two wrong answers
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/<login>
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: /<name>/ redirects to /<name>, 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-09-30 14:39:14 +00:00
f507a057aa Merge branch 'claude/relaxed-faraday-h4zd09' of https://github.com/pablovolenski/vienalatina 2026-09-30 13:03:01 +00:00
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
34810efc23 Merge branch 'claude/relaxed-faraday-h4zd09' of https://github.com/pablovolenski/vienalatina 2026-09-29 14:16:46 +00:00
Claude
63dd19e451
Style the profile page, and drop the step before writing
Two bugs, both mine.

The profile page arrived unstyled because its CSS was in a <style>
block. default-src 'self' covers style-src, 'self' does not permit
inline, so the browser dropped the whole block without a word — the
photo loaded because img-src allows same-origin, which is what made the
screenshot look like a half-working page rather than a blocked one. The
third time this policy has silently made something inert, after two
rounds of inline event handlers. Moved to static/profile.css, where the
policy allows it, and test_templates.py now fails on an inline <style>
the way it already does on an inline onclick.

Private messages had an "Abrir conversación" button that created an
empty conversation and sent you to a page where you then had to type. It
bought nothing and littered the inbox with rows reading "Sin mensajes
todavía" for people nobody had written to. A conversation is now
addressed by the person — /privados/con/<member_id> — and the page
always carries the history and the box together. The row is created by
the first message, not by looking at somebody's name.

That also makes the access rule structural instead of checked. Every
lookup is scoped to the member doing the looking, so there is no query
that could return somebody else's correspondence, and the two helpers
that took a conversation id are gone. A third person opening the same
URL now sees their own empty conversation, which the tests assert
directly rather than asserting a 404.

281 tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-09-29 14:16:25 +00:00
e5b312b323 Merge branch 'claude/relaxed-faraday-h4zd09' of https://github.com/pablovolenski/vienalatina 2026-09-29 13:59:07 +00:00
Claude
6acc8922b1
Phase D: public profiles, without risking the public site
A member fills in a bio, links and a photo, ticks a box, and has a page at
vienalatina.com/su-nombre. Until they tick it there is no page, and an
unpublished profile 404s exactly like a name that was never a member.

The routing was the dangerous part and it is not solved by a list. The
original plan reserved Hugo's paths in the Caddyfile, which is wrong the
first time the site grows one, and the failure is a member's page
silently shadowing part of vienalatina.com. Instead Caddy forwards a
request only when the path is a single segment, is not /comunidad, and
Hugo has built nothing there — `not file` with try_files. The static
site wins every collision because the filesystem answers the question,
so the rule cannot drift. A member called "de" shadows nothing; their
profile is merely unreachable, which is why such names are refused at
sign-up: to protect the member, not the site.

An unknown name 404s from the app and handle_response turns that into
the site's own 404.html, so the public site keeps its error page and the
app never needs a public-facing one. Both directives verified against
Caddy's documentation source, since caddyserver.com is unreachable here.

Links are the injection surface on a public page: anything whose scheme
is not http or https is dropped, which is asserted against javascript:,
data: and vbscript:, including a leading-space variant. They render with
rel="nofollow noopener".

The photo is public, which the existing upload code deliberately is not,
so it gets its own route that serves a file only while a published
profile points at it. Unpublishing takes the picture down with the page,
and a private board image cannot be fetched through it — both tested.

The page does not extend base.html: that is the members-area chrome, and
rendering a public page inside it would put "Área privada" and a Salir
button on something anybody can read. It repeats the brand colours
instead of sharing them, because Hugo fingerprints its stylesheet — a
deliberate duplicate, named as one, with the source of truth in a
comment.

Migration 3 adds the columns. 231 tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
2026-09-29 13:22:43 +00:00
63 changed files with 5759 additions and 446 deletions

View File

@ -145,37 +145,56 @@ runtime.
## Members area
`apps/board/` — a small Flask app at `/comunidad/`, behind Caddy, holding roles
and an internal message board. Signed-in members only.
`apps/board/` — a small Flask app at `/comunidad/`, behind Caddy. A member signs
in once and gets five sections: **Inicio** (a dashboard), **Muro** (the internal
board), **Privados** (messages between two members), **Publicaciones** (the
public site, through moderation) and, for admins, **Gestión**.
```
apps/board/
app.py factory, config, the CSRF and noindex hooks
auth.py Gitea OAuth2 (confidential client) and the membership gate
members.py roles, provisioning, ownership transfer, GDPR erasure/export
board.py threads and comments
content.py the editor — writes posts to Gitea's contents API
gitea.py the only module that talks to Gitea
tokens.py per-member access tokens, refreshed before they expire
render.py markdown with raw HTML disabled
schema.sql the tables, including the one-owner index
tests/ pytest, 97 checks — `python3 -m pytest apps/board/tests`
app.py factory, config, the CSRF and noindex hooks
auth.py the login form, passwords, the membership gate
passwords.py scrypt hashing and the failed-attempt limiter
members.py roles, onboarding, ownership transfer, GDPR erasure/export
home.py Inicio, and Gestión
board.py the wall: threads and comments
messages.py private messages, unread marks, blocking
submissions.py what members propose for the public site, and its moderation
content.py the editor — commits posts and pages through Gitea's API
profiles.py public pages at vienalatina.com/<name>
uploads.py pictures: sniffed, renamed, served behind the login
invites.py one-time links for invitations and password resets
gitea.py the only module that talks to Gitea
migrations.py numbered schema steps, keyed on PRAGMA user_version
render.py markdown with raw HTML disabled
schema.sql the tables, including the one-owner index
tests/ pytest — `python3 -m pytest apps/board/tests`
```
Three things about it are load-bearing and easy to undo by accident:
Four things about it are load-bearing and easy to undo by accident:
- **A Gitea account is not a membership.** Login succeeds only for an active row
in `members`. Drop that check and every account on the instance gets in,
starting with the translations bot.
- **The members area owns its own logins.** A password is a scrypt hash in
`members.password_hash`; a NULL hash cannot be signed in with, which is what
makes an invitation the only way in for a new member.
- **One owner, enforced by a partial unique index**, not by application code.
The owner cannot be suspended or demoted by anyone; stepping down means
transferring ownership to an admin.
- **A moderator curates content and has no power over people.** No creating,
suspending, promoting or erasing anybody — `may_create` and `may_manage` in
`members.py` are the whole rule, and they are tested as plain functions.
- **`html=False` in `render.py`** is the entire XSS defence, and it works
because markdown-it then emits only its own tags. Turning it on means owning a
sanitiser allowlist forever.
Admins can delete anyone's post; **nobody can edit anyone else's**, admins
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
@ -183,10 +202,16 @@ Its SQLite database is the only state on the server that git does not hold.
### Writing posts
`/comunidad/contenido/` replaces Decap CMS for admins: a form that commits a
file through Gitea's contents API, so Woodpecker sees an ordinary push and
translate → build → deploy runs unchanged. Commits carry the author's own
account, not a bot's.
`/comunidad/contenido/` replaces Decap CMS: a form that commits a file through
Gitea's contents API, so Woodpecker sees an ordinary push and translate → build →
deploy runs unchanged. Commits name the person who wrote the post, not a bot —
`write_file` sends an author per commit.
Moderators and admins write there directly. A member writes in
`/comunidad/publicaciones/` instead, and the proposal waits in SQLite until a
moderator approves it, which commits it through that same code under the
member's own name. Nothing a member writes reaches the repository before then,
because a commit to it *is* publication: the webhook starts the pipeline.
It exists because Decap has no supported way to be themed — its maintainer's
answer is override its CSS and accept that class names move, or fork it — so

View File

@ -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
@ -94,13 +94,21 @@ def create_app(overrides: dict | None = None) -> Flask:
# 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`).")
from . import auth, board, content, members, messages, uploads
from . import (auth, board, content, home, members, messages, profiles,
submissions, uploads)
app.register_blueprint(auth.bp, url_prefix=URL_PREFIX)
app.register_blueprint(home.bp, url_prefix=URL_PREFIX)
app.register_blueprint(submissions.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(uploads.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(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.jinja_env.globals["csrf_token"] = csrf_token
@ -111,10 +119,13 @@ def create_app(overrides: dict | None = None) -> Flask:
return {"current_year": datetime.now(timezone.utc).year}
@app.context_processor
def _unread():
# Lazily: base.html is rendered for signed-out pages and error pages
# too, and neither should run a query to draw a badge nobody sees.
return {"unread_private": messages.unread_count}
def _badges():
# Lazily, as functions: base.html is rendered for signed-out pages and
# error pages too, and neither should run a query to draw a badge
# nobody sees.
return {"unread_private": messages.unread_count,
"pending_review": submissions.pending_count,
"may_moderate": submissions.may_moderate}
@app.before_request
def _before():
@ -137,8 +148,13 @@ def create_app(overrides: dict | None = None) -> Flask:
# pointing at another site will not load — which for a private board is
# the right answer anyway, since an external image is a request that
# tells someone else who read the thread and when.
#
# `blob:` is in img-src for one thing only: the thumbnail of a picture
# somebody has just chosen and not yet uploaded. A blob URL is a handle
# to bytes already in this page; it reaches no network and cannot be
# pointed at another site.
response.headers["Content-Security-Policy"] = (
"default-src 'self'; img-src 'self' data:; frame-ancestors 'none'"
"default-src 'self'; img-src 'self' data: blob:; frame-ancestors 'none'"
)
return response
@ -162,5 +178,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

View File

@ -45,7 +45,7 @@ def load_member() -> None:
return
row = get_db().execute(
"""SELECT * FROM members
WHERE id = ? AND active = 1 AND role IN ('owner', 'admin', 'user')""",
WHERE id = ? AND active = 1 AND role != 'tombstone'""",
(member_id,),
).fetchone()
if row is None:
@ -54,22 +54,26 @@ 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("board.threads")
return target if target.startswith(prefix) else url_for("home.index")
@bp.route("/login", methods=["GET", "POST"])
def login():
if g.member is not None:
return redirect(url_for("board.threads"))
return redirect(url_for("home.index"))
target = request.values.get("next", "")
if request.method == "GET":
@ -98,7 +102,7 @@ def login():
member = get_db().execute(
"""SELECT * FROM members
WHERE (gitea_login = ? COLLATE NOCASE OR email = ? COLLATE NOCASE)
AND role IN ('owner', 'admin', 'user')""",
AND role != 'tombstone'""",
(identifier, identifier),
).fetchone()
@ -117,7 +121,40 @@ 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 remember_session(redirect(safe_next(target)))
# --- the hint the public site reads --------------------------------------
#
# The static pages on vienalatina.com are files on disk; nothing there knows who
# is looking. The members' bar is therefore drawn by a script that asks this app
# — and asking on every page view, for every stranger who ever lands on the
# site, to be told they are nobody, is a request per page for nothing.
#
# So sign-in also sets this: a second cookie holding the digit 1, readable by
# that script, saying only "somebody signed in on this browser once". Without it
# the script makes no request at all. It is a hint and never a credential: the
# real session cookie stays HttpOnly and signed, and `sesion.json` decides
# everything. Somebody who sets this by hand gets a bar that says they are not
# signed in.
SESSION_HINT = "vl_sesion"
def remember_session(response):
response.set_cookie(
SESSION_HINT, "1",
max_age=60 * 60 * 24 * 30,
secure=current_app.config["SESSION_COOKIE_SECURE"],
httponly=False, # the whole point: a script has to read it
samesite="Lax",
path="/", # including the static site, which is why it exists
)
return response
def forget_session(response):
response.delete_cookie(SESSION_HINT, path="/")
return response
def invite_url(token: str) -> str:
@ -176,7 +213,7 @@ def recover():
member = get_db().execute(
"""SELECT * FROM members
WHERE email = ? COLLATE NOCASE AND active = 1
AND role IN ('owner', 'admin', 'user')""",
AND role != 'tombstone'""",
(email,),
).fetchone()
@ -203,4 +240,4 @@ def logout():
"""
session.clear()
flash("Has cerrado sesión.", "ok")
return redirect(url_for("auth.login"))
return forget_session(redirect(url_for("auth.login")))

View File

@ -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,)
@ -93,12 +123,18 @@ def _comment_or_404(comment_id: int):
return row
@bp.route("/")
@bp.route("/muro")
@login_required
def threads():
"""The wall. It used to be the root of the members area, and `Inicio` is
there now: the first thing after signing in should say what has happened
everywhere, not drop somebody into one of the five places it could have
happened. Thread URLs are untouched, so nothing anyone has linked to moves.
"""
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
@ -110,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/<int:thread_id>")
@ -119,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"])
@ -260,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/<int:thread_id>/estado", methods=["POST"])
@admin_required
def set_state(thread_id: int):

View File

@ -33,7 +33,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect,
from . import gitea
from .db import get_db
from .render import to_html
from .security import admin_required
from .security import moderator_required
# One list of accepted formats for the whole app, kept in the module that
# knows what each one looks like on the wire, so the editor and the board
# cannot drift apart about what a picture is.
@ -41,14 +41,21 @@ from .uploads import IMAGE_EXTENSIONS
bp = Blueprint("content", __name__)
# `role` is the floor for writing in this collection, checked by
# _collection_or_404 rather than by a decorator, because the two collections in
# one blueprint do not share an answer: a moderator curates what the public
# reads, and the static pages of the site are not that — they are the site's own
# structure, and changing "Acerca de" is an administrator's job.
COLLECTIONS = {
"post": {
"label": "Artículos", "singular": "Artículo",
"folder": "content/post", "dated": True,
"label": "Artículos", "singular": "Artículo", "new_label": "Nuevo artículo",
"folder": "content/post", "dated": True, "role": "moderator",
},
"page": {
"label": "Páginas", "singular": "Página",
"folder": "content/page", "dated": False,
# `new_label` spelled out rather than "Nuevo " + the singular: Spanish
# gives the article a gender, and the button read "Nuevo página".
"label": "Páginas", "singular": "Página", "new_label": "Nueva página",
"folder": "content/page", "dated": False, "role": "admin",
},
}
@ -64,6 +71,15 @@ BODY_MAX = 100_000
# file in the repository — the pipeline and the Caddyfile included.
SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*\.es\.md$")
# A byline links to a profile on this site or to nothing. Same shape as a
# username, with the leading slash, so no form can turn an author link into a
# link somewhere else.
AUTHOR_URL = re.compile(r"^/[A-Za-z0-9][A-Za-z0-9._-]{0,38}$")
# A page's basename, as it appears in acerca.es.md — which is what another page
# names when it hangs under it.
PAGE_BASENAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$")
# --- the contract with translate.py --------------------------------------
@ -102,6 +118,17 @@ def frontmatter_for(collection: str, form: dict) -> dict:
fields["date"] = form["date"]
fields["lang"] = "es"
fields["manual_translation"] = form["manual_translation"]
if collection == "page":
# Only written when set, so a page that sits at the top of the menu has
# no `parent: ""` line for somebody to wonder about later.
if form.get("parent"):
fields["parent"] = form["parent"]
if form.get("weight"):
fields["weight"] = form["weight"]
if form.get("faq"):
fields["faq"] = form["faq"]
if form.get("image_alt"):
fields["image_alt"] = form["image_alt"]
if collection == "post":
if form["categories"]:
fields["categories"] = form["categories"]
@ -109,6 +136,19 @@ def frontmatter_for(collection: str, form: dict) -> dict:
fields["description"] = form["description"]
if form["image"]:
fields["image"] = form["image"]
# Who wrote it, for the page rather than for git. The commit has named
# the author since the editor was built; the article did not, so a
# reader could not tell whose it was or click through to them.
#
# `author_url` is only ever set when that member has published their
# page — a byline linking to a 404 is worse than a byline that does not
# link. translate.py copies both into the German and Portuguese
# siblings by itself: it carries the whole frontmatter and translates
# only title and description, and a name is not translated.
if form.get("author"):
fields["author"] = form["author"]
if form.get("author_url"):
fields["author_url"] = form["author_url"]
return fields
@ -166,9 +206,22 @@ def listing(collection: str) -> list[dict]:
# --- form handling -------------------------------------------------------
def _collection_or_404(collection: str) -> dict:
"""404 for a collection that does not exist, 403 for one this member may not
write to. Every route here calls it before doing anything else, which is
what makes the per-collection rule real rather than a note in a template."""
if collection not in COLLECTIONS:
abort(404)
return COLLECTIONS[collection]
meta = COLLECTIONS[collection]
if meta["role"] == "admin" and g.member["role"] not in ("owner", "admin"):
abort(403)
return meta
def visible_collections() -> dict:
"""The collections this member may write to, for the tabs. A tab that only
ever produces a 403 is worse than no tab."""
return {name: meta for name, meta in COLLECTIONS.items()
if meta["role"] != "admin" or g.member["role"] in ("owner", "admin")}
def _name_or_404(name: str) -> str:
@ -193,6 +246,36 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]:
errors.append("La fecha debe tener el formato AAAA-MM-DD.")
categories = [c for c in request.form.getlist("categories") if c in CATEGORIES]
# Carried through the form as hidden fields, the way the date and the image
# path are: they belong to the document being edited, not to whoever is
# editing it, so saving a correction must not re-sign the post. Checked on
# the way back in because a hidden field is only a convention — the URL has
# to be a path on this site and nothing else.
# A page's place in the menu. `parent` is another page's basename — the one
# translate.py uses to pair siblings, so a parent chosen once holds in all
# three languages — and the menu is built from these, not from a list in
# config.yaml that nobody remembers to edit.
parent = request.form.get("parent", "").strip()
if parent and not PAGE_BASENAME.match(parent):
parent = ""
try:
weight = max(0, min(999, int(request.form.get("weight", "") or 50)))
except ValueError:
weight = 50
# Questions and answers, one `pregunta|respuesta` per line — the same shape
# the profile links field uses, and parsed the same way: a line without a
# separator is dropped rather than published half-formed. They are rendered
# on the page and as FAQPage structured data, which is the shape an answer
# engine quotes most readily.
faq = clean_faq(request.form.get("faq", ""))
image_alt = request.form.get("image_alt", "").strip()[:200]
author = request.form.get("author", "").strip()[:80]
author_url = request.form.get("author_url", "").strip()
if author_url and not AUTHOR_URL.match(author_url):
author_url = ""
image = request.form.get("image", "").strip()
if image and not re.match(r"^/uploads/[A-Za-z0-9._-]+$", image):
errors.append("La imagen no es válida.")
@ -208,50 +291,133 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]:
"description": request.form.get("description", "").strip(),
"image": image,
"manual_translation": request.form.get("manual_translation") == "on",
"author": author, "author_url": author_url,
"parent": parent, "weight": weight,
"faq": faq, "image_alt": image_alt,
}
return fields, body, errors
def _upload_image() -> str:
"""Commit an uploaded picture and return the path the frontmatter uses.
def commit_picture(data: bytes, filename: str, author=None) -> str:
"""Commit a picture into the site repository and return the path the
frontmatter uses.
Deliberately a second commit rather than part of the post's. Gitea's
contents API writes one file per request, and batching both into a single
commit means the lower-level git trees API — noticeably more code to get
wrong, for a benefit nobody sees beyond one fewer pipeline run.
"""
upload = request.files.get("picture")
if not upload or not upload.filename:
return ""
extension = upload.filename.rsplit(".", 1)[-1].lower()
Takes bytes rather than an upload so that approving a member's submission
can commit the picture it has had on disk since they proposed it, through
exactly this code.
"""
extension = filename.rsplit(".", 1)[-1].lower()
if extension not in IMAGE_EXTENSIONS:
raise gitea.GiteaError(
f"Formato de imagen no admitido. Usa: {', '.join(sorted(IMAGE_EXTENSIONS))}."
)
data = upload.read()
maximum = current_app.config["UPLOAD_MAX_BYTES"]
if len(data) > maximum:
raise gitea.GiteaError(
f"La imagen pesa {len(data) // 1024}KB y el máximo es {maximum // 1024}KB."
)
stem = slugify(upload.filename.rsplit(".", 1)[0])[:60]
stem = slugify(filename.rsplit(".", 1)[0])[:60]
# A random suffix rather than a counter: two people uploading "foto.jpg"
# in the same minute must not race for the same path.
name = f"{stem}-{secrets.token_hex(3)}.{extension}"
gitea.write_file(f"{UPLOAD_FOLDER}/{name}", data,
f"content: subir {name}", gitea.content_token(),
member=g.member)
member=author or g.member)
return f"/uploads/{name}"
def clean_faq(raw: str) -> list[str]:
"""`pregunta|respuesta` per line, kept only when both halves are there.
Stored as the lines themselves rather than as a list of dicts: the template
and the schema both split on the first separator, and a YAML list of strings
survives translate.py's `dict(fm)` copy unchanged, which a nested structure
would too but less legibly in a diff.
"""
entries = []
for line in raw.splitlines():
question, separator, answer = line.strip().partition("|")
if not separator:
continue
question, answer = question.strip(), answer.strip()
if question and answer:
entries.append(f"{question[:200]}|{answer[:600]}")
if len(entries) >= 10:
break
return entries
def _upload_image() -> str:
upload = request.files.get("picture")
if not upload or not upload.filename:
return ""
return commit_picture(upload.read(), upload.filename)
def _field(row, name, default=None):
"""One lookup that works on a sqlite3.Row and on a plain dict.
They disagree about what a missing key is — IndexError for one, KeyError for
the other — and `approve` hands this a dict built from a row, so both arrive
here.
"""
try:
return row[name]
except (KeyError, IndexError):
return default
def byline(author) -> dict:
"""The two frontmatter keys naming a writer, from their member row.
Takes the row (or the plain dict `submissions.approve` builds from one), so
that a post published through the editor and a proposal approved by somebody
else produce the same two keys from the same code — and in the second case
they name the member, not the moderator who pressed the button.
"""
if author is None:
return {}
login = _field(author, "gitea_login", "")
name = _field(author, "display_name", "") or login
if not name:
return {}
published = _field(author, "profile_published", 0)
return {
"author": name,
"author_url": f"/{login}" if published and login else "",
}
def publish(collection: str, fields: dict, body: str, author) -> str:
"""Write one post or page into the repository and return its path.
The single place a commit is made from a finished form, shared by the editor
and by a moderator approving a submission, so both produce a byte-identical
file and the same commit shape. `author` is who wrote it, not who pressed
the button: `gitea.write_file` sends author and committer per commit, so an
approved submission keeps the member's name in git history.
"""
fields = dict(fields, **byline(author))
name = filename_for(collection, fields["title"], fields["date"])
path = f"{COLLECTIONS[collection]['folder']}/{name}"
document = build_document(frontmatter_for(collection, fields), body)
gitea.write_file(path, document.encode("utf-8"),
f"content: publicar «{fields['title']}»",
gitea.content_token(), member=author)
return path
# --- routes --------------------------------------------------------------
@bp.route("/contenido")
@bp.route("/contenido/<collection>")
@admin_required
@moderator_required
def index(collection: str = "post"):
meta = _collection_or_404(collection)
try:
@ -260,17 +426,18 @@ def index(collection: str = "post"):
flash(str(exc), "error")
items = []
return render_template("content_list.html", collection=collection, meta=meta,
collections=COLLECTIONS, items=items)
collections=visible_collections(), items=items)
@bp.route("/contenido/<collection>/nuevo", methods=["GET", "POST"])
@admin_required
@moderator_required
def new(collection: str):
meta = _collection_or_404(collection)
if request.method == "GET":
return render_template("content_form.html", collection=collection, meta=meta,
categories=CATEGORIES, item=None, fields=None,
body="", today=date_type.today().isoformat())
body="", today=date_type.today().isoformat(),
parents=possible_parents(collection))
fields, body, errors = _read_form(collection)
if errors:
@ -280,12 +447,7 @@ def new(collection: str):
picture = _upload_image()
if picture:
fields["image"] = picture
name = filename_for(collection, fields["title"], fields["date"])
path = f"{meta['folder']}/{name}"
document = build_document(frontmatter_for(collection, fields), body)
gitea.write_file(path, document.encode("utf-8"),
f"content: publicar «{fields['title']}»",
gitea.content_token(), member=g.member)
publish(collection, fields, body, g.member)
except gitea.GiteaError as exc:
return _back_to_form(collection, meta, fields, body, [str(exc)], None)
@ -294,7 +456,7 @@ def new(collection: str):
@bp.route("/contenido/<collection>/editar/<name>", methods=["GET", "POST"])
@admin_required
@moderator_required
def edit(collection: str, name: str):
meta = _collection_or_404(collection)
name = _name_or_404(name)
@ -320,11 +482,22 @@ def edit(collection: str, name: str):
"description": fm.get("description", ""),
"image": fm.get("image", ""),
"manual_translation": bool(fm.get("manual_translation")),
# Carried through the form untouched. Correcting a typo in somebody
# else's post must not re-sign it with the name of whoever is
# fixing it — the same rule the board has about editing other
# people's words, applied to the byline.
"author": fm.get("author", ""),
"author_url": fm.get("author_url", ""),
"parent": fm.get("parent", ""),
"weight": fm.get("weight", ""),
"faq": "\n".join(fm.get("faq") or []),
"image_alt": fm.get("image_alt", ""),
}
return render_template("content_form.html", collection=collection, meta=meta,
categories=CATEGORIES, item={"name": name, "sha": sha},
fields=fields, body=body,
today=date_type.today().isoformat())
today=date_type.today().isoformat(),
parents=possible_parents(collection, name))
fields, body, errors = _read_form(collection)
sha = request.form.get("sha", "")
@ -336,6 +509,8 @@ def edit(collection: str, name: str):
picture = _upload_image()
if picture:
fields["image"] = picture
# Deliberately not through publish(): that stamps the byline of whoever
# is publishing, and an edit keeps the author the file already names.
document = build_document(frontmatter_for(collection, fields), body)
gitea.write_file(path, document.encode("utf-8"),
f"content: actualizar «{fields['title']}»",
@ -348,7 +523,7 @@ def edit(collection: str, name: str):
@bp.route("/contenido/<collection>/eliminar/<name>", methods=["POST"])
@admin_required
@moderator_required
def delete(collection: str, name: str):
meta = _collection_or_404(collection)
name = _name_or_404(name)
@ -368,7 +543,7 @@ def delete(collection: str, name: str):
@bp.route("/contenido/<collection>/vista-previa", methods=["POST"])
@admin_required
@moderator_required
def preview(collection: str):
"""Rendered on the server and returned as a whole page.
@ -382,12 +557,33 @@ def preview(collection: str):
return render_template("content_form.html", collection=collection, meta=meta,
categories=CATEGORIES, item=item, fields=fields, body=body,
today=date_type.today().isoformat(),
parents=possible_parents(collection,
item["name"] if item else ""),
preview_html=to_html(body))
def possible_parents(collection: str, exclude: str = "") -> list[dict]:
"""The pages a page may hang under, for the select in the form.
Only pages have a parent, and a page cannot be its own. A failure to reach
the git server returns an empty list rather than an error: not being able to
offer the choice is no reason to refuse to open the form.
"""
if collection != "page":
return []
try:
items = listing("page")
except gitea.GiteaError:
return []
return [{"base": item["name"].removesuffix(".es.md"), "title": item["title"]}
for item in items if item["name"] != exclude]
def _back_to_form(collection, meta, fields, body, errors, item):
for message in errors:
flash(message, "error")
return render_template("content_form.html", collection=collection, meta=meta,
categories=CATEGORIES, item=item, fields=fields, body=body,
today=date_type.today().isoformat()), 400
today=date_type.today().isoformat(),
parents=possible_parents(collection,
item["name"] if item else "")), 400

View File

@ -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

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

@ -0,0 +1,188 @@
"""Inicio — the one screen a member lands on.
Every section of the members area was added in its own phase, and each one added
an entry to a flat navigation until signing in meant choosing between five words
with no idea which one held anything new. This page answers that first question:
what has happened since I was last here, and what is waiting for me.
It owns no data. Every panel is a query the module responsible already runs for
its own page — the wall's newest threads, the unread count from `messages`, the
queue from `submissions` — gathered here and linked back there. Nothing on this
page is the only way to reach anything.
"""
from __future__ import annotations
from flask import Blueprint, g, jsonify, render_template, request, url_for
from . import submissions
from .db import TOMBSTONE_LOGIN, get_db
from .render import excerpt, to_html
from .security import admin_required, csrf_token, login_required
bp = Blueprint("home", __name__)
RECENT = 5
# The longest text the preview will render. The forms themselves cap what can be
# saved; this is only here so a crafted request cannot ask for a megabyte of
# markdown to be parsed on every keystroke.
BODY_MAX = 100_000
@bp.route("/")
@login_required
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
WHERE t.deleted_at IS NULL
ORDER BY t.created_at DESC LIMIT ?""",
(RECENT,),
).fetchall()
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
AND (mine.last_read_at IS NULL OR msg.created_at > mine.last_read_at)
) AS unread,
(SELECT MAX(created_at) FROM messages
WHERE conversation_id = c.id AND deleted_at IS NULL) AS last_at
FROM conversations c
JOIN conversation_members mine
ON mine.conversation_id = c.id AND mine.member_id = :me
JOIN conversation_members theirs
ON theirs.conversation_id = c.id AND theirs.member_id != :me
JOIN members other ON other.id = theirs.member_id
ORDER BY last_at DESC NULLS LAST LIMIT :limit""",
{"me": g.member["id"], "limit": RECENT},
).fetchall()
mine = db.execute(
"""SELECT id, title, state, note FROM submissions
WHERE author_id = ? ORDER BY created_at DESC LIMIT ?""",
(g.member["id"], RECENT),
).fetchall()
# Only the people who can act on it get the queue; for everyone else the
# panel is not drawn, rather than drawn empty.
queue = []
if submissions.may_moderate():
queue = db.execute(
"""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 ?""",
(g.member["id"], RECENT),
).fetchall()
people = db.execute(
"""SELECT COUNT(*) AS n FROM members
WHERE active = 1 AND role != 'tombstone' AND gitea_login != ?""",
(TOMBSTONE_LOGIN,),
).fetchone()["n"]
return render_template("home.html", threads=threads, conversations=conversations,
mine=mine, queue=queue, people=people, excerpt=excerpt,
state_labels=submissions.STATE_LABELS)
@bp.route("/sesion.json")
def session_state():
"""Who is signed in, for the bar the public site draws.
vienalatina.com is files on disk; it cannot know who is reading it, and
baking the answer into those files would mean caching one member's name for
the next visitor. So the browser asks here instead, and this is the only
place that decides — including which sections to offer, read from the same
rule the navigation uses, so the two cannot drift.
Three properties worth stating, because each is a way this leaks:
* **A visitor gets `{"signed_in": false}` and nothing else.** No names, no
counts, no hint about who else exists.
* **`no-store`.** A cached answer is somebody else's name on a shared
machine, or a bar that stays after signing out.
* **No badge counts.** They would need queries on every public page view,
for a number nobody can act on until they are inside anyway.
"""
if g.member is None:
return _no_store(jsonify({"signed_in": False}))
sections = [
{"label": "Inicio", "url": url_for("home.index")},
{"label": "Muro", "url": url_for("board.threads")},
{"label": "Privados", "url": url_for("messages.inbox")},
{"label": "Publicaciones", "url": url_for("submissions.index")},
]
if g.member["role"] in ("owner", "admin"):
sections.append({"label": "Gestión", "url": url_for("home.gestion")})
return _no_store(jsonify({
"signed_in": True,
"name": g.member["display_name"] or g.member["gitea_login"],
"sections": sections,
"profile": url_for("profiles.edit"),
"logout": url_for("auth.logout"),
# Signing out is a POST, so the bar needs the token to render a real
# form. Handing it to a script on our own pages gives nothing away: a
# page on another origin cannot read this response — no CORS header
# allows it — and the session cookie is SameSite=Lax, so it is not sent
# with a cross-site POST in the first place.
"csrf": csrf_token(),
}))
def _no_store(response):
response.headers["Cache-Control"] = "no-store"
return response
@bp.route("/previsualizar", methods=["POST"])
@login_required
def preview():
"""Render markdown the way the site will, for the Vista previa button.
A round trip rather than a markdown parser in the browser, deliberately. The
preview has to agree with what gets published, and the only way to guarantee
that is to render it with the same function — `render.to_html`, with raw HTML
disabled, which is the whole of the XSS defence here. A second parser in
JavaScript would be a second opinion about what somebody's text means, and
the two would disagree the first time anybody wrote something unusual.
"""
body = request.form.get("body", "")[:BODY_MAX]
return _no_store(jsonify({"html": to_html(body)}))
@bp.route("/gestion")
@admin_required
def gestion():
"""Administration, which is two links and a count rather than a screen of
its own — Miembros and the static pages both already have their pages. It
exists so that neither of them has to sit in the navigation every member
sees, which is how *Contenido* ended up looking like a tab for everybody.
"""
db = get_db()
counts = {
"members": db.execute(
"SELECT COUNT(*) AS n FROM members WHERE role != 'tombstone'").fetchone()["n"],
"suspended": db.execute(
"SELECT COUNT(*) AS n FROM members WHERE active = 0 AND role != 'tombstone'"
).fetchone()["n"],
"moderators": db.execute(
"SELECT COUNT(*) AS n FROM members WHERE role IN ('owner', 'admin', 'moderator')"
).fetchone()["n"],
"pending": db.execute(
"SELECT COUNT(*) AS n FROM submissions WHERE state = 'pending'").fetchone()["n"],
}
return render_template("gestion.html", counts=counts)

View File

@ -1,11 +1,17 @@
"""Members and roles.
Three roles, and the rules between them are short enough to state in full:
Four roles, and the rules between them are short enough to state in full:
* exactly one **owner**, who creates and removes admins and can hand ownership
on; nobody can deactivate or demote them, including themselves
* **admins** create and deactivate users, and moderate the board
* **users** post, comment, and edit or delete their own writing
* **admins** create, deactivate and promote members, moderate the board, and
publish and edit the static pages of the public site
* **moderators** approve or reject what members propose for the public site,
and publish their own posts without waiting for anybody. They have no power
over people: moderating content is not the same authority, and giving one the
other is how a curation role turns into a second admin by accident
* **members** post on the wall, write privately, keep a public profile, and
propose posts for the public site
The predicates live as plain functions at the top of this module so they can be
tested without a request, a session or a browser — and so that reading them
@ -21,7 +27,7 @@ import sqlite3
from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
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 .security import admin_required, login_required, owner_required
@ -31,20 +37,33 @@ bp = Blueprint("members", __name__)
# edges. Checked here so a bad name fails before we create anything anywhere.
LOGIN_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9._-]{0,38}[A-Za-z0-9])?$")
ROLE_LABELS = {"owner": "Responsable", "admin": "Administrador", "user": "Usuario"}
# "Miembro" rather than "Usuario" on the screens, while the stored value stays
# `user`: renaming the value would mean a migration and rewriting every role
# check for a word nobody types.
ROLE_LABELS = {"owner": "Responsable", "admin": "Administrador",
"moderator": "Moderador", "user": "Miembro"}
# Who may be given which role on the Miembros screen, most trusted first, so
# the form and the predicates below cannot disagree about the list.
ASSIGNABLE_ROLES = ("admin", "moderator", "user")
def may_create(actor_role: str, target_role: str) -> bool:
"""Who may bring whom in. Admins cannot mint more admins."""
if target_role == "admin":
return actor_role == "owner"
if target_role == "user":
if target_role in ("moderator", "user"):
return actor_role in ("owner", "admin")
return False
def may_manage(actor_role: str, target_role: str) -> bool:
"""Deactivate, reactivate, or change the role of an existing member."""
"""Deactivate, reactivate, or change the role of an existing member.
A moderator appears nowhere in this function, deliberately: they approve
posts and nothing else. Being trusted to judge what the public reads is not
the same as being trusted to suspend the person who wrote it.
"""
if target_role == "owner":
return False # the owner is out of reach of everyone, themselves included
if target_role == "admin":
@ -102,8 +121,22 @@ 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
# person's name in the commit and is not ours to rewrite from here.
("submissions", "author_id"),
}
# Who reviewed somebody else's submission is a fact about that submission, not
# personal data of the reviewer, so it survives their erasure with the name
# removed rather than taking the submission down with it.
CLEARED_ON_ERASE_AFTER = {("submissions", "reviewed_by")}
def _conversations_of(member_id: int) -> str:
return "SELECT conversation_id FROM conversation_members WHERE member_id = ?"
@ -127,7 +160,10 @@ def erase_member(db: sqlite3.Connection, member_id: int) -> list[str]:
try:
# Read before deleting: once the conversations are gone there is
# 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
JOIN messages m ON m.id = a.message_id
WHERE m.conversation_id IN ({_conversations_of(member_id)})""",
@ -147,6 +183,15 @@ 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,),
)]
db.execute("DELETE FROM submissions WHERE author_id = ?", (member_id,))
for table, column in sorted(CLEARED_ON_ERASE_AFTER):
db.execute(f"UPDATE {table} SET {column} = NULL WHERE {column} = ?",
(member_id,))
# Table and column names come from the module constants above, never
# from a request, so the interpolation is not a place user input can
# reach.
@ -177,11 +222,14 @@ 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'
ORDER BY CASE m.role WHEN 'owner' THEN 0 WHEN 'admin' THEN 1 ELSE 2 END,
ORDER BY CASE m.role WHEN 'owner' THEN 0 WHEN 'admin' THEN 1
WHEN 'moderator' THEN 2 ELSE 3 END,
m.display_name COLLATE NOCASE"""
).fetchall()
return render_template("members.html", members=rows, labels=ROLE_LABELS)
@ -210,6 +258,13 @@ def new():
if not LOGIN_RE.match(login):
flash("El usuario solo puede tener letras, números, punto, guion y guion bajo.", "error")
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:
# 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
@ -309,11 +364,23 @@ def set_active(member_id: int):
@bp.route("/miembros/<int:member_id>/rol", methods=["POST"])
@owner_required
@admin_required
def set_role(member_id: int):
"""Admin-level rather than owner-level, now that there is a role between
the two worth handing out routinely.
Two predicates, both of them: `may_manage` for reaching this person at all,
and `may_create` for the role being given — you may only grant a role you
could have created somebody with, which keeps "admins cannot mint admins"
true here as well without restating it.
"""
target = _load(member_id)
role = request.form.get("role", "")
if role not in ("admin", "user") or not may_manage(g.member["role"], target["role"]):
if role not in ASSIGNABLE_ROLES:
abort(403)
if not may_manage(g.member["role"], target["role"]):
abort(403)
if not may_create(g.member["role"], role):
abort(403)
get_db().execute("UPDATE members SET role = ? WHERE id = ?", (role, member_id))
flash(f"{target['display_name']} ahora es {ROLE_LABELS[role].lower()}.", "ok")

View File

@ -25,34 +25,6 @@ bp = Blueprint("messages", __name__)
BODY_MAX = 20_000
def _other_party(conversation_id: int):
"""The member on the far side, or None if they have been erased."""
return get_db().execute(
"""SELECT m.* FROM conversation_members cm
JOIN members m ON m.id = cm.member_id
WHERE cm.conversation_id = ? AND cm.member_id != ?""",
(conversation_id, g.member["id"]),
).fetchone()
def _mine_or_404(conversation_id: int):
"""Membership is the entire access rule, and it is checked on every hit.
Not "does this conversation exist" — a member who is not in it must not be
able to tell the difference between a conversation that is not theirs and
one that does not exist.
"""
row = get_db().execute(
"""SELECT c.* FROM conversations c
JOIN conversation_members cm ON cm.conversation_id = c.id
WHERE c.id = ? AND cm.member_id = ?""",
(conversation_id, g.member["id"]),
).fetchone()
if row is None:
abort(404)
return row
def blocked_between(a: int, b: int) -> bool:
"""A block in either direction stops both directions."""
return get_db().execute(
@ -63,6 +35,18 @@ def blocked_between(a: int, b: int) -> bool:
).fetchone() is not None
def existing_conversation(other_id: int) -> int | None:
"""The conversation between us and `other_id`, or None. Creates nothing."""
row = get_db().execute(
"""SELECT a.conversation_id AS id
FROM conversation_members a
JOIN conversation_members b ON b.conversation_id = a.conversation_id
WHERE a.member_id = ? AND b.member_id = ?""",
(g.member["id"], other_id),
).fetchone()
return row["id"] if row else None
def conversation_with(other_id: int) -> int:
"""The conversation between the signed-in member and `other_id`, made if
it does not exist yet."""
@ -112,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,
@ -138,7 +124,7 @@ def inbox():
people = get_db().execute(
"""SELECT m.id, m.display_name FROM members m
WHERE m.id != :me AND m.active = 1
AND m.role IN ('owner', 'admin', 'user')
AND m.role != 'tombstone'
AND m.gitea_login != :ghost
AND NOT EXISTS (SELECT 1 FROM blocks
WHERE (blocker_id = :me AND blocked_id = m.id)
@ -151,88 +137,91 @@ def inbox():
excerpt=lambda text: (text or "")[:120])
@bp.route("/privados/nueva", methods=["POST"])
@bp.route("/privados/con")
@login_required
def start():
"""The member comes from the form, not the path, so the select can post
straight here. A path parameter would need JavaScript to rewrite the
action, and the Content-Security-Policy makes inline handlers silently
inert — a class of bug this codebase has already paid for once."""
member_id = request.form.get("member_id", type=int)
if member_id is None or member_id == g.member["id"]:
def pick():
"""The select posts here as a plain GET and is sent on to the conversation.
A form cannot put its own value into a path, and rewriting the action with
JavaScript is not available: the Content-Security-Policy has no
'unsafe-inline', so an inline handler is ignored without a word. One tiny
redirect avoids the whole question.
"""
return redirect(url_for("messages.talk",
member_id=request.args.get("member_id", type=int) or 0))
@bp.route("/privados/con/<int:member_id>", methods=["GET", "POST"])
@login_required
def talk(member_id: int):
"""One page for a conversation, whether or not it exists yet.
There used to be an "Abrir conversación" step that created an empty
conversation and sent you to it. It bought nothing — you still had to type
a message afterwards — and it littered the inbox with rows saying "Sin
mensajes todavía" for people nobody had actually written to. The
conversation is now created by the first message, not by looking at
somebody's name.
"""
if member_id == g.member["id"]:
abort(400)
target = get_db().execute(
other = get_db().execute(
"""SELECT * FROM members
WHERE id = ? AND active = 1 AND role IN ('owner', 'admin', 'user')""",
WHERE id = ? AND active = 1 AND role != 'tombstone'""",
(member_id,),
).fetchone()
if target is None:
abort(404)
if blocked_between(g.member["id"], member_id):
abort(403)
return redirect(url_for("messages.conversation",
conversation_id=conversation_with(member_id)))
@bp.route("/privados/<int:conversation_id>")
@login_required
def conversation(conversation_id: int):
_mine_or_404(conversation_id)
db = get_db()
rows = db.execute(
"""SELECT m.*, a.display_name AS author
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""",
(conversation_id,),
).fetchall()
# Marked read on opening, which is what the member just did. Written before
# rendering so a slow page does not leave the badge stale.
db.execute(
"""UPDATE conversation_members SET last_read_at = datetime('now')
WHERE conversation_id = ? AND member_id = ?""",
(conversation_id, g.member["id"]),
)
other = _other_party(conversation_id)
return render_template(
"conversation.html", conversation_id=conversation_id, messages=rows,
other=other, to_html=to_html,
images=uploads.for_messages([row["id"] for row in rows]),
blocked=other is not None and blocked_between(g.member["id"], other["id"]),
)
@bp.route("/privados/<int:conversation_id>/enviar", methods=["POST"])
@login_required
def send(conversation_id: int):
_mine_or_404(conversation_id)
other = _other_party(conversation_id)
if other is None:
flash("Esa persona ya no está en la comunidad.", "error")
return redirect(url_for("messages.conversation", conversation_id=conversation_id))
# Checked here and not only hidden in the template: the template is a
# courtesy, this is the rule.
if blocked_between(g.member["id"], other["id"]):
abort(404)
blocked = blocked_between(g.member["id"], member_id)
if blocked and request.method == "POST":
abort(403)
body = request.form.get("body", "").strip()[:BODY_MAX]
try:
staged = uploads.stage(request.files.getlist("pictures"))
except uploads.RejectedUpload as exc:
flash(str(exc), "error")
return redirect(url_for("messages.conversation", conversation_id=conversation_id))
if not body and not staged:
flash("Escribe algo o adjunta una imagen.", "error")
return redirect(url_for("messages.conversation", conversation_id=conversation_id))
db = get_db()
conversation_id = existing_conversation(member_id)
cursor = get_db().execute(
"INSERT INTO messages (conversation_id, author_id, body_md) VALUES (?, ?, ?)",
(conversation_id, g.member["id"], body),
if request.method == "POST":
body = request.form.get("body", "").strip()[:BODY_MAX]
try:
staged = uploads.stage(request.files.getlist("pictures"))
except uploads.RejectedUpload as exc:
flash(str(exc), "error")
return redirect(url_for("messages.talk", member_id=member_id))
if not body and not staged:
flash("Escribe algo o adjunta una imagen.", "error")
return redirect(url_for("messages.talk", member_id=member_id))
# Only now does the conversation come into being.
if conversation_id is None:
conversation_id = conversation_with(member_id)
cursor = db.execute(
"INSERT INTO messages (conversation_id, author_id, body_md) VALUES (?, ?, ?)",
(conversation_id, g.member["id"], body),
)
uploads.save(staged, g.member["id"], message_id=cursor.lastrowid)
return redirect(url_for("messages.talk", member_id=member_id) + "#final")
rows = []
if conversation_id is not None:
rows = db.execute(
"""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""",
(conversation_id,),
).fetchall()
db.execute(
"""UPDATE conversation_members SET last_read_at = datetime('now')
WHERE conversation_id = ? AND member_id = ?""",
(conversation_id, g.member["id"]),
)
return render_template(
"conversation.html", other=other, messages=rows, to_html=to_html,
images=uploads.for_messages([row["id"] for row in rows]),
blocked=blocked,
)
uploads.save(staged, g.member["id"], message_id=cursor.lastrowid)
return redirect(url_for("messages.conversation", conversation_id=conversation_id) + "#final")
@bp.route("/privados/bloquear/<int:member_id>", methods=["POST"])

View File

@ -24,6 +24,7 @@ again, so a correction is a new step.
from __future__ import annotations
import re
import sqlite3
@ -31,6 +32,24 @@ def _columns(db: sqlite3.Connection, table: str) -> set[str]:
return {row[1] for row in db.execute(f"PRAGMA table_info({table})")}
def _role_check(db: sqlite3.Connection) -> str:
"""The CREATE TABLE text of `members` with its comments stripped.
A CHECK constraint is the one piece of a table no pragma reports, so the
only way to ask what roles are allowed is to read the statement back — and
sqlite_master stores that statement *verbatim*, comments included. schema.sql
explains above the column why 'moderator' needed a rebuild, and searching the
raw text would find that sentence and conclude the work was already done.
Which is exactly what happened, and what the start-up test caught.
"""
row = db.execute(
"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'members'"
).fetchone()
if row is None:
return ""
return re.sub(r"--[^\n]*", "", row[0])
def _attachments_accept_messages(db: sqlite3.Connection) -> None:
"""Let an attachment hang off a private message.
@ -104,11 +123,96 @@ def _members_own_their_passwords(db: sqlite3.Connection) -> None:
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}")
def _members_can_moderate(db: sqlite3.Connection) -> None:
"""Add the `moderator` role, which means rebuilding this table.
`role` carries `CHECK (role IN ('owner','admin','user','tombstone'))`, and
SQLite has no DROP CONSTRAINT, so widening the list is not an ALTER. This is
the same documented procedure as step 1 — new table, copy, drop, rename —
but on a table eight others point at, which is what makes it worth spelling
out:
* `members` is referenced by threads, comments, conversation_members,
messages, blocks, attachments, invites, submissions and by itself
(`created_by`). Those clauses say `REFERENCES members`, resolved by name
at runtime rather than bound to the table's identity, so after the rename
they point at the new table with nothing to update.
* The rename only rewrites clauses that name `members_new`, and nothing
does, so no other table's schema is touched.
* `migrations.apply()` turns foreign keys off *outside* the transaction,
which is the only place it works — see the comment there.
* The partial unique index enforcing one owner is not carried over by the
copy and has to be recreated, or the database quietly loses the rule that
stops a second owner existing.
Checked afterwards with `PRAGMA foreign_key_check`, and by the test that
builds a pre-migration database with a row in every referencing table.
"""
if "moderator" in _role_check(db):
return
db.execute("""
CREATE TABLE members_new (
id INTEGER PRIMARY KEY,
gitea_login TEXT NOT NULL UNIQUE COLLATE NOCASE,
display_name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '',
password_hash TEXT,
profile_published INTEGER NOT NULL DEFAULT 0 CHECK (profile_published IN (0, 1)),
bio TEXT,
links TEXT,
photo_name TEXT,
role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'moderator',
'user', 'tombstone')),
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
created_by INTEGER REFERENCES members(id),
last_seen_at TEXT
)""")
db.execute("""
INSERT INTO members_new
(id, gitea_login, display_name, email, password_hash,
profile_published, bio, links, photo_name,
role, active, created_at, created_by, last_seen_at)
SELECT id, gitea_login, display_name, email, password_hash,
profile_published, bio, links, photo_name,
role, active, created_at, created_by, last_seen_at
FROM members""")
db.execute("DROP TABLE members")
db.execute("ALTER TABLE members_new RENAME TO members")
db.execute("""CREATE UNIQUE INDEX IF NOT EXISTS members_one_owner
ON members(role) WHERE role = 'owner'""")
broken = db.execute("PRAGMA foreign_key_check").fetchall()
if broken:
raise RuntimeError(f"migration left dangling references: {broken}")
# (number, description, function). The number is the value written to
# user_version once the step succeeds.
STEPS = [
(1, "attachments can belong to a private message", _attachments_accept_messages),
(2, "members keep their own password", _members_own_their_passwords),
(3, "members can have a public page", _members_get_a_public_page),
(4, "members can be moderators", _members_can_moderate),
]

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

@ -0,0 +1,227 @@
"""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>/")
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("/<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)
@bp.route("/miembro/foto/<stored_name>")
@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"])
@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,7 +13,17 @@ CREATE TABLE IF NOT EXISTS members (
display_name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '',
password_hash TEXT,
role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')),
-- 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,
-- 'moderator' arrived with migration 4, which had to rebuild this table:
-- SQLite has no DROP CONSTRAINT, so widening a CHECK is never an ALTER.
role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'moderator',
'user', 'tombstone')),
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
created_by INTEGER REFERENCES members(id),
@ -209,3 +219,76 @@ CREATE TABLE IF NOT EXISTS invites (
CREATE INDEX IF NOT EXISTS invites_open
ON invites(member_id, purpose) WHERE used_at IS NULL;
-- Public posts a member has proposed, waiting for a moderator.
--
-- A draft in SQLite, deliberately not a commit. A commit to the site
-- repository *is* publication: Gitea's webhook fires Woodpecker, which
-- translates, builds and deploys within minutes. So nothing written here
-- reaches git until somebody with the moderator role approves it, and
-- approval is the only code path that calls gitea.write_file for a
-- submission.
--
-- Moderators and admins do not use this table at all: they write through the
-- editor in content.py and their post is committed as they save it. The queue
-- exists for members, which is the whole of the curation policy — fewer posts,
-- each one read by somebody before the public sees it.
--
-- The picture is a column here rather than a row in `attachments`, following
-- members.photo_name: a submission carries at most one, and giving
-- `attachments` a fourth possible parent would mean rebuilding that table
-- again for nothing. It lives in /data/uploads like every other private
-- picture, and is committed to the repository only on approval.
CREATE TABLE IF NOT EXISTS submissions (
id INTEGER PRIMARY KEY,
author_id INTEGER NOT NULL REFERENCES members(id),
title TEXT NOT NULL,
body_md TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
categories TEXT NOT NULL DEFAULT '', -- comma-separated, as content_cache
photo_name TEXT,
state TEXT NOT NULL DEFAULT 'pending'
CHECK (state IN ('pending', 'approved', 'rejected')),
-- Why it was rejected, in the moderator's words, shown to the author. A
-- queue that swallows work without saying why is a queue people stop using.
note TEXT,
reviewed_by INTEGER REFERENCES members(id),
reviewed_at TEXT,
-- Where it landed in the repository, so the author can be shown that it is
-- live rather than merely "approved".
published_path TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT
);
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;

View File

@ -54,6 +54,23 @@ def admin_required(view):
return wrapped
def moderator_required(view):
"""Curating the public site. Admins and the owner count as moderators.
Deliberately separate from admin_required: a moderator decides what the
public sees and nothing else. They cannot reach Gestión, cannot create or
deactivate anybody, and cannot change a role — moderating content is not
power over people.
"""
@wraps(view)
@login_required
def wrapped(*args, **kwargs):
if g.member["role"] not in ("owner", "admin", "moderator"):
abort(403)
return view(*args, **kwargs)
return wrapped
def owner_required(view):
@wraps(view)
@login_required

View File

@ -112,6 +112,9 @@ button, input, select, textarea { font: inherit; }
margin-bottom: 1.5rem;
}
.feed-head h1 { margin: 0; }
/* Two things on the right of a heading — a link and a button — kept on one
line and aligned to each other rather than to the heading's baseline. */
.feed-head__actions { display: flex; align-items: center; gap: 1rem; }
.card {
background: var(--surface);
@ -324,3 +327,273 @@ input[type="file"] {
border-radius: var(--radius-md);
border: 1px solid var(--border-light);
}
/* One picture rather than a gallery: a proposal carries at most a single
image, and it is shown at reading size while it is being reviewed. */
.attachment {
display: block;
margin: 0.75rem 0;
max-height: 320px;
max-width: 100%;
border-radius: var(--radius-md);
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 <details> element, because the Content-Security-Policy has no
* 'unsafe-inline' and a menu that needs an onclick="" attribute is a menu the
* browser silently refuses to open. The summary is the whole control; the
* panel is positioned relative to it.
*/
.account { position: relative; }
.account__name {
cursor: pointer;
list-style: none; /* Firefox's default marker */
color: var(--muted);
font-size: 0.9rem;
padding: 0.25rem 0;
}
.account__name::-webkit-details-marker { display: none; }
.account__name::after { content: " ▾"; color: var(--subtle); }
.account[open] .account__name { color: var(--brand); }
.account__menu {
position: absolute;
right: 0;
z-index: 20;
min-width: 13rem;
display: flex;
flex-direction: column;
gap: 0.15rem;
padding: 0.5rem;
background: var(--surface);
border: 1px solid var(--border-light);
border-radius: var(--radius-md);
box-shadow: var(--shadow);
}
.account__menu a,
.account__menu button {
text-align: left;
padding: 0.4rem 0.5rem;
border-radius: var(--radius-sm);
font-size: 0.92rem;
text-decoration: none;
color: var(--text);
}
.account__menu a:hover,
.account__menu button:hover { background: var(--surface-soft); }
.account__menu form { margin: 0; }
/* --- Inicio's panels -------------------------------------------------- */
.panel {
background: var(--surface);
border: 1px solid var(--border-light);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-sm);
padding: 1rem 1.25rem;
margin-bottom: 1.25rem;
}
/* Anything the member is expected to act on, rather than read. */
.panel--attention { border-color: var(--brand); background: var(--brand-softer); }
.panel__head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 1rem;
margin-bottom: 0.5rem;
}
.panel__head h2 { margin: 0; font-size: 1.05rem; }
.panel__row {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 0.5rem;
margin: 0.35rem 0;
padding-bottom: 0.35rem;
border-bottom: 1px solid var(--border-light);
}
.panel__row:last-child { border-bottom: none; padding-bottom: 0; }
/* --- where a proposal has got to -------------------------------------- */
.tag--pending { background: var(--surface-soft); color: var(--muted); }
.tag--approved { background: var(--brand-soft); color: var(--brand-dark); }
.tag--rejected { background: #f7dcdc; color: var(--danger); }
/* A role picker sitting in a table cell beside the other row actions. */
.inline-form { display: flex; align-items: center; gap: 0.35rem; margin: 0; }
.inline-form select { padding: 0.2rem 0.35rem; font-size: 0.85rem; }
/* Present for a screen reader, absent for everybody else — a <select> in a
table of actions has no room for a visible label but still needs one. */
.sr-only {
position: absolute;
width: 1px; height: 1px;
padding: 0; margin: -1px;
overflow: hidden;
clip: rect(0 0 0 0);
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; }
/* --- the writing boxes ------------------------------------------------- */
.md-bar {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
margin-bottom: 0.35rem;
}
.md-bar__button {
min-width: 2rem;
padding: 0.25rem 0.5rem;
border: 1px solid var(--border-light);
border-radius: var(--radius-sm);
background: var(--surface);
color: var(--muted);
font-size: 0.85rem;
cursor: pointer;
line-height: 1.4;
}
.md-bar__button:hover { border-color: var(--brand); color: var(--brand-dark); }
.md-bar__button--wide { margin-left: auto; }
.md-preview {
margin: 0.5rem 0 1rem;
padding: 0.85rem 1rem;
border: 1px dashed var(--border);
border-radius: var(--radius-md);
background: var(--surface-soft);
line-height: 1.6;
}
.md-preview :first-child { margin-top: 0; }
.md-preview :last-child { margin-bottom: 0; }
.md-preview img { max-width: 100%; border-radius: var(--radius-sm); }
/* What you just chose, before it is uploaded. */
.file-strip {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
margin: 0.5rem 0 0;
}
.file-strip__item { margin: 0; width: 120px; }
.file-strip__item img {
display: block;
width: 120px;
height: 90px;
object-fit: cover;
border-radius: var(--radius-sm);
border: 1px solid var(--border-light);
}
.file-strip__item figcaption {
margin-top: 0.2rem;
font-size: 0.72rem;
color: var(--subtle);
overflow-wrap: anywhere;
}

View File

@ -13,3 +13,152 @@ document.addEventListener("submit", function (event) {
event.preventDefault();
}
});
// --- the writing boxes ----------------------------------------------------
//
// A toolbar, a preview and thumbnails, all of it ours. Not because a library
// would be wrong, but because the Content-Security-Policy here loads scripts
// from this origin only, and vendoring an editor means owning its updates
// forever — for buttons that wrap a selection in asterisks.
//
// Everything below attaches on load and leaves anything it does not recognise
// alone, so a form that has not opted in behaves exactly as it did.
(function () {
"use strict";
// What each button does to the selected text. `wrap` goes on both sides,
// `prefix` goes at the start of every selected line.
var TOOLS = [
{ label: "N", title: "Negrita", wrap: "**" },
{ label: "I", title: "Cursiva", wrap: "_" },
{ label: "H", title: "Título", prefix: "## " },
{ label: "“”", title: "Cita", prefix: "> " },
{ label: "•", title: "Lista", prefix: "- " },
{ label: "🔗", title: "Enlace", link: true }
];
function apply(box, tool) {
var start = box.selectionStart;
var end = box.selectionEnd;
var selected = box.value.slice(start, end);
var replacement;
if (tool.link) {
var url = window.prompt("Dirección del enlace", "https://");
if (!url) return;
replacement = "[" + (selected || "texto") + "](" + url + ")";
} else if (tool.prefix) {
// Line by line, so marking three lines as a list marks three lines.
replacement = (selected || "").split("\n").map(function (line) {
return line.indexOf(tool.prefix) === 0 ? line : tool.prefix + line;
}).join("\n");
} else {
replacement = tool.wrap + (selected || "texto") + tool.wrap;
}
box.setRangeText(replacement, start, end, "end");
box.focus();
// Fires the input event frameworks and our own counters would expect; the
// browser does not fire one for a programmatic change.
box.dispatchEvent(new Event("input", { bubbles: true }));
}
function toolbarFor(box) {
var bar = document.createElement("div");
bar.className = "md-bar";
TOOLS.forEach(function (tool) {
var button = document.createElement("button");
button.type = "button"; // never a submit inside a form
button.className = "md-bar__button";
button.title = tool.title;
button.textContent = tool.label;
button.addEventListener("click", function () { apply(box, tool); });
bar.appendChild(button);
});
var preview = document.createElement("button");
preview.type = "button";
preview.className = "md-bar__button md-bar__button--wide";
preview.textContent = "Vista previa";
var panel = document.createElement("div");
panel.className = "md-preview";
panel.hidden = true;
preview.addEventListener("click", function () {
if (!panel.hidden) {
panel.hidden = true;
return;
}
var token = box.form && box.form.querySelector("input[name=csrf_token]");
var data = new FormData();
data.append("body", box.value);
data.append("csrf_token", token ? token.value : "");
panel.textContent = "Un momento…";
panel.hidden = false;
fetch("/comunidad/previsualizar", {
method: "POST", body: data, credentials: "same-origin"
}).then(function (response) {
return response.ok ? response.json() : null;
}).then(function (result) {
// The server rendered this with the same markdown the site uses, with
// raw HTML disabled, so what comes back is already safe to insert —
// and inserting it as text would show the tags instead of the writing.
panel.innerHTML = result ? result.html : "";
if (!result) panel.textContent = "No se pudo generar la vista previa.";
}).catch(function () {
panel.textContent = "No se pudo generar la vista previa.";
});
});
bar.appendChild(preview);
box.parentNode.insertBefore(bar, box);
box.parentNode.insertBefore(panel, box.nextSibling);
}
// --- thumbnails of what was just chosen ---------------------------------
//
// So that attaching the wrong photograph is noticed before posting rather
// than after. createObjectURL gives a handle to bytes already in this page —
// nothing is uploaded until the form is submitted — which is what `blob:` in
// the image policy is there for.
function previewFiles(input) {
var strip = input.nextElementSibling;
if (!strip || !strip.classList.contains("file-strip")) {
strip = document.createElement("div");
strip.className = "file-strip";
input.parentNode.insertBefore(strip, input.nextSibling);
}
Array.prototype.forEach.call(strip.querySelectorAll("img"), function (img) {
URL.revokeObjectURL(img.src); // or every re-pick leaks one
});
strip.textContent = "";
Array.prototype.forEach.call(input.files, function (file) {
if (file.type.indexOf("image/") !== 0) return;
var figure = document.createElement("figure");
figure.className = "file-strip__item";
var img = document.createElement("img");
img.src = URL.createObjectURL(file);
img.alt = "";
var caption = document.createElement("figcaption");
caption.textContent = file.name + " · " + Math.round(file.size / 1024) + " KB";
figure.appendChild(img);
figure.appendChild(caption);
strip.appendChild(figure);
});
}
document.addEventListener("DOMContentLoaded", function () {
Array.prototype.forEach.call(
document.querySelectorAll("textarea[data-markdown]"), toolbarFor);
document.addEventListener("change", function (event) {
var input = event.target;
if (input.tagName === "INPUT" && input.type === "file" &&
(input.accept || "").indexOf("image") !== -1) {
previewFiles(input);
}
});
});
})();

View File

@ -0,0 +1,88 @@
/* The public profile page at vienalatina.com/su-nombre.
*
* A separate file rather than a <style> block in the template, and that is not
* a matter of taste. The Content-Security-Policy in app.py is
* `default-src 'self'` with no 'unsafe-inline', so a browser silently ignores
* an inline <style> — the page arrives in Times New Roman with blue links and
* nothing in the console explains why. Served from /comunidad/static/ it is
* same-origin, allowed, and the policy keeps its teeth.
*
* The colours are repeated from themes/vienalatina/assets/css/main.css rather
* than shared with it: Hugo fingerprints its stylesheet, so there is no stable
* URL to link to. If the brand changes there, change it here. A deliberate
* duplicate, said out loud.
*/
: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; }
/* Bounded on both axes: a photo straight off a phone is several thousand
pixels wide, and without this it pushes the name off the screen. */
.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;
}

407
apps/board/submissions.py Normal file
View File

@ -0,0 +1,407 @@
"""What members propose for the public site, and who lets it through.
The whole of the curation policy, in three sentences. A member writes a post
here and it waits. A moderator or an admin reads it and either approves it —
which commits it to the site repository under the member's own name — or rejects
it with a reason the author can read. Moderators and admins do not queue: they
write in the editor (`content.py`) and their post is committed as they save it.
**Nothing in this module reaches git until somebody approves.** That is not a
convention, it is the reason the table exists: a commit to the content repository
*is* publication, because Gitea's webhook starts the translate → build → deploy
pipeline within seconds. A draft that lived in the repository with a "pending"
flag would already be on vienalatina.com in three languages.
Approval goes through `content.publish`, the same function the editor uses, so an
approved submission is byte-identical to a post written by a moderator and the
pipeline cannot tell the two apart. `gitea.write_file` takes an author per commit,
so git history names the member who wrote it, not the moderator who approved it.
There is deliberately no way to promote a thread from the wall into a
submission. Writing for the public is a separate act — somebody decided to
address strangers rather than the people they already know, and that decision is
the thing worth keeping visible.
"""
from __future__ import annotations
from datetime import date as date_type
from flask import (Blueprint, abort, current_app, flash, g, redirect,
render_template, request, send_from_directory, url_for)
from . import content, gitea, uploads
from .db import get_db
from .render import excerpt, to_html
from .security import login_required, moderator_required
bp = Blueprint("submissions", __name__)
TITLE_MAX = content.TITLE_MAX
BODY_MAX = content.BODY_MAX
# How many proposals one member may have waiting at once. Not a security limit:
# everyone here is a known member. It is a limit on how much unread work one
# person can put on the moderators before talking to them.
PENDING_MAX = 3
STATE_LABELS = {
"pending": "En revisión",
"approved": "Publicado",
"rejected": "Devuelto",
}
def may_moderate(member=None) -> bool:
member = member or g.member
return member is not None and member["role"] in ("owner", "admin", "moderator")
def pending_count() -> int:
"""For the badge in the navigation, and 0 for anyone who cannot act on it —
a member does not need to know how long the queue is."""
if not may_moderate():
return 0
return get_db().execute(
"SELECT COUNT(*) AS n FROM submissions WHERE state = 'pending'"
).fetchone()["n"]
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.profile_published AS author_published,
r.display_name AS reviewer
FROM submissions s
JOIN members m ON m.id = s.author_id
LEFT JOIN members r ON r.id = s.reviewed_by
WHERE s.id = ?""",
(submission_id,),
).fetchone()
if row is None:
abort(404)
return row
def _mine_or_403(row) -> None:
if row["author_id"] != g.member["id"]:
abort(403)
def _read_proposal() -> tuple[dict, list[str]]:
"""The same fields the editor asks for, minus the ones only a publisher
decides: the date is the day it is approved, and `manual_translation` is a
pipeline switch, not something to explain to a member."""
fields = {
"title": request.form.get("title", "").strip()[:TITLE_MAX],
"body": request.form.get("body", "").strip()[:BODY_MAX],
"description": request.form.get("description", "").strip()[:300],
"categories": [c for c in request.form.getlist("categories")
if c in content.CATEGORIES],
}
errors = []
if not fields["title"]:
errors.append("El título no puede estar vacío.")
if not fields["body"]:
errors.append("El texto no puede estar vacío.")
return fields, errors
# --- the member's side ----------------------------------------------------
@bp.route("/publicaciones")
@login_required
def index():
"""One page for both sides of the queue.
A member sees what they proposed and what happened to it. A moderator sees
that plus everything waiting, because the first thing a moderator wants on
opening this section is the list of things to read.
"""
db = get_db()
mine = db.execute(
"""SELECT * FROM submissions WHERE author_id = ?
ORDER BY CASE state WHEN 'pending' THEN 0 ELSE 1 END, created_at DESC""",
(g.member["id"],),
).fetchall()
queue = []
if may_moderate():
queue = db.execute(
"""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""",
(g.member["id"],),
).fetchall()
return render_template("submissions.html", mine=mine, queue=queue,
labels=STATE_LABELS, excerpt=excerpt,
can_moderate=may_moderate())
@bp.route("/publicaciones/nueva", methods=["GET", "POST"])
@login_required
def propose():
if may_moderate():
# Not a refusal: a moderator's post does not queue, so sending them
# through a form that would only wait for their own approval is a
# detour with nothing at the end of it.
return redirect(url_for("content.new", collection="post"))
if request.method == "GET":
return render_template("submission_form.html", item=None, fields=None,
categories=content.CATEGORIES)
fields, errors = _read_proposal()
waiting = get_db().execute(
"SELECT COUNT(*) AS n FROM submissions WHERE author_id = ? AND state = 'pending'",
(g.member["id"],),
).fetchone()["n"]
if waiting >= PENDING_MAX:
errors.append(
f"Ya tienes {waiting} propuestas en revisión. Espera a que las lean "
"antes de enviar otra."
)
staged = []
if not errors:
try:
staged = uploads.stage(request.files.getlist("picture"))
except uploads.RejectedUpload as exc:
errors.append(str(exc))
if errors:
return _back_to_form(None, fields, errors)
photo_name = _store_picture(staged)
get_db().execute(
"""INSERT INTO submissions
(author_id, title, body_md, description, categories, photo_name)
VALUES (?, ?, ?, ?, ?, ?)""",
(g.member["id"], fields["title"], fields["body"], fields["description"],
", ".join(fields["categories"]), photo_name),
)
flash("Enviado. Un moderador lo leerá antes de publicarlo.", "ok")
return redirect(url_for("submissions.index"))
@bp.route("/publicaciones/<int:submission_id>", methods=["GET"])
@login_required
def show(submission_id: int):
"""The author reads their own; a moderator reads anybody's. Nobody else
reads any of it — an unapproved post is private writing."""
row = _load(submission_id)
if row["author_id"] != g.member["id"] and not may_moderate():
abort(403)
return render_template("submission.html", item=row, labels=STATE_LABELS,
body_html=to_html(row["body_md"]),
can_moderate=may_moderate(),
mine=row["author_id"] == g.member["id"])
@bp.route("/publicaciones/<int:submission_id>/editar", methods=["GET", "POST"])
@login_required
def edit(submission_id: int):
"""Only while it is waiting or has come back. Editing an approved one would
change nothing: the file is already in the repository, and the editor is
where a published post is changed."""
row = _load(submission_id)
_mine_or_403(row)
if row["state"] == "approved":
flash("Ya está publicado. Pide a un moderador que lo edite en el sitio.", "error")
return redirect(url_for("submissions.index"))
if request.method == "GET":
return render_template("submission_form.html", item=row, categories=content.CATEGORIES,
fields={
"title": row["title"], "body": row["body_md"],
"description": row["description"],
"categories": [c.strip() for c in
(row["categories"] or "").split(",") if c.strip()],
})
fields, errors = _read_proposal()
staged = []
if not errors:
try:
staged = uploads.stage(request.files.getlist("picture"))
except uploads.RejectedUpload as exc:
errors.append(str(exc))
if errors:
return _back_to_form(row, fields, errors)
photo_name = row["photo_name"]
if staged:
if photo_name:
uploads.remove(photo_name)
photo_name = _store_picture(staged)
get_db().execute(
"""UPDATE submissions
SET title = ?, body_md = ?, description = ?, categories = ?,
photo_name = ?, state = 'pending', note = NULL,
reviewed_by = NULL, reviewed_at = NULL,
updated_at = datetime('now')
WHERE id = ?""",
(fields["title"], fields["body"], fields["description"],
", ".join(fields["categories"]), photo_name, submission_id),
)
# Back to pending on every edit, including one made after a rejection: a
# rejected post that has been rewritten is waiting again, and leaving it
# marked "devuelto" would hide it from the queue forever.
flash("Actualizado. Vuelve a estar en revisión.", "ok")
return redirect(url_for("submissions.index"))
@bp.route("/publicaciones/<int:submission_id>/retirar", methods=["POST"])
@login_required
def withdraw(submission_id: int):
row = _load(submission_id)
_mine_or_403(row)
if row["state"] == "approved":
abort(403)
get_db().execute("DELETE FROM submissions WHERE id = ?", (submission_id,))
if row["photo_name"]:
uploads.remove(row["photo_name"])
flash("Propuesta retirada.", "ok")
return redirect(url_for("submissions.index"))
@bp.route("/publicaciones/foto/<stored_name>")
@login_required
def photo(stored_name: str):
"""Behind the login and narrower than that: the author and the moderators.
A submission's picture is not published yet, and "any signed-in member" is
not the audience the author chose when they attached it.
"""
if not uploads.STORED_NAME.match(stored_name):
abort(404)
row = get_db().execute(
"SELECT author_id FROM submissions WHERE photo_name = ?", (stored_name,)
).fetchone()
if row is None:
abort(404)
if row["author_id"] != g.member["id"] and not may_moderate():
abort(404)
return send_from_directory(uploads.directory(), stored_name)
# --- the moderator's side -------------------------------------------------
@bp.route("/publicaciones/<int:submission_id>/aprobar", methods=["POST"])
@moderator_required
def approve(submission_id: int):
"""Commit it, under the author's name, and record where it landed."""
row = _load(submission_id)
if row["state"] == "approved":
flash("Esa propuesta ya estaba publicada.", "error")
return redirect(url_for("submissions.index"))
author = {"display_name": row["author"], "email": row["author_email"],
"gitea_login": row["author_login"],
# For the byline on the published page: it links to their profile
# only if they have one, so an approved post never carries a link
# to a 404.
"profile_published": row["author_published"]}
fields = {
"title": row["title"],
# The day it is published, not the day it was written: Hugo sorts by
# this and the URL carries it, so a proposal that waited a week should
# not arrive dated a week ago.
"date": date_type.today(),
"categories": [c.strip() for c in (row["categories"] or "").split(",") if c.strip()],
"description": row["description"],
"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 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))
get_db().execute(
"""UPDATE submissions
SET state = 'approved', note = NULL, reviewed_by = ?,
reviewed_at = datetime('now'), published_path = ?,
photo_name = NULL, updated_at = datetime('now')
WHERE id = ?""",
(g.member["id"], path, submission_id),
)
# The private copy goes now that the picture is in the repository: one file,
# in one place, and no orphan in /data/uploads that nothing will ever serve.
if row["photo_name"]:
uploads.remove(row["photo_name"])
flash(f"Publicado «{row['title']}». La traducción tarda un par de minutos.", "ok")
return redirect(url_for("submissions.index"))
@bp.route("/publicaciones/<int:submission_id>/rechazar", methods=["POST"])
@moderator_required
def reject(submission_id: int):
"""A reason is required, and it is shown to the author.
Not politeness: without one the author has no idea whether to rewrite it,
shorten it or drop it, and the next thing they send has the same problem.
"""
row = _load(submission_id)
note = request.form.get("note", "").strip()[:1_000]
if not note:
flash("Escribe el motivo: el autor lo va a leer.", "error")
return redirect(url_for("submissions.show", submission_id=submission_id))
if row["state"] == "approved":
abort(403)
get_db().execute(
"""UPDATE submissions
SET state = 'rejected', note = ?, reviewed_by = ?,
reviewed_at = datetime('now'), updated_at = datetime('now')
WHERE id = ?""",
(note, g.member["id"], submission_id),
)
flash("Devuelto al autor con tu motivo.", "ok")
return redirect(url_for("submissions.index"))
# --- helpers --------------------------------------------------------------
def _store_picture(staged: list[dict]) -> str | None:
"""Write the one picture to disk without an `attachments` row.
A submission carries at most one, and `attachments` insists a row belongs to
exactly one of a thread, a comment or a message. Giving it a fourth possible
parent would mean rebuilding that table again — so this follows what a
profile photo already does: a column on the row, a file in the same
directory, and `uploads.remove` when it goes.
"""
if not staged:
return None
item = staged[0]
(uploads.directory() / item["stored_name"]).write_bytes(item["data"])
return item["stored_name"]
def _back_to_form(item, fields, errors):
for message in errors:
flash(message, "error")
return render_template("submission_form.html", item=item, fields=fields,
categories=content.CATEGORIES), 400

View File

@ -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 -%}
<a class="who-link" href="{{ url_for('profiles_public.show', name=login) }}">{{ name }}</a>
{%- else -%}
{{ name }}
{%- endif -%}
{% endmacro %}

View File

@ -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) %}
<form class="reaction" method="post" action="{{ url_for('board.react') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<input type="hidden" name="kind" value="{{ kind }}">
<input type="hidden" name="id" value="{{ target_id }}">
<input type="hidden" name="back" value="{{ back }}">
<button class="reaction__button {{ 'reaction__button--mine' if state and state.mine }}"
type="submit"
aria-label="{{ 'Quitar mi me gusta' if state and state.mine else 'Me gusta' }}">
<span aria-hidden="true">👍</span>
{% if state and state.count %}<span class="reaction__count">{{ state.count }}</span>{% endif %}
</button>
</form>
{% endmacro %}

View File

@ -16,29 +16,46 @@
<div class="site-bar__inner">
<a class="site-bar__brand" href="/"><span class="site-bar__brand-text">Viena Latina</span></a>
{% if g.member %}
<div class="site-bar__account">
<span class="who">{{ g.member.display_name }}</span>
<form method="post" action="{{ url_for('auth.logout') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish" type="submit">Salir</button>
</form>
</div>
{# <details> rather than a button with a handler: the CSP has no
'unsafe-inline', so a menu that needs onclick="" is a menu that
silently never opens. This one works with the CSS and the HTML
alone. #}
<details class="account">
<summary class="account__name">{{ g.member.display_name }}</summary>
<div class="account__menu">
<a href="{{ url_for('profiles.edit') }}">Mi perfil</a>
<a href="{{ url_for('members.export') }}">Descargar mis datos</a>
<form method="post" action="{{ url_for('auth.logout') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish" type="submit">Salir</button>
</form>
</div>
</details>
{% endif %}
</div>
{% if g.member %}
<nav class="site-bar__pages" aria-label="Secciones">
{# Five entries, and four of them are the same for everybody. The role
only decides whether Gestión is there — it used to decide three of
them, which is how an ordinary member ended up signing in to a wall
and a member list with their own profile and their own private
messages hidden from them. Account items are in the corner menu
above, because "Mi perfil" is not a section of the site. #}
<ul class="page-nav">
<li><a href="{{ url_for('board.threads') }}">Mensajes</a></li>
{% if g.member.role in ('owner', 'admin') %}
<li><a href="{{ url_for('home.index') }}">Inicio</a></li>
<li><a href="{{ url_for('board.threads') }}">Muro</a></li>
<li>
{# "Mensajes" is the public board, so this cannot be called that.
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 unread = unread_private() %}{% if unread %} <span class="tag">{{ unread }}</span>{% endif %}</a>
</li>
<li><a href="{{ url_for('content.index') }}">Contenido</a></li>
<li>
{# The badge counts what is waiting for a moderator, so for
anybody else the function returns 0 and nothing is drawn. #}
<a href="{{ url_for('submissions.index') }}">Publicaciones{% set waiting = pending_review() %}{% if waiting %} <span class="tag">{{ waiting }}</span>{% endif %}</a>
</li>
{% if g.member.role in ('owner', 'admin') %}
<li><a href="{{ url_for('home.gestion') }}">Gestión</a></li>
{% endif %}
<li><a href="{{ url_for('members.index') }}">Miembros</a></li>
</ul>
</nav>
{% endif %}
@ -57,7 +74,7 @@
<footer class="site-foot">
<a href="/">Ir al sitio público</a>
{% if g.member %} · <a href="{{ url_for('members.export') }}">Descargar mis datos</a>{% endif %}
{% if g.member %} · <a href="{{ url_for('members.index') }}">Miembros</a>{% endif %}
<div class="site-foot__legal">Viena Latina © {{ current_year }} · Área privada</div>
</footer>
</div>

View File

@ -7,7 +7,7 @@
<h1>Editar respuesta</h1>
<label for="body">Mensaje</label>
<textarea id="body" name="body" rows="10" required>{{ comment.body_md }}</textarea>
<textarea id="body" data-markdown name="body" rows="10" required>{{ comment.body_md }}</textarea>
<div class="actions">
<button class="btn" type="submit">Guardar</button>

View File

@ -20,8 +20,14 @@
<input type="hidden" name="sha" value="{{ item.sha }}">
<input type="hidden" name="name" value="{{ item.name }}">
{% endif %}
{# The byline travels with the document, like the date and the image path.
An edit keeps whoever wrote it; only publishing sets it. #}
{% if f and f.author %}
<input type="hidden" name="author" value="{{ f.author }}">
<input type="hidden" name="author_url" value="{{ f.author_url or '' }}">
{% endif %}
<h1>{{ 'Editar' if item else 'Nuevo' }} {{ meta.singular|lower }}</h1>
<h1>{{ ('Editar ' ~ meta.singular|lower) if item else meta.new_label }}</h1>
<label for="title">Título</label>
<input id="title" name="title" maxlength="140" required value="{{ f.title or '' }}">
@ -31,6 +37,34 @@
<input id="date" name="date" type="date" required value="{{ f.date or today }}">
{% endif %}
{% if collection == 'page' %}
{# Where this page sits in the public menu. The menu is built from the pages
themselves, so a page published here appears on the site by itself —
choosing a parent puts it in the submenu under that page instead of on the
top row. The choice is made once and holds in the three languages. #}
<label for="parent">En el menú</label>
{% set names = parents | map(attribute='base') | list %}
<select id="parent" name="parent">
<option value="">En la barra principal</option>
{% if f.parent and f.parent not in names %}
{# The page it hung under has been deleted, or the git server could not be
reached to list them. Either way the relationship is kept and said out
loud, rather than dropped silently by the next save. #}
<option value="{{ f.parent }}" selected>Dentro de «{{ f.parent }}» (no encontrada)</option>
{% endif %}
{% for other in parents %}
<option value="{{ other.base }}" {{ 'selected' if f.parent == other.base }}>
Dentro de «{{ other.title }}»
</option>
{% endfor %}
</select>
<label for="weight">Orden</label>
<input id="weight" name="weight" type="number" min="0" max="999"
value="{{ f.weight or 50 }}">
<p class="muted small">Menor número, más a la izquierda. 50 si da igual.</p>
{% endif %}
{% if collection == 'post' %}
<fieldset class="fieldset">
<legend>Categorías</legend>
@ -45,6 +79,11 @@
<label for="description">Resumen</label>
<textarea id="description" name="description" rows="2">{{ f.description or '' }}</textarea>
<p class="muted small">
Una o dos frases que se entiendan solas: es lo que aparece en los
listados, en WhatsApp al compartir el enlace y lo que citan los
buscadores. Mejor concreta («El sábado 12 en Ottakring») que general.
</p>
<label for="picture">Imagen destacada</label>
{% if f.image %}
@ -52,12 +91,28 @@
<input type="hidden" name="image" value="{{ f.image }}">
{% endif %}
<input id="picture" name="picture" type="file" accept="image/*">
<label for="image_alt">Texto alternativo de la imagen</label>
<input id="image_alt" name="image_alt" maxlength="200" value="{{ f.image_alt or '' }}">
<p class="muted small">
Qué se ve en la foto, en una frase. Lo lee quien no puede ver la imagen y
lo leen también los buscadores.
</p>
{% endif %}
<label for="body">Cuerpo</label>
<textarea id="body" name="body" rows="18" required
<textarea id="body" data-markdown name="body" rows="18" required
placeholder="Markdown: **negrita**, ## títulos, listas, [enlaces](https://…).">{{ body }}</textarea>
<label for="faq">Preguntas frecuentes <span class="muted small">(opcional)</span></label>
<textarea id="faq" name="faq" rows="5"
placeholder="¿Dónde es?|En la plaza de Ottakring, junto al mercado.">{{ f.faq or '' }}</textarea>
<p class="muted small">
Una por línea, con el formato <span class="mono">pregunta|respuesta</span>.
Se muestran al final de la página y son lo que mejor citan los buscadores
y los asistentes de IA: pregunta concreta, respuesta corta y verificable.
</p>
<label class="check">
<input type="checkbox" name="manual_translation" {{ 'checked' if f.manual_translation }}>
Traducción manual — no generar alemán ni portugués para esto

View File

@ -4,9 +4,7 @@
{% block main %}
<div class="feed-head">
<h1>Contenido</h1>
<a class="btn" href="{{ url_for('content.new', collection=collection) }}">
Nuevo {{ meta.singular|lower }}
</a>
<a class="btn" href="{{ url_for('content.new', collection=collection) }}">{{ meta.new_label }}</a>
</div>
<nav class="tabs" aria-label="Tipo de contenido">
@ -34,14 +32,22 @@
</td>
{% if meta.dated %}<td>{{ item.date }}</td>{% endif %}
<td>{{ item.categories }}</td>
<td class="actions actions--row">
<a class="linkish" href="{{ url_for('content.edit', collection=collection, name=item.name) }}">Editar</a>
<form method="post"
action="{{ url_for('content.delete', collection=collection, name=item.name) }}"
data-confirm="Se eliminará «{{ item.title }}» del sitio público. ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish linkish--danger" type="submit">Eliminar</button>
</form>
{# The flex row goes INSIDE the cell, never on it. `.actions` is
display:flex, and a <td> told to be a flex container stops being a
table cell: it leaves the row's layout and draws its bottom border
at its own height, so the columns' lines no longer meet. The page
still renders, which is why this survived two rounds of looking at
it. test_templates.py now fails if it comes back. #}
<td>
<div class="actions actions--row">
<a class="linkish" href="{{ url_for('content.edit', collection=collection, name=item.name) }}">Editar</a>
<form method="post"
action="{{ url_for('content.delete', collection=collection, name=item.name) }}"
data-confirm="Se eliminará «{{ item.title }}» del sitio público. ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish linkish--danger" type="submit">Eliminar</button>
</form>
</div>
</td>
</tr>
{% endfor %}

View File

@ -1,28 +1,29 @@
{% extends "base.html" %}
{% from "_person.html" import person %}
{% from "_attachments.html" import attachments %}
{% block title %}{{ other.display_name if other else 'Conversación' }}{% endblock %}
{% block title %}{{ other.display_name }}{% endblock %}
{% block main %}
<div class="feed-head">
<h1>{{ other.display_name if other else 'Miembro eliminado' }}</h1>
<h1>{{ person(other.display_name, other.gitea_login, other.profile_published) }}</h1>
<a class="linkish" href="{{ url_for('messages.inbox') }}">Volver</a>
</div>
{% for m in messages %}
<article class="card card--comment">
<div class="card__meta">
<span>{{ m.author }}</span> · <time>{{ m.created_at }}</time>
<span>{{ person(m.author, m.author_login, m.author_published) }}</span> · <time>{{ m.created_at }}</time>
</div>
<div class="prose">{{ to_html(m.body_md) }}</div>
{{ attachments(images.get(m.id, [])) }}
</article>
{% else %}
<p class="muted">Todavía no os habéis escrito. Empieza abajo.</p>
{% endfor %}
<span id="final"></span>
{% if other is none %}
<p class="muted">Esta persona ya no está en la comunidad.</p>
{% elif blocked %}
{% if blocked %}
<p class="muted">
Hay un bloqueo entre vosotros, así que ninguno de los dos puede escribir.
</p>
@ -34,11 +35,14 @@
Si el bloqueo lo puso la otra persona, esto no lo quita.
</p>
{% else %}
{# Always on this page, under the history. There is no separate step to "open"
a conversation: arriving at somebody's name is opening it, and nothing is
created in the database until the first message is actually sent. #}
<form class="card" method="post" enctype="multipart/form-data"
action="{{ url_for('messages.send', conversation_id=conversation_id) }}">
action="{{ url_for('messages.talk', member_id=other.id) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label for="body">Mensaje</label>
<textarea id="body" name="body" rows="4"
<textarea id="body" data-markdown name="body" rows="4" autofocus
placeholder="Se puede usar Markdown: **negrita**, listas, enlaces."></textarea>
<label for="pictures">Imágenes <span class="muted small">(opcional)</span></label>

View File

@ -5,6 +5,6 @@
<article class="card card--center">
<h1>{{ code }}</h1>
<p class="muted">{{ message }}</p>
<a class="btn" href="{{ url_for('board.threads') }}">Volver a los mensajes</a>
<a class="btn" href="{{ url_for('home.index') }}">Volver a Inicio</a>
</article>
{% endblock %}

View File

@ -0,0 +1,63 @@
{% extends "base.html" %}
{% block title %}Gestión{% endblock %}
{% block main %}
<div class="feed-head">
<h1>Gestión</h1>
</div>
<p class="muted">
Lo que sólo hace la administración. Todo lo demás — el muro, los privados,
las publicaciones — está en las otras secciones y funciona igual para ti que
para cualquier miembro.
</p>
<section class="panel">
<div class="panel__head">
<h2>Miembros</h2>
<a class="linkish" href="{{ url_for('members.index') }}">Abrir</a>
</div>
<p class="panel__row">
{{ counts.members }} en total · {{ counts.moderators }} pueden moderar
{% if counts.suspended %} · {{ counts.suspended }} suspendido{{ '' if counts.suspended == 1 else 's' }}{% endif %}
</p>
<p class="muted small">
Dar de alta, invitar de nuevo, cambiar el rol, suspender y eliminar.
</p>
</section>
<section class="panel">
<div class="panel__head">
<h2>Artículos publicados</h2>
<a class="linkish" href="{{ url_for('content.index', collection='post') }}">Abrir</a>
</div>
<p class="muted small">
Lo que ya está en vienalatina.com: editar, corregir o retirar. Para
publicar algo nuevo, o para revisar lo que proponen los miembros, está
<a href="{{ url_for('submissions.index') }}">Publicaciones</a>.
</p>
</section>
<section class="panel">
<div class="panel__head">
<h2>Páginas del sitio</h2>
<a class="linkish" href="{{ url_for('content.index', collection='page') }}">Abrir</a>
</div>
<p class="muted small">
Acerca de, contacto y las demás páginas fijas de vienalatina.com. Las
publicaciones no están aquí: eso es
<a href="{{ url_for('submissions.index') }}">Publicaciones</a>, que los
moderadores comparten contigo.
</p>
</section>
{% if counts.pending %}
<section class="panel panel--attention">
<div class="panel__head">
<h2>Pendiente de revisar</h2>
<a class="linkish" href="{{ url_for('submissions.index') }}">Ver</a>
</div>
<p class="panel__row">{{ counts.pending }} propuesta{{ '' if counts.pending == 1 else 's' }} esperando a un moderador.</p>
</section>
{% endif %}
{% endblock %}

View File

@ -0,0 +1,83 @@
{% extends "base.html" %}
{% from "_person.html" import person %}
{% block title %}Inicio{% endblock %}
{% block main %}
<div class="feed-head">
<h1>Hola, {{ g.member.display_name }}</h1>
<span class="muted small">{{ people }} miembro{{ '' if people == 1 else 's' }} activo{{ '' if people == 1 else 's' }}</span>
</div>
{# Panels in the order things get acted on: what is waiting for me, then what
is waiting for everybody, then what I have sent somewhere. #}
{% if queue %}
<section class="panel panel--attention">
<div class="panel__head">
<h2>Para revisar</h2>
<a class="linkish" href="{{ url_for('submissions.index') }}">Ver la cola</a>
</div>
{% for item in queue %}
<p class="panel__row">
<a href="{{ url_for('submissions.show', submission_id=item.id) }}">{{ item.title }}</a>
<span class="muted small">{{ person(item.author, item.author_login, item.author_published) }} · {{ item.created_at }}</span>
</p>
{% endfor %}
</section>
{% endif %}
<section class="panel">
<div class="panel__head">
<h2>Privados</h2>
<a class="linkish" href="{{ url_for('messages.inbox') }}">Todos</a>
</div>
{% if not conversations %}
<p class="muted">Todavía no tienes conversaciones. Escribe a alguien desde Privados.</p>
{% endif %}
{% for c in conversations %}
<p class="panel__row">
<a href="{{ url_for('messages.talk', member_id=c.other_id) }}">{{ c.other_name }}</a>
{% if c.unread %}<span class="tag">{{ c.unread }}</span>{% endif %}
{% if c.last_at %}<span class="muted small">{{ c.last_at }}</span>{% endif %}
</p>
{% endfor %}
</section>
<section class="panel">
<div class="panel__head">
<h2>Muro</h2>
<a class="linkish" href="{{ url_for('board.threads') }}">Todo el muro</a>
</div>
{% if not threads %}
<p class="muted">El muro está vacío. <a href="{{ url_for('board.new_thread') }}">Escribe el primero.</a></p>
{% endif %}
{% for t in threads %}
<p class="panel__row">
<a href="{{ url_for('board.thread', thread_id=t.id) }}">{{ t.title }}</a>
<span class="muted small">{{ person(t.author, t.author_login, t.author_published) }} · {{ t.replies }} respuesta{{ '' if t.replies == 1 else 's' }}</span>
</p>
{% endfor %}
</section>
<section class="panel">
<div class="panel__head">
<h2>Mis publicaciones</h2>
<a class="linkish" href="{{ url_for('submissions.index') }}">Publicaciones</a>
</div>
{% if not mine %}
<p class="muted">
{% if may_moderate() %}
Puedes publicar directamente en el sitio desde <a href="{{ url_for('content.index') }}">Publicaciones</a>.
{% else %}
¿Tienes algo que contarle al barrio? <a href="{{ url_for('submissions.propose') }}">Propón una publicación</a>
y un moderador la leerá antes de publicarla.
{% endif %}
</p>
{% endif %}
{% for item in mine %}
<p class="panel__row">
<a href="{{ url_for('submissions.show', submission_id=item.id) }}">{{ item.title }}</a>
<span class="tag tag--{{ item.state }}">{{ state_labels[item.state] }}</span>
</p>
{% endfor %}
</section>
{% endblock %}

View File

@ -7,15 +7,16 @@
</div>
{% if people %}
<form class="card" method="post" action="{{ url_for('messages.start') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
{# GET, not POST: choosing somebody to write to is navigation, not a change.
It also means no conversation is created just because a name was picked. #}
<form class="card" method="get" action="{{ url_for('messages.pick') }}">
<label for="para">Escribir a</label>
<select id="para" name="member_id">
{% for person in people %}
<option value="{{ person.id }}">{{ person.display_name }}</option>
{% endfor %}
</select>
<button class="btn" type="submit">Abrir conversación</button>
<button class="btn" type="submit">Escribir</button>
</form>
{% endif %}
@ -25,7 +26,7 @@
{% for c in conversations %}
<article class="card">
<a class="card__title" href="{{ url_for('messages.conversation', conversation_id=c.id) }}">
<a class="card__title" href="{{ url_for('messages.talk', member_id=c.other_id) }}">
{{ c.other_name }}
{% if c.unread %}<span class="tag">{{ c.unread }}</span>{% endif %}
</a>

View File

@ -29,15 +29,16 @@
</p>
{% endif %}
{% if can_make_admin %}
<label for="role">Rol</label>
<select id="role" name="role">
<option value="user">Usuario</option>
<option value="admin">Administrador</option>
<option value="user">Miembro — escribe en el muro y propone publicaciones</option>
<option value="moderator">Moderador — además aprueba lo que proponen</option>
{% if can_make_admin %}
<option value="admin">Administrador — además gestiona miembros y páginas</option>
{% endif %}
</select>
{% else %}
<input type="hidden" name="role" value="user">
<p class="muted small">Los administradores sólo pueden dar de alta usuarios.</p>
{% if not can_make_admin %}
<p class="muted small">Sólo el responsable puede nombrar administradores.</p>
{% endif %}
<div class="actions">

View File

@ -1,4 +1,5 @@
{% extends "base.html" %}
{% from "_person.html" import person %}
{% block title %}Miembros{% endblock %}
{% set me = g.member %}
@ -13,73 +14,127 @@
{% endif %}
</div>
<table class="table">
<thead>
<tr><th>Nombre</th><th>Usuario</th><th>Rol</th><th>Estado</th>{% if is_admin %}<th></th>{% endif %}</tr>
</thead>
<tbody>
{# 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 <details> so that the page is
a directory first and a control panel second. #}
<ul class="people">
{% for m in members %}
<tr class="{{ '' if m.active else 'row--off' }}">
<td>{{ m.display_name }}{% if m.id == me.id %} <span class="muted small">(tú)</span>{% endif %}</td>
<td class="mono">{{ m.gitea_login }}</td>
<td>{{ labels[m.role] }}</td>
<td>{{ 'Activo' if m.active else 'Suspendido' }}</td>
{% if is_admin %}
<td class="actions actions--row">
{# The owner is untouchable, so the row shows nothing rather than
buttons that would only produce a 403. #}
{% if m.role != 'owner' %}
<form method="post" action="{{ url_for('members.set_active', member_id=m.id) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<input type="hidden" name="active" value="{{ 0 if m.active else 1 }}">
<button class="linkish" type="submit">{{ 'Suspender' if m.active else 'Reactivar' }}</button>
</form>
{# 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 %}
<form method="post" action="{{ url_for('members.invite', member_id=m.id) }}"
data-confirm="Se enviará un enlace nuevo a {{ m.email }} y el anterior dejará de servir. ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish" type="submit">Enviar invitación</button>
</form>
{% endif %}
{% if is_owner %}
<form method="post" action="{{ url_for('members.set_role', member_id=m.id) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<input type="hidden" name="role" value="{{ 'user' if m.role == 'admin' else 'admin' }}">
<button class="linkish" type="submit">{{ 'Hacer usuario' if m.role == 'admin' else 'Hacer administrador' }}</button>
</form>
{% if m.role == 'admin' and m.active %}
<form method="post" action="{{ url_for('members.transfer', member_id=m.id) }}"
data-confirm="Vas a dejar de ser el responsable y {{ m.display_name }} pasará a serlo. ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish" type="submit">Transferir titularidad</button>
</form>
{% endif %}
<form method="post" action="{{ url_for('members.erase', member_id=m.id) }}"
data-confirm="Se borrarán sus datos personales. Sus mensajes quedarán como «Miembro eliminado». ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish linkish--danger" type="submit">Eliminar</button>
</form>
{% endif %}
{% endif %}
</td>
<li class="person-card {{ '' if m.active else 'person-card--off' }}">
<div class="person-card__head">
{% if m.photo_name %}
<img class="person-card__photo"
src="{{ url_for('profiles.member_photo', stored_name=m.photo_name) }}"
alt="" loading="lazy">
{% else %}
{# Their initial rather than a silhouette: a placeholder that is at
least theirs. #}
<span class="person-card__photo person-card__photo--none" aria-hidden="true">
{{ m.display_name[:1]|upper }}
</span>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
<div class="person-card__who">
<h2 class="person-card__name">
{{ person(m.display_name, m.gitea_login, m.profile_published) }}
{% if m.id == me.id %}<span class="muted small">(tú)</span>{% endif %}
</h2>
{# The username is shown to everyone: it is not a secret, it is
their address — vienalatina.com/<usuario> — and somebody
looking for a person's page needs to know how it is spelled.
The email stays inside the admin block. #}
<p class="muted small">
<span class="mono">{{ m.gitea_login }}</span> · {{ labels[m.role] }}
{% if not m.active %} · Suspendido{% endif %}
{% if m.posts %} · {{ m.posts }} en el muro{% endif %}
</p>
</div>
</div>
{% if m.bio %}<p class="person-card__bio">{{ m.bio.split('\n')[0][:160] }}</p>{% endif %}
<div class="person-card__foot">
{% if m.id != me.id and m.active %}
<a class="linkish" href="{{ url_for('messages.talk', member_id=m.id) }}">Escribir</a>
{% endif %}
{% if m.profile_published %}
<a class="linkish" href="{{ url_for('profiles_public.show', name=m.gitea_login) }}">Su página</a>
{% elif m.id == me.id %}
<a class="linkish" href="{{ url_for('profiles.edit') }}">Editar mi perfil</a>
{% endif %}
</div>
{% if is_admin and m.role != 'owner' %}
{# A <details>, not a script: the CSP has no 'unsafe-inline'. Closed by
default, so the directory reads as a directory. #}
<details class="person-card__admin">
<summary>Gestionar</summary>
<div class="person-card__actions">
<form method="post" action="{{ url_for('members.set_active', member_id=m.id) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<input type="hidden" name="active" value="{{ 0 if m.active else 1 }}">
<button class="linkish" type="submit">{{ 'Suspender' if m.active else 'Reactivar' }}</button>
</form>
{# 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 %}
<form method="post" action="{{ url_for('members.invite', member_id=m.id) }}"
data-confirm="Se enviará un enlace nuevo a {{ m.email }} y el anterior dejará de servir. ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish" type="submit">Enviar invitación</button>
</form>
{% endif %}
{% if is_owner or m.role != 'admin' %}
<form class="inline-form" method="post"
action="{{ url_for('members.set_role', member_id=m.id) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label class="sr-only" for="role-{{ m.id }}">Rol de {{ m.display_name }}</label>
<select id="role-{{ m.id }}" name="role">
<option value="user" {{ 'selected' if m.role == 'user' }}>Miembro</option>
<option value="moderator" {{ 'selected' if m.role == 'moderator' }}>Moderador</option>
{% if is_owner %}
<option value="admin" {{ 'selected' if m.role == 'admin' }}>Administrador</option>
{% endif %}
</select>
<button class="linkish" type="submit">Cambiar rol</button>
</form>
{% endif %}
{% if is_owner %}
{% if m.role == 'admin' and m.active %}
<form method="post" action="{{ url_for('members.transfer', member_id=m.id) }}"
data-confirm="Vas a dejar de ser el responsable y {{ m.display_name }} pasará a serlo. ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish" type="submit">Transferir titularidad</button>
</form>
{% endif %}
<form method="post" action="{{ url_for('members.erase', member_id=m.id) }}"
data-confirm="Se borrarán sus datos personales. Sus mensajes quedarán como «Miembro eliminado». ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish linkish--danger" type="submit">Eliminar</button>
</form>
{% endif %}
{% if m.email %}<p class="muted small">{{ m.email }}</p>{% endif %}
</div>
</details>
{% endif %}
</li>
{% endfor %}
</ul>
{% if is_admin %}
<p class="muted small">
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.
</p>
{% endif %}
{% endblock %}

View File

@ -0,0 +1,42 @@
{# 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.
Its styling lives in static/profile.css and NOT in a <style> block here.
The Content-Security-Policy has no 'unsafe-inline', so an inline block is
ignored by the browser without a word, and the page arrives looking like
1996. test_templates.py fails the build if one reappears. #}
<!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] }}">
<link rel="stylesheet" href="{{ url_for('static', filename='profile.css') }}">
</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,62 @@
{% 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" data-markdown 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 %}
<p class="muted small">
Tu foto aparece en <a href="{{ url_for('members.index') }}">Miembros</a>,
que sólo ven las personas que han entrado. Fuera del sitio sólo se ve si
publicas tu página, abajo.
</p>
<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,74 @@
{% extends "base.html" %}
{% from "_person.html" import person %}
{% block title %}{{ item.title }}{% endblock %}
{% block main %}
<div class="feed-head">
<h1>{{ item.title }}</h1>
<a class="linkish" href="{{ url_for('submissions.index') }}">Volver</a>
</div>
<article class="card">
<div class="card__meta">
<span class="tag tag--{{ item.state }}">{{ labels[item.state] }}</span>
<span>{{ person(item.author, item.author_login, item.author_published) }}</span> · <time>{{ item.created_at }}</time>
{% if item.categories %} · <span>{{ item.categories }}</span>{% endif %}
</div>
{% if item.description %}<p class="muted">{{ item.description }}</p>{% endif %}
{% if item.photo_name %}
<img class="attachment"
src="{{ url_for('submissions.photo', stored_name=item.photo_name) }}"
alt="Imagen de «{{ item.title }}»">
{% endif %}
<div class="prose">{{ body_html }}</div>
</article>
{% if item.state == 'rejected' and item.note %}
<article class="card">
<h2>Motivo de la devolución</h2>
<p>{{ item.note }}</p>
{% if item.reviewer %}<p class="muted small">— {{ item.reviewer }}, {{ item.reviewed_at }}</p>{% endif %}
</article>
{% endif %}
{% if item.state == 'approved' %}
<p class="muted">
Publicado{% if item.reviewer %} por {{ item.reviewer }}{% endif %}{% if item.published_path %} en <span class="mono">{{ item.published_path }}</span>{% endif %}.
La traducción al alemán y al portugués tarda un par de minutos.
</p>
{% endif %}
{% if can_moderate and item.state != 'approved' %}
{# Approve and reject are two forms rather than one with a choice: they are not
variations of the same action, and the reason is required for only one. #}
<form class="card" method="post"
action="{{ url_for('submissions.approve', submission_id=item.id) }}"
data-confirm="Se publicará en vienalatina.com con el nombre de {{ item.author }}. ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<p class="muted small">
Al aprobar se publica tal cual está, firmado por {{ item.author }} — en el
sitio y en el historial del repositorio.
</p>
<button class="btn" type="submit">Aprobar y publicar</button>
</form>
<form class="card" method="post" action="{{ url_for('submissions.reject', submission_id=item.id) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label for="note">Devolver con un motivo</label>
<textarea id="note" name="note" rows="3"
placeholder="Qué hay que cambiar para que se pueda publicar."></textarea>
<button class="linkish" type="submit">Devolver al autor</button>
</form>
{% endif %}
{% if mine and item.state != 'approved' %}
<div class="actions">
<a class="btn" href="{{ url_for('submissions.edit', submission_id=item.id) }}">Editar</a>
<form method="post" action="{{ url_for('submissions.withdraw', submission_id=item.id) }}"
data-confirm="Se borrará la propuesta. ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish linkish--danger" type="submit">Retirar</button>
</form>
</div>
{% endif %}
{% endblock %}

View File

@ -0,0 +1,55 @@
{% extends "base.html" %}
{% block title %}{{ 'Editar propuesta' if item else 'Proponer una publicación' }}{% endblock %}
{% block main %}
<div class="feed-head">
<h1>{{ 'Editar propuesta' if item else 'Proponer una publicación' }}</h1>
</div>
<p class="muted">
Esto no es el muro: va a vienalatina.com, en español, y se traduce solo al
alemán y al portugués. Un moderador lo lee antes de que salga.
</p>
<form class="card" method="post" enctype="multipart/form-data"
action="{{ url_for('submissions.edit', submission_id=item.id) if item else url_for('submissions.propose') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label for="title">Título</label>
<input id="title" name="title" type="text" required maxlength="140"
value="{{ fields.title if fields else '' }}">
<label for="description">Resumen <span class="muted small">(opcional)</span></label>
<input id="description" name="description" type="text" maxlength="300"
value="{{ fields.description if fields else '' }}">
<p class="muted small">Una o dos líneas: es lo que se ve en los listados.</p>
<fieldset class="choices">
<legend>Categorías</legend>
{% for category in categories %}
<label class="choice">
<input type="checkbox" name="categories" value="{{ category }}"
{{ 'checked' if fields and category in fields.categories }}>
{{ category }}
</label>
{% endfor %}
</fieldset>
<label for="body">Texto</label>
<textarea id="body" data-markdown name="body" rows="16" required
placeholder="Se puede usar Markdown: **negrita**, ## títulos, listas, enlaces.">{{ fields.body if fields else '' }}</textarea>
<label for="picture">Imagen <span class="muted small">(opcional)</span></label>
<input id="picture" name="picture" type="file" accept="image/*">
{% if item and item.photo_name %}
<p class="muted small">
Ya tiene una imagen. Si eliges otra, la sustituye.
</p>
{% endif %}
<div class="actions">
<button class="btn" type="submit">{{ 'Guardar' if item else 'Enviar a revisión' }}</button>
<a class="linkish" href="{{ url_for('submissions.index') }}">Cancelar</a>
</div>
</form>
{% endblock %}

View File

@ -0,0 +1,92 @@
{% extends "base.html" %}
{% from "_person.html" import person %}
{% block title %}Publicaciones{% endblock %}
{% block main %}
<div class="feed-head">
<h1>Publicaciones</h1>
{% if can_moderate %}
{# A moderator cannot open Gestión, so this is their only route to what is
already on the site. It was a clause inside a paragraph below, which is
the same as not being there. #}
<div class="feed-head__actions">
<a class="linkish" href="{{ url_for('content.index', collection='post') }}">Ya publicado</a>
<a class="btn" href="{{ url_for('content.new', collection='post') }}">Publicar</a>
</div>
{% else %}
<a class="btn" href="{{ url_for('submissions.propose') }}">Proponer</a>
{% endif %}
</div>
<p class="muted">
{% if can_moderate %}
Lo que publicas aquí sale al sitio en cuanto lo guardas. Lo que proponen los
miembros espera en esta cola hasta que tú u otro moderador lo apruebe.
{% else %}
Esto va a vienalatina.com, donde lo lee cualquiera. Un moderador lo lee
primero: si hace falta cambiar algo te lo devuelve con el motivo.
{% endif %}
</p>
{% if can_moderate %}
<h2 class="section-head">Esperando revisión</h2>
{% if not queue %}
<article class="card"><p class="muted">Nada pendiente. La cola está vacía.</p></article>
{% endif %}
{% for item in queue %}
<article class="card">
<div class="card__meta">
<span>{{ person(item.author, item.author_login, item.author_published) }}</span> · <time>{{ item.created_at }}</time>
</div>
<h3 class="card__title">
<a href="{{ url_for('submissions.show', submission_id=item.id) }}">{{ item.title }}</a>
</h3>
<p class="card__excerpt">{{ excerpt(item.body_md) }}</p>
<div class="card__foot actions actions--row">
<a class="linkish" href="{{ url_for('submissions.show', submission_id=item.id) }}">Leer y revisar</a>
</div>
</article>
{% endfor %}
{% endif %}
<h2 class="section-head">Lo que he propuesto</h2>
{% if not mine %}
<article class="card">
<p class="muted">
{% if can_moderate %}
Nada. Tus publicaciones no pasan por aquí: van directas al sitio.
{% else %}
Todavía no has propuesto nada.
{% endif %}
</p>
</article>
{% endif %}
{% for item in mine %}
<article class="card">
<div class="card__meta">
<span class="tag tag--{{ item.state }}">{{ labels[item.state] }}</span>
<time>{{ item.created_at }}</time>
</div>
<h3 class="card__title">
<a href="{{ url_for('submissions.show', submission_id=item.id) }}">{{ item.title }}</a>
</h3>
{% if item.state == 'rejected' and item.note %}
{# The reason, on the list rather than one click away: it is the only thing
the author needs in order to know what to do next. #}
<p class="card__excerpt"><strong>Motivo:</strong> {{ item.note }}</p>
{% endif %}
<div class="card__foot actions actions--row">
{% if item.state != 'approved' %}
<a class="linkish" href="{{ url_for('submissions.edit', submission_id=item.id) }}">Editar</a>
<form method="post" action="{{ url_for('submissions.withdraw', submission_id=item.id) }}"
data-confirm="Se borrará la propuesta «{{ item.title }}». ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="linkish linkish--danger" type="submit">Retirar</button>
</form>
{% elif item.published_path %}
<span class="muted small">Publicado en {{ item.published_path }}</span>
{% endif %}
</div>
</article>
{% endfor %}
{% endblock %}

View File

@ -1,4 +1,6 @@
{% extends "base.html" %}
{% from "_person.html" import person %}
{% from "_reaction.html" import reaction %}
{% from "_attachments.html" import attachments %}
{% block title %}{{ thread.title }}{% endblock %}
@ -7,7 +9,7 @@
<div class="card__meta">
{% if thread.pinned %}<span class="tag">Fijado</span>{% endif %}
{% if thread.locked %}<span class="tag tag--quiet">Cerrado</span>{% endif %}
<span>{{ author }}</span> · <time>{{ thread.created_at }}</time>
<span>{{ person(author.display_name, author.gitea_login, author.profile_published) }}</span> · <time>{{ thread.created_at }}</time>
{% if thread.edited_at %}<span class="muted small">(editado)</span>{% endif %}
</div>
<h1 class="card__title">{{ thread.title }}</h1>
@ -15,6 +17,8 @@
{{ attachments(thread_images) }}
<div class="actions">
{{ reaction('thread', thread.id, reactions.get(thread.id),
url_for('board.thread', thread_id=thread.id)) }}
{% if may_edit(thread) %}
<a class="linkish" href="{{ url_for('board.edit_thread', thread_id=thread.id) }}">Editar</a>
{% endif %}
@ -45,14 +49,16 @@
<h2 class="section-head">{{ comments|length }} respuesta{{ '' if comments|length == 1 else 's' }}</h2>
{% for c in comments %}
<article class="card card--comment">
<article class="card card--comment" id="c{{ c.id }}">
<div class="card__meta">
<span>{{ c.author }}</span> · <time>{{ c.created_at }}</time>
<span>{{ person(c.author, c.author_login, c.author_published) }}</span> · <time>{{ c.created_at }}</time>
{% if c.edited_at %}<span class="muted small">(editado)</span>{% endif %}
</div>
<div class="prose">{{ to_html(c.body_md) }}</div>
{{ attachments(comment_images.get(c.id, [])) }}
<div class="actions">
{{ reaction('comment', c.id, comment_reactions.get(c.id),
url_for('board.thread', thread_id=thread.id) ~ '#c' ~ c.id) }}
{% if may_edit(c) %}
<a class="linkish" href="{{ url_for('board.edit_comment', comment_id=c.id) }}">Editar</a>
{% endif %}
@ -75,7 +81,7 @@
action="{{ url_for('board.comment', thread_id=thread.id) }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<label for="body">Responder</label>
<textarea id="body" name="body" rows="5" required
<textarea id="body" data-markdown name="body" rows="5" required
placeholder="Se puede usar Markdown: **negrita**, listas, enlaces."></textarea>
<label for="pictures">Imágenes <span class="muted small">(opcional)</span></label>

View File

@ -12,7 +12,7 @@
value="{{ thread.title if thread else '' }}">
<label for="body">Mensaje</label>
<textarea id="body" name="body" rows="14" required
<textarea id="body" data-markdown name="body" rows="14" required
placeholder="Se puede usar Markdown: **negrita**, listas, enlaces.">{{ thread.body_md if thread else '' }}</textarea>
{# Only when writing, not when editing: the edit route does not read files,

View File

@ -1,15 +1,17 @@
{% extends "base.html" %}
{% block title %}Mensajes{% endblock %}
{% from "_person.html" import person %}
{% from "_reaction.html" import reaction %}
{% block title %}Muro{% endblock %}
{% block main %}
<div class="feed-head">
<h1>Mensajes</h1>
<h1>Muro</h1>
<a class="btn" href="{{ url_for('board.new_thread') }}">Escribir</a>
</div>
{% if not threads %}
<article class="card">
<p class="muted">Todavía no hay mensajes. Escribe el primero.</p>
<p class="muted">Todavía no hay nada en el muro. Escribe el primero.</p>
</article>
{% endif %}
@ -18,13 +20,16 @@
<div class="card__meta">
{% if t.pinned %}<span class="tag">Fijado</span>{% endif %}
{% if t.locked %}<span class="tag tag--quiet">Cerrado</span>{% endif %}
<span>{{ t.author }}</span> · <time>{{ t.created_at }}</time>
<span>{{ person(t.author, t.author_login, t.author_published) }}</span> · <time>{{ t.created_at }}</time>
</div>
<h2 class="card__title">
<a href="{{ url_for('board.thread', thread_id=t.id) }}">{{ t.title }}</a>
</h2>
<p class="card__excerpt">{{ excerpt(t.body_md) }}</p>
<p class="card__foot">{{ t.replies }} respuesta{{ '' if t.replies == 1 else 's' }}</p>
<div class="card__foot">
{{ reaction('thread', t.id, reactions.get(t.id), url_for('board.threads', page=page)) }}
<span>{{ t.replies }} respuesta{{ '' if t.replies == 1 else 's' }}</span>
</div>
</article>
{% endfor %}

View File

@ -108,3 +108,40 @@ def test_the_cooldown_stops_a_double_submit(app, client, post, make_member, sign
post("/comunidad/nuevo", {"title": "Segundo", "body": "Dos"})
count = db.execute("SELECT COUNT(*) AS n FROM threads").fetchone()["n"]
assert count == 1
# --- the preview behind the Vista previa button ---------------------------
#
# A round trip rather than a markdown parser in the browser: the preview has to
# agree with what gets published, and the only way to guarantee that is to
# render it with the same function the board and the site use.
def test_the_preview_renders_the_same_markdown_the_board_does(post, make_member, sign_in):
sign_in(make_member("maria"))
response = post("/comunidad/previsualizar", {"body": "**hola** y _adiós_"})
assert response.status_code == 200
assert response.get_json()["html"] == "<p><strong>hola</strong> y <em>adiós</em></p>\n"
def test_the_preview_drops_html_exactly_as_the_board_does(post, make_member, sign_in):
"""`html=False` in render.py is the whole XSS defence. A preview that
rendered raw HTML would be a hole in the members area and a lie about what
posting is going to do."""
sign_in(make_member("maria"))
html = post("/comunidad/previsualizar",
{"body": "<script>alert(1)</script>"}).get_json()["html"]
assert "<script>" not in html
def test_the_preview_needs_a_session(client):
assert client.post("/comunidad/previsualizar", data={"body": "hola"}).status_code in (302, 400)
def test_the_preview_is_never_cached(post, make_member, sign_in):
sign_in(make_member("maria"))
response = post("/comunidad/previsualizar", {"body": "hola"})
assert response.headers["Cache-Control"] == "no-store"

View File

@ -308,3 +308,294 @@ def test_the_preview_renders_markdown_and_escapes_html(repo, editor, post):
assert "<strong>fuerte</strong>" in page
assert "<script>alert(1)</script>" not in page
assert not repo.files # a preview must not publish anything
# --- who may write which collection --------------------------------------
#
# One blueprint, two answers. A moderator curates what the public reads, so
# posts are theirs. The static pages are the site's own structure — "Acerca de",
# contact — and changing those is an administrator's job. The check lives in
# _collection_or_404, which every route here calls before doing anything.
def test_a_moderator_may_publish_a_post(repo, db, post, make_member, sign_in):
sign_in(make_member("luisa", role="moderator"))
response = post("/comunidad/contenido/post/nuevo",
{"title": "Aviso", "body": "Texto.", "date": "2026-09-25"})
assert response.status_code == 302
assert list(repo.files) == ["content/post/2026-09-25-aviso.es.md"]
def test_a_moderator_may_not_touch_the_static_pages(repo, client, post,
make_member, sign_in):
sign_in(make_member("luisa", role="moderator"))
assert client.get("/comunidad/contenido/page").status_code == 403
assert client.get("/comunidad/contenido/page/nuevo").status_code == 403
assert post("/comunidad/contenido/page/nuevo",
{"title": "Acerca de", "body": "Texto."}).status_code == 403
assert repo.files == {}
def test_a_member_may_not_use_the_editor_at_all(repo, client, post,
make_member, sign_in):
"""Their route to the public site is a proposal, which waits for somebody."""
sign_in(make_member("maria"))
for path in ("/comunidad/contenido", "/comunidad/contenido/post/nuevo",
"/comunidad/contenido/page/nuevo"):
assert client.get(path).status_code == 403, path
assert repo.files == {}
def test_the_tabs_only_offer_what_this_member_may_open(repo, client, make_member, sign_in):
"""A tab that always produces a 403 is worse than no tab."""
sign_in(make_member("luisa", role="moderator"))
assert "Páginas" not in client.get("/comunidad/contenido").get_data(as_text=True)
sign_in(make_member("admina", role="admin"))
assert "Páginas" in client.get("/comunidad/contenido").get_data(as_text=True)
# --- when the git server refuses the token -------------------------------
#
# This is the shape of a real outage, and it went undiagnosed for two phases.
# `_content_request` answered 401/403 with PermissionError, for a caller
# (tokens.py) that had been deleted — so the editor 500ed and approving a
# submission blamed a missing photograph. Both are asserted here, from the
# outside, because both were invisible from the inside.
class RefusingRepo:
"""Gitea with a token that has no repository scope: 403 to everything."""
class Response:
status_code = 403
@staticmethod
def json():
return {}
def request(self, *args, **kwargs):
return self.Response()
@pytest.fixture
def refused(monkeypatch):
monkeypatch.setattr(gitea, "requests", RefusingRepo())
def test_the_editor_says_what_is_wrong_instead_of_500ing(
refused, client, make_member, sign_in):
sign_in(make_member("admina", role="admin"))
for path in ("/comunidad/contenido", "/comunidad/contenido/page"):
response = client.get(path)
assert response.status_code == 200, path
body = response.get_data(as_text=True)
assert "CONTENT_TOKEN" in body and "repository" in body, path
def test_a_refused_write_does_not_escape_as_a_permission_error(
refused, client, post, make_member, sign_in):
"""PermissionError is an OSError, which is how it ended up being reported as
a missing file somewhere else entirely. It must not leave gitea.py."""
sign_in(make_member("admina", role="admin"))
response = post("/comunidad/contenido/post/nuevo",
{"title": "Aviso", "body": "Texto.", "date": "2026-09-25"})
assert response.status_code == 400 # back to the form, not a 500
assert "rechazó el token" in response.get_data(as_text=True)
def test_an_unexpected_error_renders_the_site_is_own_page(app, client, make_member,
sign_in, monkeypatch):
"""Flask's default 500 page is in English, has no way back, and says nothing.
Ours says something and is logged with the path.
PROPAGATE_EXCEPTIONS off on purpose: the fixture sets TESTING, which re-raises
instead of running the handler, and the handler is the subject here."""
app.config["PROPAGATE_EXCEPTIONS"] = False
sign_in(make_member("maria"))
def explode():
raise RuntimeError("something nobody anticipated")
monkeypatch.setattr("apps.board.board.get_db", explode)
response = client.get("/comunidad/muro")
assert response.status_code == 500
body = response.get_data(as_text=True)
assert "Algo falló de nuestro lado" in body
assert "Viena Latina" in body # the site's chrome, not Flask's
# --- the byline ----------------------------------------------------------
#
# The commit has named the author since the editor was built; the page did not,
# so a reader could not tell whose article they were reading. These check the
# three places it can go wrong: publishing, approving somebody else's proposal,
# and editing — where re-signing the post with the editor's name would be worse
# than having no byline at all.
def test_a_published_post_names_its_author(repo, db, post, make_member, sign_in):
import yaml
author = make_member("luisa", role="moderator")
db.execute("UPDATE members SET display_name = ?, profile_published = 1 WHERE id = ?",
("Luisa Fernández", author))
sign_in(author)
publish(post)
path, = repo.files
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
assert front["author"] == "Luisa Fernández"
assert front["author_url"] == "/luisa"
def test_without_a_published_page_the_byline_does_not_link(
repo, db, post, make_member, sign_in):
import yaml
author = make_member("luisa", role="moderator")
db.execute("UPDATE members SET profile_published = 0 WHERE id = ?", (author,))
sign_in(author)
publish(post)
path, = repo.files
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
assert front["author"] == "Luisa"
assert "author_url" not in front # a byline linking to a 404 is worse
def test_editing_a_post_keeps_the_author_it_already_had(
repo, editor, post, client):
"""The one that matters. An admin fixing a typo in somebody's article must
not end up signing it — the same rule the board has about editing other
people's words."""
import yaml
repo.files["content/post/2026-09-25-de-otro.es.md"] = (
"---\ntitle: De otro\ndate: 2026-09-25\nlang: es\n"
"manual_translation: false\nauthor: Salvador Dalí\nauthor_url: /salvador\n"
"---\n\nTexto.\n").encode("utf-8")
page = client.get("/comunidad/contenido/post/editar/2026-09-25-de-otro.es.md")
body = page.get_data(as_text=True)
assert 'name="author" value="Salvador Dalí"' in body
assert 'name="author_url" value="/salvador"' in body
post("/comunidad/contenido/post/editar/2026-09-25-de-otro.es.md",
{"title": "De otro", "body": "Texto corregido.", "date": "2026-09-25",
"sha": repo._sha(repo.files["content/post/2026-09-25-de-otro.es.md"]),
"author": "Salvador Dalí", "author_url": "/salvador"})
front = yaml.safe_load(
repo.files["content/post/2026-09-25-de-otro.es.md"].decode().split("---")[1])
assert front["author"] == "Salvador Dalí"
assert front["author_url"] == "/salvador"
def test_an_author_url_cannot_point_off_the_site(repo, editor, post):
"""It arrives as a hidden field, which is a convention and not a promise."""
import yaml
post("/comunidad/contenido/post/nuevo",
{"title": "Aviso", "body": "Texto.", "date": "2026-09-25",
"author": "Alguien", "author_url": "https://ejemplo.invalid/premio"})
path, = repo.files
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
assert "author_url" not in front
def test_a_page_carries_no_byline(repo, editor, post):
"""Acerca de and Contacto are the site speaking, not a person."""
import yaml
post("/comunidad/contenido/page/nuevo", {"title": "Acerca de", "body": "Texto."})
path, = repo.files
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
assert "author" not in front
# --- where a page sits in the public menu --------------------------------
#
# The menu used to be three names in config.yaml, so a page published here never
# appeared on the site and the three languages had to be kept in step by hand.
# It is built from the pages now, which makes these two fields the whole of the
# navigation: `parent` nests a page under another, `weight` orders them.
def test_a_page_records_where_it_goes_in_the_menu(repo, editor, post):
import yaml
post("/comunidad/contenido/page/nuevo",
{"title": "Estatutos", "body": "Texto.", "parent": "acerca", "weight": "10"})
path, = repo.files
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
assert front["parent"] == "acerca"
assert front["weight"] == 10
def test_a_top_level_page_carries_no_parent_line(repo, editor, post):
"""Rather than `parent: ""`, which is a line somebody has to decide whether
to worry about."""
import yaml
post("/comunidad/contenido/page/nuevo", {"title": "Contacto", "body": "Texto."})
path, = repo.files
assert "parent" not in yaml.safe_load(repo.files[path].decode().split("---")[1])
def test_a_parent_that_is_not_a_basename_is_dropped(repo, editor, post):
"""It arrives from a select, so anything else is somebody crafting a
request — and a parent with a slash in it would be a path, not a page."""
import yaml
post("/comunidad/contenido/page/nuevo",
{"title": "Estatutos", "body": "Texto.", "parent": "../../etc/passwd"})
path, = repo.files
assert "parent" not in yaml.safe_load(repo.files[path].decode().split("---")[1])
def test_a_page_keeps_its_place_when_edited(repo, editor, post, client):
repo.files["content/page/acerca.es.md"] = (
"---\ntitle: Acerca\nlang: es\n---\n\nTexto.\n").encode("utf-8")
repo.files["content/page/estatutos.es.md"] = (
"---\ntitle: Estatutos\nlang: es\nparent: acerca\nweight: 10\n---\n\nTexto.\n"
).encode("utf-8")
body = client.get("/comunidad/contenido/page/editar/estatutos.es.md").get_data(as_text=True)
assert 'value="acerca" selected' in body or 'value="acerca" selected' in body
assert 'value="10"' in body
def test_the_parent_select_never_offers_the_page_itself(repo, editor, client):
repo.files["content/page/acerca.es.md"] = (
"---\ntitle: Acerca\nlang: es\n---\n\nTexto.\n").encode("utf-8")
repo.files["content/page/contacto.es.md"] = (
"---\ntitle: Contacto\nlang: es\n---\n\nTexto.\n").encode("utf-8")
body = client.get("/comunidad/contenido/page/editar/acerca.es.md").get_data(as_text=True)
assert 'value="contacto"' in body
assert 'value="acerca"' not in body
def test_a_post_has_no_menu_fields(repo, editor, client):
"""Articles are dated and listed, never in the menu."""
body = client.get("/comunidad/contenido/post/nuevo").get_data(as_text=True)
assert 'name="parent"' not in body
assert 'name="weight"' not in body
def test_a_parent_that_has_been_deleted_is_kept_and_named(repo, editor, client):
"""Otherwise the next save would quietly promote the page to the top of the
menu, and nobody would connect that to having deleted another page."""
repo.files["content/page/estatutos.es.md"] = (
"---\ntitle: Estatutos\nlang: es\nparent: borrada\n---\n\nTexto.\n"
).encode("utf-8")
body = client.get("/comunidad/contenido/page/editar/estatutos.es.md").get_data(as_text=True)
assert 'value="borrada" selected' in body
assert "no encontrada" in body

View File

@ -6,7 +6,6 @@ import sqlite3
import pytest
from apps.board import gitea
from apps.board.members import may_create, may_manage
@ -34,6 +33,67 @@ def test_only_the_owner_manages_admins():
assert not may_manage("admin", "admin")
# --- the moderator, who curates content and not people -------------------
def test_admins_and_the_owner_make_moderators():
assert may_create("owner", "moderator")
assert may_create("admin", "moderator")
assert not may_create("moderator", "moderator")
assert not may_create("user", "moderator")
def test_a_moderator_has_no_power_over_anybody():
"""The line the whole role rests on. Being trusted to judge what the public
reads is not being trusted to suspend the person who wrote it, and a
moderator who could do both would be a second kind of admin."""
for target in ("owner", "admin", "moderator", "user"):
assert not may_manage("moderator", target), target
assert not may_create("moderator", target), target
def test_an_admin_may_promote_a_member_to_moderator(client, db, post, make_member, sign_in):
admin = make_member("admina", role="admin")
maria = make_member("maria")
sign_in(admin)
post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"})
assert db.execute("SELECT role FROM members WHERE id = ?",
(maria,)).fetchone()["role"] == "moderator"
def test_an_admin_still_cannot_mint_an_admin_through_the_role_form(
client, db, post, make_member, sign_in):
"""`set_role` moved from owner-only to admin-level so moderators can be
appointed routinely. That must not quietly hand admins the one power the
owner keeps."""
admin = make_member("admina", role="admin")
maria = make_member("maria")
sign_in(admin)
assert post(f"/comunidad/miembros/{maria}/rol", {"role": "admin"}).status_code == 403
assert db.execute("SELECT role FROM members WHERE id = ?",
(maria,)).fetchone()["role"] == "user"
def test_a_moderator_cannot_change_a_role_at_all(client, db, post, make_member, sign_in):
sign_in(make_member("luisa", role="moderator"))
maria = make_member("maria")
assert post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"}).status_code == 403
def test_the_role_form_refuses_a_role_that_is_not_offered(
client, db, post, owner_id, make_member, sign_in):
"""`tombstone` is a real value in the CHECK constraint and would make the
member vanish from every listing while keeping their row."""
sign_in(owner_id)
maria = make_member("maria")
assert post(f"/comunidad/miembros/{maria}/rol", {"role": "tombstone"}).status_code == 403
assert post(f"/comunidad/miembros/{maria}/rol", {"role": "owner"}).status_code == 403
# --- the database holds the line ----------------------------------------
def test_a_second_owner_is_impossible(db):
@ -206,9 +266,10 @@ def test_every_table_pointing_at_members_is_accounted_for(db):
members.py's erase lists. Otherwise erasure breaks — and it breaks at the
moment somebody exercises a right they are entitled to, which is the worst
possible time to find out."""
from apps.board.members import (CLEARED_ON_ERASE, REASSIGNED_ON_ERASE,
REMOVED_ON_ERASE)
handled = REASSIGNED_ON_ERASE | CLEARED_ON_ERASE | REMOVED_ON_ERASE
from apps.board.members import (CLEARED_ON_ERASE, CLEARED_ON_ERASE_AFTER,
REASSIGNED_ON_ERASE, REMOVED_ON_ERASE)
handled = (REASSIGNED_ON_ERASE | CLEARED_ON_ERASE | CLEARED_ON_ERASE_AFTER
| REMOVED_ON_ERASE)
tables = [row["name"] for row in db.execute(
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")]
@ -290,3 +351,82 @@ def test_erasing_a_member_lets_the_name_be_used_again(
assert db.execute(
"SELECT 1 FROM members WHERE gitea_login = 'salvador'").fetchone() is not None
# --- the directory --------------------------------------------------------
#
# Miembros used to be a five-column admin table whose last column held four
# forms, wrapping on top of each other. It is a directory now: everybody sees
# the people, admins open a per-card block for the controls. Both halves are
# asserted, because "the table is gone" is only an improvement if the controls
# came with it.
def test_everybody_sees_the_people(client, db, make_member, sign_in):
maria = make_member("maria")
db.execute("UPDATE members SET bio = ? WHERE id = ?",
("Vivo en Ottakring.\nSegunda línea.", maria))
sign_in(make_member("otra"))
body = client.get("/comunidad/miembros").get_data(as_text=True)
assert "Maria" in body and "maria" in body
assert "Vivo en Ottakring." in body
assert "Segunda línea." not in body # the first line only, as a summary
assert f'/comunidad/privados/con/{maria}' in body # somewhere to write from
def test_a_plain_member_sees_no_controls_and_no_addresses(client, make_member, sign_in):
make_member("maria")
sign_in(make_member("otra"))
body = client.get("/comunidad/miembros").get_data(as_text=True)
for control in ("Gestionar", "Suspender", "Cambiar rol", "Eliminar",
"Enviar invitación", "maria@example.com"):
assert control not in body, control
def test_an_admin_keeps_every_control(client, make_member, sign_in):
make_member("maria")
sign_in(make_member("admina", role="admin"))
body = client.get("/comunidad/miembros").get_data(as_text=True)
for control in ("Gestionar", "Suspender", "Cambiar rol", "Enviar invitación",
"maria@example.com"):
assert control in body, control
assert "Eliminar" not in body # erasure is the owner's alone
def test_a_photo_shows_inside_even_when_the_page_is_not_published(
app, client, db, make_member, sign_in):
"""profiles.photo serves only published pages, which is right for the open
internet and wrong for a directory behind the login."""
from apps.board import uploads
maria = make_member("maria")
stored = "foto-abcdefabcdef.png"
db.execute("UPDATE members SET photo_name = ?, profile_published = 0 WHERE id = ?",
(stored, maria))
with app.app_context():
uploads.directory().joinpath(stored).write_bytes(b"\x89PNG\r\n\x1a\n" + b"\0" * 32)
sign_in(make_member("otra"))
assert stored in client.get("/comunidad/miembros").get_data(as_text=True)
assert client.get(f"/comunidad/miembro/foto/{stored}").status_code == 200
# …and it is still not public, which is the whole distinction.
assert client.get(f"/comunidad/foto/{stored}").status_code == 404
def test_the_members_area_photo_needs_a_session(app, client, db, make_member):
from apps.board import uploads
maria = make_member("maria")
stored = "foto-abcdefabcdef.png"
db.execute("UPDATE members SET photo_name = ? WHERE id = ?", (stored, maria))
with app.app_context():
uploads.directory().joinpath(stored).write_bytes(b"\x89PNG\r\n\x1a\n")
response = client.get(f"/comunidad/miembro/foto/{stored}")
assert response.status_code == 302
assert "/login" in response.headers["Location"]

View File

@ -1,8 +1,12 @@
"""Private messages, unread marks and blocking.
The access rule is membership of the conversation, and it is worth testing
from the outside rather than trusting the query: the failure mode is not an
error, it is somebody quietly reading correspondence that is not theirs.
A conversation is addressed by the person, not by an id: `/privados/con/<id>`
is "what I have said to them and they to me", and it exists as a page before it
exists as a row. That makes the access rule structural rather than checked — a
lookup is always scoped to the member doing the looking, so there is no query
that could return somebody else's correspondence. The tests below still come at
it from the outside, because the failure mode here is not an error, it is
somebody quietly reading what is not theirs.
"""
from __future__ import annotations
@ -10,63 +14,122 @@ from __future__ import annotations
import io
from pathlib import Path
PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
def conversation_between(client, post, a, b, sign_in):
sign_in(a)
response = post("/comunidad/privados/nueva", {"member_id": str(b)})
return int(response.headers["Location"].rstrip("/").rsplit("/", 1)[1])
def talk(member_id: int) -> str:
return f"/comunidad/privados/con/{member_id}"
# --- who may read what ----------------------------------------------------
def test_a_stranger_cannot_read_a_conversation(client, post, make_member, sign_in):
"""404 rather than 403, deliberately: a member who is not in a conversation
should not be able to tell it apart from one that does not exist."""
def test_a_third_person_sees_their_own_empty_conversation(
client, post, make_member, sign_in):
"""The old design gave conversations their own ids, so this test had to
check that a stranger opening one got a 404. Addressing by person removes
the question: `/privados/con/<jose>` means *my* conversation with José, so
a third person opening the same URL sees an empty page, not this one."""
maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in)
sign_in(maria)
post(talk(jose), {"body": "Algo privado"})
sign_in(make_member("curiosa"))
assert client.get(f"/comunidad/privados/{conversation}").status_code == 404
page = client.get(talk(jose))
assert page.status_code == 200
assert "Algo privado" not in page.get_data(as_text=True)
def test_a_stranger_cannot_send_into_one_either(client, post, make_member, sign_in):
maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in)
sign_in(make_member("curiosa"))
response = post(f"/comunidad/privados/{conversation}/enviar", {"body": "Hola"})
assert response.status_code == 404
def test_the_two_parties_can(client, db, post, make_member, sign_in):
maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in)
post(f"/comunidad/privados/{conversation}/enviar", {"body": "Hola José"})
sign_in(jose)
body = client.get(f"/comunidad/privados/{conversation}").get_data(as_text=True)
assert "Hola José" in body
def test_opening_the_same_person_twice_reuses_the_conversation(
def test_writing_to_somebody_does_not_join_you_to_their_other_conversations(
client, db, post, make_member, sign_in):
maria, jose = make_member("maria"), make_member("jose")
first = conversation_between(client, post, maria, jose, sign_in)
second = conversation_between(client, post, maria, jose, sign_in)
sign_in(maria)
post(talk(jose), {"body": "Para José"})
curiosa = make_member("curiosa")
sign_in(curiosa)
post(talk(jose), {"body": "Para José también"})
# Two separate conversations, and neither shows the other's messages.
assert db.execute("SELECT COUNT(*) AS n FROM conversations").fetchone()["n"] == 2
assert "Para José" not in client.get(talk(jose)).get_data(as_text=True).replace(
"Para José también", "")
def test_the_two_parties_see_it(client, post, make_member, sign_in):
maria, jose = make_member("maria"), make_member("jose")
sign_in(maria)
post(talk(jose), {"body": "Hola José"})
sign_in(jose)
assert "Hola José" in client.get(talk(maria)).get_data(as_text=True)
def test_writing_twice_reuses_the_one_conversation(client, db, post, make_member, sign_in):
maria, jose = make_member("maria"), make_member("jose")
sign_in(maria)
post(talk(jose), {"body": "Una"})
post(talk(jose), {"body": "Dos"})
assert first == second
assert db.execute("SELECT COUNT(*) AS n FROM conversations").fetchone()["n"] == 1
assert db.execute("SELECT COUNT(*) AS n FROM messages").fetchone()["n"] == 2
# --- no ceremony before writing -------------------------------------------
def test_the_box_is_there_before_anything_has_been_said(
client, post, make_member, sign_in):
"""There used to be an "Abrir conversación" button that created an empty
conversation and sent you to it. The page now arrives ready to type in."""
maria, jose = make_member("maria"), make_member("jose")
sign_in(maria)
page = client.get(talk(jose))
assert page.status_code == 200
body = page.get_data(as_text=True)
assert 'name="body"' in body # the textarea, on first arrival
assert "Todavía no os habéis escrito" in body
def test_merely_looking_creates_nothing(client, db, make_member, sign_in):
"""Otherwise the inbox fills with "Sin mensajes todavía" for every name
somebody was curious about."""
maria, jose = make_member("maria"), make_member("jose")
sign_in(maria)
client.get(talk(jose))
assert db.execute("SELECT COUNT(*) AS n FROM conversations").fetchone()["n"] == 0
def test_the_picker_sends_you_straight_there(client, make_member, sign_in):
maria, jose = make_member("maria"), make_member("jose")
sign_in(maria)
response = client.get(f"/comunidad/privados/con?member_id={jose}")
assert response.status_code == 302
assert response.headers["Location"].endswith(f"/privados/con/{jose}")
def test_you_cannot_write_to_yourself(client, make_member, sign_in):
maria = make_member("maria")
sign_in(maria)
assert client.get(talk(maria)).status_code == 400
def test_you_cannot_write_to_somebody_who_is_not_a_member(client, make_member, sign_in):
sign_in(make_member("maria"))
assert client.get(talk(9999)).status_code == 404
# --- unread ---------------------------------------------------------------
def test_unread_is_per_member_and_clears_on_reading(client, post, make_member, sign_in):
maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in)
post(f"/comunidad/privados/{conversation}/enviar", {"body": "¿Vienes?"})
sign_in(maria)
post(talk(jose), {"body": "¿Vienes?"})
badge = '<span class="tag">1</span>'
@ -76,7 +139,7 @@ def test_unread_is_per_member_and_clears_on_reading(client, post, make_member, s
sign_in(jose)
assert badge in client.get("/comunidad/privados").get_data(as_text=True)
client.get(f"/comunidad/privados/{conversation}") # opening marks it read
client.get(talk(maria)) # opening marks it read
assert badge not in client.get("/comunidad/privados").get_data(as_text=True)
@ -87,15 +150,13 @@ def test_a_block_stops_both_directions(client, post, make_member, sign_in):
leaves the blocker able to keep writing, which is a megaphone, not a
safety feature."""
maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in)
sign_in(maria)
post(talk(jose), {"body": "Hola"})
post(f"/comunidad/privados/bloquear/{jose}") # maria blocks jose
post(f"/comunidad/privados/bloquear/{jose}") # maria blocks jose
assert post(f"/comunidad/privados/{conversation}/enviar",
{"body": "Otra cosa"}).status_code == 403 # …and maria too
assert post(talk(jose), {"body": "Otra cosa"}).status_code == 403 # …and maria too
sign_in(jose)
assert post(f"/comunidad/privados/{conversation}/enviar",
{"body": "¿Hola?"}).status_code == 403
assert post(talk(maria), {"body": "¿Hola?"}).status_code == 403
def test_a_block_is_enforced_in_the_handler_not_the_template(
@ -103,23 +164,24 @@ def test_a_block_is_enforced_in_the_handler_not_the_template(
"""The form is hidden once blocked, but hiding is a courtesy. Somebody who
keeps the old page open, or crafts the request, meets the same refusal."""
maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in)
sign_in(jose)
post(f"/comunidad/privados/bloquear/{maria}")
sign_in(maria) # never reloaded the page, still has the form
assert post(f"/comunidad/privados/{conversation}/enviar",
{"body": "Hola"}).status_code == 403
assert post(talk(jose), {"body": "Hola"}).status_code == 403
def test_a_blocked_person_cannot_start_a_new_conversation(
def test_a_blocked_person_still_sees_the_history_but_no_box(
client, post, make_member, sign_in):
maria, jose = make_member("maria"), make_member("jose")
sign_in(maria)
post(talk(jose), {"body": "Antes del bloqueo"})
post(f"/comunidad/privados/bloquear/{jose}")
sign_in(jose)
assert post("/comunidad/privados/nueva", {"member_id": str(maria)}).status_code == 403
body = client.get(talk(jose)).get_data(as_text=True)
assert "Antes del bloqueo" in body
assert 'name="body"' not in body
assert "bloqueo entre vosotros" in body
def test_unblocking_only_removes_your_own(client, db, post, make_member, sign_in):
@ -150,9 +212,8 @@ def test_a_picture_in_a_message_is_private_to_the_two_of_them(
"""The board's pictures are for every member. These are not, and being
signed in is nowhere near enough of a check."""
maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in)
post(f"/comunidad/privados/{conversation}/enviar",
{"body": "Mira", "pictures": (io.BytesIO(PNG), "foto.png")},
sign_in(maria)
post(talk(jose), {"body": "Mira", "pictures": (io.BytesIO(PNG), "foto.png")},
content_type="multipart/form-data")
name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"]
@ -167,10 +228,11 @@ def test_a_picture_in_a_message_is_private_to_the_two_of_them(
def test_an_empty_message_with_no_picture_is_refused(client, db, post, make_member, sign_in):
maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in)
post(f"/comunidad/privados/{conversation}/enviar", {"body": " "})
sign_in(maria)
post(talk(jose), {"body": " "})
assert db.execute("SELECT COUNT(*) AS n FROM messages").fetchone()["n"] == 0
assert db.execute("SELECT COUNT(*) AS n FROM conversations").fetchone()["n"] == 0
# --- erasure --------------------------------------------------------------
@ -181,9 +243,8 @@ def test_erasing_a_member_takes_their_private_messages(
two-party exchange has no remainder to preserve, and keeping half of
somebody's erased correspondence is what erasure exists to prevent."""
maria, jose = make_member("maria"), make_member("jose")
conversation = conversation_between(client, post, maria, jose, sign_in)
post(f"/comunidad/privados/{conversation}/enviar",
{"body": "Privado", "pictures": (io.BytesIO(PNG), "f.png")},
sign_in(maria)
post(talk(jose), {"body": "Privado", "pictures": (io.BytesIO(PNG), "f.png")},
content_type="multipart/form-data")
name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"]

View File

@ -19,7 +19,37 @@ from apps.board import migrations
# here as a literal rather than imported: the point is to reproduce what is on
# the server, and schema.sql has moved on.
OLD_SCHEMA = """
CREATE TABLE members (id INTEGER PRIMARY KEY, gitea_login TEXT);
-- `members` as it shipped, because step 4 rebuilds it and a stub with two
-- columns would prove nothing about copying the other eleven.
CREATE TABLE members (
id INTEGER PRIMARY KEY,
gitea_login TEXT NOT NULL UNIQUE COLLATE NOCASE,
display_name TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')),
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
created_by INTEGER REFERENCES members(id),
last_seen_at TEXT
);
CREATE UNIQUE INDEX members_one_owner ON members(role) WHERE role = 'owner';
-- Three of the eight tables that point at members(id), so the rebuild in step
-- 4 is checked with real references across it rather than on its own.
CREATE TABLE conversation_members (
conversation_id INTEGER NOT NULL,
member_id INTEGER NOT NULL REFERENCES members(id),
PRIMARY KEY (conversation_id, member_id)
);
CREATE TABLE blocks (
blocker_id INTEGER NOT NULL REFERENCES members(id),
blocked_id INTEGER NOT NULL REFERENCES members(id),
PRIMARY KEY (blocker_id, blocked_id)
);
CREATE TABLE invites (
id INTEGER PRIMARY KEY,
member_id INTEGER NOT NULL REFERENCES members(id) ON DELETE CASCADE,
purpose TEXT NOT NULL
);
CREATE TABLE threads (id INTEGER PRIMARY KEY, deleted_at TEXT);
CREATE TABLE comments (id INTEGER PRIMARY KEY, deleted_at TEXT);
CREATE TABLE messages (id INTEGER PRIMARY KEY, deleted_at TEXT);
@ -48,7 +78,13 @@ def old_db(tmp_path):
# and fails on the server.
db.execute("PRAGMA foreign_keys = ON")
db.executescript(OLD_SCHEMA)
db.execute("INSERT INTO members (id, gitea_login) VALUES (1, 'salvador')")
db.execute("INSERT INTO members (id, gitea_login, display_name, email, role) "
"VALUES (1, 'salvador', 'Salvador', 's@example.com', 'user')")
db.execute("INSERT INTO members (id, gitea_login, display_name, role, created_by) "
"VALUES (2, 'pablo', 'Pablo', 'owner', 1)")
db.execute("INSERT INTO conversation_members VALUES (1, 1)")
db.execute("INSERT INTO blocks VALUES (1, 2)")
db.execute("INSERT INTO invites (member_id, purpose) VALUES (1, 'invite')")
db.execute("INSERT INTO threads (id) VALUES (7)")
db.execute("INSERT INTO comments (id) VALUES (9)")
db.execute(
@ -126,6 +162,72 @@ def test_running_it_twice_changes_nothing(old_db):
number for number, _, _ in migrations.STEPS)
# --- step 4: the moderator role ------------------------------------------
def test_the_role_check_refuses_a_moderator_beforehand(old_db):
"""The premise, like the CHECK test above. SQLite has no DROP CONSTRAINT,
so if this ever stops raising, step 4 can shrink to an ALTER."""
with pytest.raises(sqlite3.IntegrityError):
old_db.execute("INSERT INTO members (gitea_login, display_name, role) "
"VALUES ('luisa', 'Luisa', 'moderator')")
def test_a_moderator_is_accepted_afterwards(old_db):
migrations.apply(old_db)
old_db.execute("INSERT INTO members (gitea_login, display_name, role) "
"VALUES ('luisa', 'Luisa', 'moderator')")
assert old_db.execute(
"SELECT role FROM members WHERE gitea_login = 'luisa'").fetchone()["role"] == "moderator"
def test_every_member_column_survives_the_rebuild(old_db):
"""Thirteen columns copied by name. A typo in that list is a member losing
their email address, or their password, or their public page."""
before = old_db.execute(
"SELECT id, gitea_login, display_name, email, role, active, created_by "
"FROM members ORDER BY id").fetchall()
migrations.apply(old_db)
after = old_db.execute(
"SELECT id, gitea_login, display_name, email, role, active, created_by "
"FROM members ORDER BY id").fetchall()
assert [tuple(row) for row in after] == [tuple(row) for row in before]
def test_the_one_owner_rule_survives_the_rebuild(old_db):
"""The partial unique index is not copied with the rows, so it has to be
recreated by hand. Without it the database silently stops being the thing
that guarantees one owner, and a bug in a handler becomes two owners."""
migrations.apply(old_db)
with pytest.raises(sqlite3.IntegrityError):
old_db.execute("INSERT INTO members (gitea_login, display_name, role) "
"VALUES ('otro', 'Otro', 'owner')")
def test_nothing_pointing_at_a_member_is_left_dangling(old_db):
"""Dropping and renaming `members` with foreign keys off is the only way to
do this, and it is also the way to quietly orphan every row in the eight
tables that reference it."""
migrations.apply(old_db)
assert old_db.execute("PRAGMA foreign_key_check").fetchall() == []
assert old_db.execute("SELECT COUNT(*) FROM conversation_members").fetchone()[0] == 1
assert old_db.execute("SELECT COUNT(*) FROM blocks").fetchone()[0] == 1
assert old_db.execute("SELECT COUNT(*) FROM invites").fetchone()[0] == 1
# And the references still bite: foreign keys are back on after apply().
with pytest.raises(sqlite3.IntegrityError):
old_db.execute("INSERT INTO blocks VALUES (1, 999)")
def test_foreign_keys_are_back_on_afterwards(old_db):
"""apply() switches them off outside the transaction and restores them in a
finally. A migration that leaves them off makes the whole process run
without enforcement until the container next restarts."""
migrations.apply(old_db)
assert old_db.execute("PRAGMA foreign_keys").fetchone()[0] == 1
def test_a_fresh_database_skips_it(app, db):
"""schema.sql already builds the new shape, so the step must find its work
done and return quietly rather than rebuilding a table it just created."""
@ -162,6 +264,12 @@ def test_the_app_starts_against_a_database_from_before_all_this(tmp_path):
" CHECK ((thread_id IS NULL) <> (comment_id IS NULL))")
# …and predates members owning their own passwords.
old_sql = old_sql.replace(" password_hash TEXT,\n", "")
# …and predates the moderator role, so step 4 has a CHECK to widen here too.
old_sql = old_sql.replace(
" role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'moderator',\n"
" 'user', 'tombstone')),",
" role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')),")
assert "CHECK (role IN ('owner', 'admin', 'user', 'tombstone'))" in old_sql
old_sql += """
CREATE TABLE gitea_tokens (
member_id INTEGER PRIMARY KEY REFERENCES members(id) ON DELETE CASCADE,
@ -194,6 +302,14 @@ def test_the_app_starts_against_a_database_from_before_all_this(tmp_path):
assert (kept["stored_name"], kept["thread_id"], kept["bytes"]) == (
"foto-abc123abc123.jpg", 1, 2048)
# Step 4: the role list is wider, the one-owner rule survived the rebuild,
# and nothing that pointed at a member row lost its target.
db.execute("INSERT INTO members (gitea_login, display_name, role) "
"VALUES ('luisa', 'Luisa', 'moderator')")
assert db.execute("PRAGMA foreign_key_check").fetchall() == []
assert db.execute(
"SELECT name FROM sqlite_master WHERE name = 'members_one_owner'").fetchone()
# And starting again changes nothing, because a container restarts.
create_app({"SECRET_KEY": "x", "DB_PATH": path, "OWNER_LOGIN": "salvador",
"UPLOAD_DIR": str(tmp_path / "uploads"), "TESTING": True})

View File

@ -0,0 +1,218 @@
"""What each role can see and reach.
This file exists because of a bug that no other test in this suite could have
caught: *Privados*, *Mi perfil* and *Contenido* were all inside one
`{% if g.member.role in ('owner', 'admin') %}` block in base.html, so an
ordinary member signed in to a wall and a member list and nothing else. Every
feature worked. Every test passed. Most of the members area was simply invisible
to the people it was built for.
So the navigation is now asserted per role, from the rendered page, and every
section is asserted from its route as well — because a link nobody can see and a
link that 403s are the same thing to whoever needed it.
"""
from __future__ import annotations
import pytest
# Label -> the path it leads to. Both halves matter: the label is what a member
# looks for, the path is what has to answer.
SECTIONS = {
"Inicio": "/comunidad/",
"Muro": "/comunidad/muro",
"Privados": "/comunidad/privados",
"Publicaciones": "/comunidad/publicaciones",
}
ADMIN_ONLY = {"Gestión": "/comunidad/gestion"}
@pytest.fixture
def nav(client, sign_in):
def _nav(member_id):
sign_in(member_id)
page = client.get("/comunidad/")
assert page.status_code == 200
return page.get_data(as_text=True)
return _nav
@pytest.mark.parametrize("role", ["user", "moderator"])
def test_a_member_sees_the_four_shared_sections(role, nav, make_member):
"""The regression. Not one of these may depend on a role again."""
body = nav(make_member("maria", role=role))
for label in SECTIONS:
assert f">{label}" in body or f"{label}<" in body, label
@pytest.mark.parametrize("role", ["user", "moderator"])
def test_a_member_does_not_see_gestion(role, nav, make_member):
assert "Gestión" not in nav(make_member("maria", role=role))
def test_an_admin_sees_everything(nav, make_member):
body = nav(make_member("admina", role="admin"))
for label in list(SECTIONS) + list(ADMIN_ONLY):
assert label in body, label
@pytest.mark.parametrize("role", ["user", "moderator", "admin"])
def test_the_account_items_are_in_the_corner_for_everybody(role, nav, make_member):
"""They used to be navigation entries, and two of them admin-only. A member
with no way to reach their own profile or their own data export is the same
bug wearing a different hat."""
body = nav(make_member("maria", role=role))
assert "/comunidad/mi-perfil" in body
assert "/comunidad/mis-datos" in body
assert "Salir" in body
@pytest.mark.parametrize("role", ["user", "moderator", "admin"])
@pytest.mark.parametrize("path", sorted(SECTIONS.values()))
def test_every_shared_section_answers_for_every_role(role, path, client, make_member, sign_in):
sign_in(make_member("maria", role=role))
assert client.get(path).status_code == 200
@pytest.mark.parametrize("role", ["user", "moderator"])
def test_gestion_is_refused_below_admin(role, client, make_member, sign_in):
"""Refused by the route, not hidden by the template. A moderator who types
the address meets the same answer as one who cannot see the link."""
sign_in(make_member("maria", role=role))
assert client.get("/comunidad/gestion").status_code == 403
def test_gestion_opens_for_an_admin(client, make_member, sign_in):
sign_in(make_member("admina", role="admin"))
assert client.get("/comunidad/gestion").status_code == 200
def test_signing_in_lands_on_inicio(client, db, post, make_member):
"""It used to land on the wall, which is one of five places something may
have happened since the last visit."""
from apps.board import passwords
member_id = make_member("maria")
db.execute("UPDATE members SET password_hash = ? WHERE id = ?",
(passwords.hash_password("una-contraseña-larga"), member_id))
response = post("/comunidad/login",
{"identifier": "maria", "password": "una-contraseña-larga"})
assert response.status_code == 302
assert response.headers["Location"].rstrip("/").endswith("/comunidad")
def test_the_wall_keeps_its_thread_urls(client, post, make_member, sign_in):
"""The wall moved from /comunidad/ to /comunidad/muro. Thread addresses did
not, because people have linked to them from private messages."""
sign_in(make_member("maria"))
post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"})
assert client.get("/comunidad/tema/1").status_code == 200
assert client.get("/comunidad/muro").status_code == 200
def test_signed_out_visitors_get_no_navigation(client):
body = client.get("/comunidad/login").get_data(as_text=True)
for label in list(SECTIONS) + list(ADMIN_ONLY):
assert f'>{label}<' not in body, label
# --- reaching the published articles --------------------------------------
#
# The screen worked and nothing linked to it: Gestión offered only the static
# pages, and the Artículos tab exists only once you are already on that screen.
# A moderator, who cannot open Gestión at all, had no route to it.
def test_an_admin_reaches_the_articles_from_gestion(client, make_member, sign_in):
sign_in(make_member("admina", role="admin"))
body = client.get("/comunidad/gestion").get_data(as_text=True)
assert "/comunidad/contenido/post" in body
assert "Artículos publicados" in body
def test_a_moderator_reaches_them_from_publicaciones(client, make_member, sign_in):
"""Their only way in, so it is a link in the heading rather than a clause in
a paragraph."""
sign_in(make_member("luisa", role="moderator"))
body = client.get("/comunidad/publicaciones").get_data(as_text=True)
assert "/comunidad/contenido/post" in body
assert "Ya publicado" in body
def test_a_plain_member_is_offered_neither(client, make_member, sign_in):
sign_in(make_member("maria"))
body = client.get("/comunidad/publicaciones").get_data(as_text=True)
assert "/comunidad/contenido" not in body
assert "Ya publicado" not in body
# --- the strip the public site draws --------------------------------------
#
# vienalatina.com is files on disk, so the bar is drawn by a script that asks
# this app who is reading. That makes this endpoint the whole privacy surface:
# it is the only thing on the public side that knows anything about anybody.
def test_a_visitor_is_told_nothing(client):
response = client.get("/comunidad/sesion.json")
assert response.status_code == 200
assert response.get_json() == {"signed_in": False}
assert response.headers["Cache-Control"] == "no-store"
def test_a_member_gets_their_name_and_their_sections(client, make_member, sign_in):
sign_in(make_member("maria"))
state = client.get("/comunidad/sesion.json").get_json()
assert state["signed_in"] is True
assert state["name"] == "Maria"
assert [s["label"] for s in state["sections"]] == [
"Inicio", "Muro", "Privados", "Publicaciones"]
assert state["csrf"] # the bar renders a real logout form
def test_the_sections_follow_the_same_rule_as_the_navigation(
client, make_member, sign_in):
"""Two places listing the sections would drift the first time one changed;
the navigation and this endpoint have to agree about Gestión."""
sign_in(make_member("admina", role="admin"))
labels = [s["label"] for s in client.get("/comunidad/sesion.json").get_json()["sections"]]
assert "Gestión" in labels
sign_in(make_member("luisa", role="moderator"))
labels = [s["label"] for s in client.get("/comunidad/sesion.json").get_json()["sections"]]
assert "Gestión" not in labels
def test_the_answer_is_never_cached(client, make_member, sign_in):
"""A cached answer is somebody else's name on a shared machine, or a bar
that stays up after signing out."""
sign_in(make_member("maria"))
assert client.get("/comunidad/sesion.json").headers["Cache-Control"] == "no-store"
def test_signing_in_sets_the_hint_and_signing_out_clears_it(client, db, post, make_member):
"""The hint is what keeps a stranger reading one article from costing a
request to this app on every page view."""
from apps.board import passwords
member_id = make_member("maria")
db.execute("UPDATE members SET password_hash = ? WHERE id = ?",
(passwords.hash_password("una-contraseña-larga"), member_id))
signed_in = post("/comunidad/login",
{"identifier": "maria", "password": "una-contraseña-larga"})
cookie = signed_in.headers.get_all("Set-Cookie")
assert any("vl_sesion=1" in header for header in cookie)
assert any("HttpOnly" not in header for header in cookie if "vl_sesion" in header)
signed_out = post("/comunidad/logout")
assert any("vl_sesion=;" in header or "vl_sesion=\"\"" in header
for header in signed_out.headers.get_all("Set-Cookie"))

View File

@ -0,0 +1,261 @@
"""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
# --- names as doors -------------------------------------------------------
#
# A profile nobody can reach from inside the members area is a profile nobody
# visits. Every screen renders names through the one macro in
# templates/_person.html, which links only when there is a page to link to —
# the rule is in one place because both failures are silent: never linking
# hides the profiles, always linking sends people to a 404.
def test_a_name_on_the_wall_links_to_a_published_page(client, post, published, sign_in):
author = published("maria")
sign_in(author)
post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"})
for url in ("/comunidad/muro", "/comunidad/tema/1", "/comunidad/"):
assert 'href="/maria"' in client.get(url).get_data(as_text=True), url
def test_a_name_without_a_page_is_not_a_link(client, post, published, sign_in):
author = published("maria", profile_published=0)
sign_in(author)
post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"})
for url in ("/comunidad/muro", "/comunidad/tema/1"):
body = client.get(url).get_data(as_text=True)
assert 'href="/maria"' not in body, url
assert "Maria" in body, url # the name is still there
def test_a_comment_and_a_private_message_link_too(client, post, published,
make_member, sign_in):
maria = published("maria")
jose = make_member("jose")
sign_in(jose)
post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"})
sign_in(maria)
post("/comunidad/tema/1/comentar", {"body": "Yo también"})
post("/comunidad/privados/con/%d" % jose, {"body": "Hola José"})
sign_in(jose)
assert 'href="/maria"' in client.get("/comunidad/tema/1").get_data(as_text=True)
assert 'href="/maria"' in client.get(
f"/comunidad/privados/con/{maria}").get_data(as_text=True)

View File

@ -0,0 +1,150 @@
"""One 👍 per member per thing, and clicking it again takes it back.
The whole feature is a count and a toggle. What is worth testing is not that a
row appears — it is that a member cannot react twice (the database says so, not
the handler), that the button goes back where it was pressed without becoming an
open redirect, and that reacting to something that has been deleted is a 404
rather than a row pointing at nothing.
"""
from __future__ import annotations
import sqlite3
import pytest
def react(post, kind, target_id, back=None):
data = {"kind": kind, "id": target_id}
if back is not None:
data["back"] = back
return post("/comunidad/reaccion", data)
@pytest.fixture
def thread(post, make_member, sign_in):
"""A thread by José, for somebody else to react to."""
jose = make_member("jose")
sign_in(jose)
post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"})
return 1
def test_reacting_adds_one_and_reacting_again_takes_it_back(
db, post, thread, make_member, sign_in):
sign_in(make_member("maria"))
react(post, "thread", thread)
assert db.execute("SELECT COUNT(*) AS n FROM reactions").fetchone()["n"] == 1
react(post, "thread", thread)
assert db.execute("SELECT COUNT(*) AS n FROM reactions").fetchone()["n"] == 0
def test_two_members_each_get_one(db, post, thread, make_member, sign_in):
for name in ("maria", "luisa"):
sign_in(make_member(name))
react(post, "thread", thread)
assert db.execute("SELECT COUNT(*) AS n FROM reactions").fetchone()["n"] == 2
def test_the_database_refuses_a_second_one(db, thread, make_member):
"""A partial unique index rather than a check in the handler, because the
handler is one bug away from inserting twice and the index is not.
UNIQUE(member_id, thread_id) on its own would not do it: SQLite treats NULLs
as distinct, so every comment reaction — all with a NULL thread_id — would
be unique by accident."""
maria = make_member("maria")
db.execute("INSERT INTO reactions (thread_id, member_id) VALUES (?, ?)", (thread, maria))
with pytest.raises(sqlite3.IntegrityError):
db.execute("INSERT INTO reactions (thread_id, member_id) VALUES (?, ?)",
(thread, maria))
def test_a_reaction_belongs_to_exactly_one_thing(db, thread, make_member):
maria = make_member("maria")
for columns, values in (("", ""), ("thread_id, comment_id", f"{thread}, 1")):
with pytest.raises(sqlite3.IntegrityError):
db.execute(
f"INSERT INTO reactions ({columns + ', ' if columns else ''}member_id) "
f"VALUES ({values + ', ' if values else ''}{maria})")
def test_comments_can_be_reacted_to_as_well(db, post, thread, make_member, sign_in):
sign_in(make_member("maria"))
post(f"/comunidad/tema/{thread}/comentar", {"body": "Yo también"})
react(post, "comment", 1)
row = db.execute("SELECT thread_id, comment_id FROM reactions").fetchone()
assert (row["thread_id"], row["comment_id"]) == (None, 1)
def test_the_count_and_my_own_mark_show_on_the_page(client, post, thread,
make_member, sign_in):
sign_in(make_member("maria"))
react(post, "thread", thread)
for url in (f"/comunidad/tema/{thread}", "/comunidad/muro"):
body = client.get(url).get_data(as_text=True)
assert "reaction__button--mine" in body, url
assert ">1<" in body, url
# Somebody else sees the count but not the filled button.
sign_in(make_member("luisa"))
body = client.get("/comunidad/muro").get_data(as_text=True)
assert "reaction__button--mine" not in body
assert ">1<" in body
def test_reacting_to_something_that_is_gone_is_a_404(db, post, thread,
owner_id, make_member, sign_in):
sign_in(owner_id)
post(f"/comunidad/tema/{thread}/eliminar")
sign_in(make_member("maria"))
assert react(post, "thread", thread).status_code == 404
assert react(post, "thread", 9999).status_code == 404
assert db.execute("SELECT COUNT(*) AS n FROM reactions").fetchone()["n"] == 0
def test_an_unknown_kind_is_refused(post, thread, make_member, sign_in):
sign_in(make_member("maria"))
assert react(post, "members", thread).status_code == 400
def test_the_back_field_cannot_leave_the_site(post, thread, make_member, sign_in):
"""`back` is a redirect somebody can type, which is an open redirect unless
it is checked — the same hole the login form's `next` has, so it goes
through the same function."""
sign_in(make_member("maria"))
response = react(post, "thread", thread, back="https://ejemplo.invalid/premio")
assert response.status_code == 302
assert "ejemplo.invalid" not in response.headers["Location"]
def test_the_button_comes_back_to_the_comment_it_was_pressed_on(
post, thread, make_member, sign_in):
sign_in(make_member("maria"))
post(f"/comunidad/tema/{thread}/comentar", {"body": "Yo también"})
response = react(post, "comment", 1, back=f"/comunidad/tema/{thread}#c1")
assert response.headers["Location"].endswith(f"/comunidad/tema/{thread}#c1")
def test_erasing_a_member_takes_their_reactions(db, post, thread, owner_id,
make_member, sign_in):
maria = make_member("maria")
sign_in(maria)
react(post, "thread", thread)
sign_in(owner_id)
post(f"/comunidad/miembros/{maria}/eliminar")
assert db.execute("SELECT COUNT(*) AS n FROM reactions").fetchone()["n"] == 0

View File

@ -0,0 +1,471 @@
"""The moderation queue.
The property every test here circles is the same one: **nothing a member writes
reaches the site repository until a moderator approves it.** A commit to that
repository is publication — Gitea's webhook starts the translate, build and
deploy pipeline — so "queued in git with a flag" would already be live in three
languages. The Gitea layer is therefore replaced by a dictionary, and several
tests assert it was *not* written to, which is the assertion that matters most.
The second property is attribution. Approval commits under the author's name and
email, not the moderator's, because git history is where somebody looks months
later to ask who wrote a post.
"""
from __future__ import annotations
import hashlib
import io
from pathlib import Path
import pytest
from apps.board import gitea
PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
class FakeRepo:
"""Only what a submission needs: writes, with who made them."""
def __init__(self):
self.files: dict[str, bytes] = {}
self.commits: list[str] = []
self.authors: list[dict] = []
def write_file(self, path, data, message, token=None, sha=None, member=None):
self.files[path] = data
self.commits.append(message)
self.authors.append(gitea._identity(member))
return hashlib.sha1(data).hexdigest()
@pytest.fixture
def repo(monkeypatch):
fake = FakeRepo()
monkeypatch.setattr(gitea, "write_file", fake.write_file)
return fake
@pytest.fixture
def maria(make_member):
return make_member("maria", role="user")
@pytest.fixture
def luisa(make_member):
return make_member("luisa", role="moderator")
def propose(post, title="Feria en Ottakring", body="Habrá **empanadas**.", **extra):
data = {"title": title, "body": body}
data.update(extra)
return post("/comunidad/publicaciones/nueva", data)
def only_submission(db):
return db.execute("SELECT * FROM submissions").fetchone()
# --- a member proposes ----------------------------------------------------
def test_a_proposal_is_a_row_and_not_a_commit(repo, db, post, maria, sign_in):
"""The whole point of the table. If this ever commits, the post is on
vienalatina.com before anybody has read it."""
sign_in(maria)
propose(post, description="Una feria", categories=["Comunidad"])
row = only_submission(db)
assert (row["state"], row["title"], row["categories"]) == (
"pending", "Feria en Ottakring", "Comunidad")
assert repo.files == {}
assert repo.commits == []
def test_an_empty_proposal_is_refused(db, post, maria, sign_in):
sign_in(maria)
assert propose(post, title=" ", body=" ").status_code == 400
assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0
def test_only_so_many_may_wait_at_once(db, post, maria, sign_in):
"""A bound on how much unread work one person can put on the moderators
without talking to them."""
from apps.board.submissions import PENDING_MAX
sign_in(maria)
for n in range(PENDING_MAX):
propose(post, title=f"Propuesta {n}")
refused = propose(post, title="Una más")
assert refused.status_code == 400
assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == PENDING_MAX
def test_a_moderator_is_sent_to_the_editor_instead(client, luisa, sign_in):
"""Their posts do not queue, so a form that would wait for their own
approval is a detour with nothing at the end of it."""
sign_in(luisa)
response = client.get("/comunidad/publicaciones/nueva")
assert response.status_code == 302
assert "/comunidad/contenido/post/nuevo" in response.headers["Location"]
def test_a_moderator_publishing_directly_does_commit(repo, db, post, luisa, sign_in):
"""The other half of the policy: curation applies to members' posts, and a
moderator is the person doing the curating."""
sign_in(luisa)
post("/comunidad/contenido/post/nuevo",
{"title": "Aviso", "body": "Texto.", "date": "2026-09-25"})
assert list(repo.files) == ["content/post/2026-09-25-aviso.es.md"]
assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0
# --- who may read an unapproved post -------------------------------------
def test_a_stranger_cannot_read_somebody_else_is_draft(client, db, post, maria,
make_member, sign_in):
sign_in(maria)
propose(post)
submission_id = only_submission(db)["id"]
sign_in(make_member("curiosa"))
assert client.get(f"/comunidad/publicaciones/{submission_id}").status_code == 403
def test_the_author_and_the_moderators_can(client, db, post, maria, luisa, sign_in):
sign_in(maria)
propose(post)
submission_id = only_submission(db)["id"]
assert client.get(f"/comunidad/publicaciones/{submission_id}").status_code == 200
sign_in(luisa)
assert client.get(f"/comunidad/publicaciones/{submission_id}").status_code == 200
def test_the_queue_is_only_listed_for_moderators(client, db, post, maria,
luisa, make_member, sign_in):
sign_in(maria)
propose(post, title="Feria de Ottakring")
sign_in(make_member("otro"))
assert "Feria de Ottakring" not in client.get(
"/comunidad/publicaciones").get_data(as_text=True)
sign_in(luisa)
assert "Feria de Ottakring" in client.get(
"/comunidad/publicaciones").get_data(as_text=True)
def test_a_member_cannot_approve_their_own(repo, client, db, post, maria, sign_in):
"""The one that would make the whole queue decorative."""
sign_in(maria)
propose(post)
submission_id = only_submission(db)["id"]
response = post(f"/comunidad/publicaciones/{submission_id}/aprobar")
assert response.status_code == 403
assert repo.files == {}
assert only_submission(db)["state"] == "pending"
def test_a_member_cannot_reject_either(client, db, post, maria, make_member, sign_in):
sign_in(maria)
propose(post)
submission_id = only_submission(db)["id"]
sign_in(make_member("otro"))
assert post(f"/comunidad/publicaciones/{submission_id}/rechazar",
{"note": "No me gusta"}).status_code == 403
# --- approval -------------------------------------------------------------
def test_approving_commits_once_under_the_author_is_name(
repo, db, post, maria, luisa, sign_in):
"""Attribution is the reason `write_file` takes an author at all. A post
approved by Luisa but written by María has to say María in git."""
sign_in(maria)
propose(post, categories=["Comunidad"])
submission_id = only_submission(db)["id"]
sign_in(luisa)
post(f"/comunidad/publicaciones/{submission_id}/aprobar")
path, = repo.files
assert path.startswith("content/post/") and path.endswith("-feria-en-ottakring.es.md")
assert repo.authors == [{"name": "Maria", "email": "maria@example.com"}]
row = only_submission(db)
assert (row["state"], row["published_path"], row["reviewed_by"]) == (
"approved", path, luisa)
def test_the_approved_file_is_what_the_pipeline_expects(repo, db, post, maria,
luisa, sign_in):
"""The same contract the editor's own tests hold it to: Spanish source, no
`translated_from`, categories as a list."""
import yaml
sign_in(maria)
propose(post, categories=["Comunidad", "Cultura"], description="Una feria")
submission_id = only_submission(db)["id"]
sign_in(luisa)
post(f"/comunidad/publicaciones/{submission_id}/aprobar")
path, = repo.files
text = repo.files[path].decode("utf-8")
front = yaml.safe_load(text.split("---")[1])
assert front["lang"] == "es"
assert front["manual_translation"] is False
assert front["categories"] == ["Comunidad", "Cultura"]
assert front["description"] == "Una feria"
assert "translated_from" not in front
assert "empanadas" in text
def test_approving_twice_publishes_once(repo, db, post, maria, luisa, sign_in):
sign_in(maria)
propose(post)
submission_id = only_submission(db)["id"]
sign_in(luisa)
post(f"/comunidad/publicaciones/{submission_id}/aprobar")
post(f"/comunidad/publicaciones/{submission_id}/aprobar")
assert len(repo.commits) == 1
def test_a_picture_is_private_until_approval_and_committed_after(
app, repo, client, db, post, maria, luisa, make_member, sign_in):
"""Three things at once, because they are one story: the picture is readable
by the author and the moderators and nobody else, it is not in the
repository, and approving puts it there and takes the private copy away."""
sign_in(maria)
propose(post, picture=(io.BytesIO(PNG), "feria.png"))
row = only_submission(db)
stored = row["photo_name"]
url = f"/comunidad/publicaciones/foto/{stored}"
assert (Path(app.config["UPLOAD_DIR"]) / stored).exists()
assert client.get(url).status_code == 200 # the author
sign_in(make_member("curiosa"))
assert client.get(url).status_code == 404 # anybody else
sign_in(luisa)
assert client.get(url).status_code == 200 # a moderator
assert repo.files == {} # still nothing published
post(f"/comunidad/publicaciones/{row['id']}/aprobar")
assert any(path.startswith("static/uploads/") for path in repo.files)
assert only_submission(db)["photo_name"] is None
assert not (Path(app.config["UPLOAD_DIR"]) / stored).exists()
assert client.get(url).status_code == 404
def test_a_file_that_is_not_an_image_is_refused(db, post, maria, sign_in):
sign_in(maria)
response = propose(post, picture=(io.BytesIO(b"<html>nope</html>"), "foto.png"))
assert response.status_code == 400
assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0
# --- rejection ------------------------------------------------------------
def test_rejecting_needs_a_reason_and_shows_it_to_the_author(
repo, client, db, post, maria, luisa, sign_in):
sign_in(maria)
propose(post)
submission_id = only_submission(db)["id"]
sign_in(luisa)
post(f"/comunidad/publicaciones/{submission_id}/rechazar", {"note": " "})
assert only_submission(db)["state"] == "pending" # no reason, no rejection
post(f"/comunidad/publicaciones/{submission_id}/rechazar",
{"note": "Falta decir dónde es."})
assert only_submission(db)["state"] == "rejected"
assert repo.files == {}
sign_in(maria)
assert "Falta decir dónde es." in client.get(
"/comunidad/publicaciones").get_data(as_text=True)
def test_editing_a_rejected_one_puts_it_back_in_the_queue(
client, db, post, maria, luisa, sign_in):
"""Otherwise a rewritten post stays marked "devuelto" and never reaches the
queue again — the author waits for a review that cannot happen."""
sign_in(maria)
propose(post)
submission_id = only_submission(db)["id"]
sign_in(luisa)
post(f"/comunidad/publicaciones/{submission_id}/rechazar", {"note": "Falta el dónde."})
sign_in(maria)
post(f"/comunidad/publicaciones/{submission_id}/editar",
{"title": "Feria en Ottakring", "body": "En la plaza, el sábado."})
row = only_submission(db)
assert (row["state"], row["note"], row["reviewed_by"]) == ("pending", None, None)
sign_in(luisa)
assert "Feria en Ottakring" in client.get(
"/comunidad/publicaciones").get_data(as_text=True)
def test_nobody_else_may_edit_or_withdraw_it(client, db, post, maria,
luisa, make_member, sign_in):
"""A moderator approves or returns a submission. Rewriting somebody's words
and publishing them under their name is not one of the two — the same line
the board draws between deleting a post and editing it."""
sign_in(maria)
propose(post)
submission_id = only_submission(db)["id"]
for other in (luisa, make_member("otro")):
sign_in(other)
assert post(f"/comunidad/publicaciones/{submission_id}/editar",
{"title": "Otra cosa", "body": "Otro texto"}).status_code == 403
assert post(f"/comunidad/publicaciones/{submission_id}/retirar").status_code == 403
def test_withdrawing_takes_the_picture_with_it(app, db, post, maria, sign_in):
sign_in(maria)
propose(post, picture=(io.BytesIO(PNG), "feria.png"))
row = only_submission(db)
post(f"/comunidad/publicaciones/{row['id']}/retirar")
assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0
assert not (Path(app.config["UPLOAD_DIR"]) / row["photo_name"]).exists()
def test_an_approved_one_cannot_be_edited_or_withdrawn(
repo, db, post, maria, luisa, sign_in):
"""It is in the repository now. Changing it there is what the editor is
for, and withdrawing a row would not unpublish anything."""
sign_in(maria)
propose(post)
submission_id = only_submission(db)["id"]
sign_in(luisa)
post(f"/comunidad/publicaciones/{submission_id}/aprobar")
sign_in(maria)
post(f"/comunidad/publicaciones/{submission_id}/editar",
{"title": "Otra cosa", "body": "Otro texto"})
post(f"/comunidad/publicaciones/{submission_id}/retirar")
row = only_submission(db)
assert (row["state"], row["title"]) == ("approved", "Feria en Ottakring")
# --- erasure --------------------------------------------------------------
def test_erasing_the_author_takes_their_submissions_and_photos(
app, repo, db, post, owner_id, maria, sign_in):
"""A submission is private writing, so it goes the way private messages do.
What remains of an approved one is the post in the repository, which carries
their name in a commit that is not ours to rewrite from here."""
sign_in(maria)
propose(post, picture=(io.BytesIO(PNG), "feria.png"))
stored = only_submission(db)["photo_name"]
sign_in(owner_id)
post(f"/comunidad/miembros/{maria}/eliminar")
assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0
assert not (Path(app.config["UPLOAD_DIR"]) / stored).exists()
def test_erasing_a_reviewer_keeps_the_submission(db, post, owner_id, maria,
make_member, sign_in):
"""Who reviewed something is a fact about the submission, not personal data
of the reviewer, so the name goes and the row stays."""
reviewer = make_member("luisa", role="moderator")
sign_in(maria)
propose(post)
submission_id = only_submission(db)["id"]
sign_in(reviewer)
post(f"/comunidad/publicaciones/{submission_id}/rechazar", {"note": "Falta el dónde."})
sign_in(owner_id)
post(f"/comunidad/miembros/{reviewer}/eliminar")
row = only_submission(db)
assert (row["state"], row["reviewed_by"], row["note"]) == (
"rejected", None, "Falta el dónde.")
# --- the two ways approving can fail, told apart --------------------------
def test_a_refused_token_is_not_reported_as_a_missing_picture(
app, db, post, maria, luisa, sign_in, monkeypatch):
"""The bug in the screenshot. `except OSError` caught PermissionError from
the git client and blamed the photograph — on a page that was displaying the
photograph. The message has to name the thing that is actually wrong."""
sign_in(maria)
propose(post, picture=(io.BytesIO(PNG), "feria.png"))
row = only_submission(db)
class Refused:
class Response:
status_code = 403
@staticmethod
def json():
return {}
def request(self, *args, **kwargs):
return self.Response()
monkeypatch.setattr(gitea, "requests", Refused())
sign_in(luisa)
response = post(f"/comunidad/publicaciones/{row['id']}/aprobar",
follow_redirects=True)
body = response.get_data(as_text=True)
assert "rechazó el token" in body
assert "imagen en el disco" not in body
assert only_submission(db)["state"] == "pending" # nothing was recorded
# And the picture is still there, so a second attempt can succeed.
assert (Path(app.config["UPLOAD_DIR"]) / row["photo_name"]).exists()
def test_a_genuinely_missing_picture_still_says_so(
app, repo, db, post, maria, luisa, sign_in):
sign_in(maria)
propose(post, picture=(io.BytesIO(PNG), "feria.png"))
row = only_submission(db)
(Path(app.config["UPLOAD_DIR"]) / row["photo_name"]).unlink()
sign_in(luisa)
response = post(f"/comunidad/publicaciones/{row['id']}/aprobar",
follow_redirects=True)
assert "imagen en el disco" in response.get_data(as_text=True)
assert repo.files == {}
assert only_submission(db)["state"] == "pending"
def test_an_approved_post_is_signed_by_the_member_not_the_moderator(
repo, db, post, maria, luisa, sign_in):
"""Both halves of attribution now: the commit names María, and so does the
page — `author` in the frontmatter, with a link only if she has published
her profile."""
import yaml
db.execute("UPDATE members SET profile_published = 1 WHERE id = ?", (maria,))
sign_in(maria)
propose(post)
submission_id = only_submission(db)["id"]
sign_in(luisa)
post(f"/comunidad/publicaciones/{submission_id}/aprobar")
path, = repo.files
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
assert front["author"] == "Maria"
assert front["author_url"] == "/maria"
assert repo.authors == [{"name": "Maria", "email": "maria@example.com"}]

View File

@ -21,11 +21,55 @@ def test_no_inline_event_handlers(template):
"""`default-src 'self'` with no 'unsafe-inline' means the browser ignores
an onsubmit="" attribute without complaining. A delete button written that
way loses its confirmation dialog and nobody finds out until something is
deleted by accident. Use data-confirm, handled in static/board.js."""
found = INLINE_HANDLER.findall(template.read_text(encoding="utf-8"))
deleted by accident. Use data-confirm, handled in static/board.js.
Comments stripped first, like the two guards below: base.html explains in a
Jinja comment why its account menu is a <details> rather than a button with
an onclick, and a guard that fails on its own reasoning gets deleted rather
than obeyed."""
found = INLINE_HANDLER.findall(
JINJA_COMMENT.sub("", template.read_text(encoding="utf-8")))
assert not found, f"{template.name} has inline handler(s): {found}"
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
def test_no_inline_style_blocks(template):
"""The same policy, the same silence, a different symptom.
`default-src 'self'` covers style-src too, and 'self' does not permit an
inline <style>. The browser drops the whole block without a word, and the
page arrives in Times New Roman with blue links — which is exactly how the
public profile page shipped. Put it in static/ and link it, where the
policy allows it and the browser caches it.
"""
# Comments stripped first: profile.html explains in a Jinja comment why it
# has no <style> block, and a guard that trips on its own documentation is
# a guard people delete.
html = JINJA_COMMENT.sub("", template.read_text(encoding="utf-8"))
assert "<style" not in html, (
f"{template.name} has an inline <style> block, which the CSP ignores. "
"Move it to apps/board/static/ and link it with url_for('static', …)."
)
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
def test_no_table_cell_is_told_to_be_a_flex_container(template):
"""`.actions` is display:flex, and a <td> given it stops being a table cell.
It leaves the row's layout, so its bottom border is drawn at its own content
height rather than the row's and the columns' rules no longer meet. Nothing
errors, nothing logs, the page just looks subtly broken — which is how it
survived two rounds of somebody looking straight at it. The flex row belongs
in a <div> inside the cell.
"""
html = JINJA_COMMENT.sub("", template.read_text(encoding="utf-8"))
offenders = re.findall(r"<td[^>]*class=[\"'][^\"']*\bactions\b[^\"']*[\"']", html)
assert not offenders, (
f"{template.name} puts a flex class on a <td>: {offenders}. "
"Wrap the buttons in <div class=\"actions\"> inside the cell instead."
)
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
def test_every_post_form_carries_a_csrf_token(template):
"""The hook in app.py rejects a POST without one, so a form that forgets it
@ -96,3 +140,37 @@ def test_no_message_in_the_code_shows_it_either():
and "Gitea" in node.value and node.value not in docstrings
]
assert not offenders, "\n".join(offenders)
# --- the writing boxes opt in ---------------------------------------------
PROSE_BOXES = {
"thread_form.html": "body",
"comment_form.html": "body",
"thread.html": "body",
"conversation.html": "body",
"submission_form.html": "body",
"content_form.html": "body",
"profile_edit.html": "bio",
}
@pytest.mark.parametrize("name,box", sorted(PROSE_BOXES.items()))
def test_every_prose_box_has_the_markdown_toolbar(name, box):
"""`data-markdown` is what board.js attaches the toolbar and the preview to.
A box that forgets it loses both silently — the page still works, it is just
the plain textarea it always was, which nobody files as a bug."""
html = (Path(__file__).resolve().parents[1] / "templates" / name).read_text(encoding="utf-8")
opening = re.search(rf'<textarea id="{box}"[^>]*>', html)
assert opening, f"{name} has no textarea #{box}"
assert "data-markdown" in opening.group(0), (
f"{name}: #{box} is prose and should carry data-markdown")
def test_the_fields_that_are_not_prose_stay_plain():
"""The links and FAQ boxes are parsed line by line, not rendered. A bold
button there would put asterisks into a value, not into writing."""
for name, box in (("profile_edit.html", "links"), ("content_form.html", "faq")):
html = (Path(__file__).resolve().parents[1] / "templates" / name).read_text(encoding="utf-8")
opening = re.search(rf'<textarea id="{box}"[^>]*>', html)
assert opening and "data-markdown" not in opening.group(0), name

View File

@ -32,17 +32,22 @@ languages:
weight: 1
params:
description: "Comunidad latinoamericana en Viena — turismo, cultura, gastronomía, comunidad y comercio."
# Only the two ends of the menu live here. Everything between them is built
# from the pages themselves by partials/header.html — so a page published
# from the members area appears on the site, with its own translated title,
# instead of needing three edits in this file. Weight decides the side:
# under 5 goes before the pages, 5 or more after them.
menus:
main:
- name: "Inicio"
url: "/"
weight: 1
- name: "Acerca"
url: "/page/acerca/"
weight: 2
- name: "Contacto"
url: "/page/contacto/"
weight: 3
# The way into the members area, in the menu for everybody: somebody who
# has an account needs to find the door, and somebody who does not should
# at least see that there is one.
- name: "Comunidad"
url: "/comunidad/"
weight: 9
de:
languageCode: "de"
languageName: "Deutsch"
@ -54,12 +59,9 @@ languages:
- name: "Start"
url: "/de/"
weight: 1
- name: "Über uns"
url: "/de/page/acerca/"
weight: 2
- name: "Kontakt"
url: "/de/page/contacto/"
weight: 3
- name: "Community"
url: "/comunidad/"
weight: 9
pt-br:
languageCode: "pt-BR"
languageName: "Português (Brasil)"
@ -71,14 +73,23 @@ languages:
- name: "Início"
url: "/pt-br/"
weight: 1
- name: "Sobre"
url: "/pt-br/page/acerca/"
weight: 2
- name: "Contato"
url: "/pt-br/page/contacto/"
weight: 3
- name: "Comunidade"
url: "/comunidad/"
weight: 9
params:
# The picture a share card falls back on when a post or page has none, and the
# organisation's logo in the structured data. One path — /uploads/algo.png —
# and WhatsApp, Signal, Mastodon and Bluesky all start showing an image. Left
# empty until there is a logo to put here; a link then shares as title and
# description, which is what happens today.
defaultImage: ""
# The organisation's profiles elsewhere, for `sameAs` in the Organization
# schema: it is how a search or answer engine knows the Instagram account and
# this site are the same body. One URL per line when they exist.
sameAs: []
# og:locale values per language slug (ported from theme/inc/seo.php).
localeMap:
es: "es_ES"

View File

@ -356,11 +356,23 @@ Gitea → as **pablo** → Settings → Applications → *Generate New Token*, s
CONTENT_TOKEN=
```
It falls back to `GITEA_ADMIN_TOKEN` if left empty, so an existing install
keeps working — but they should not stay the same. The admin token can create
and modify every account on the instance; publishing a post needs one
repository. Since members no longer have accounts to create, the admin token
has no remaining job and can be revoked once `CONTENT_TOKEN` is in place.
**The scope matters more than this page used to admit.** Gitea's scopes are per
category, and `admin` does not contain `repository` — a site-admin token gets a
403 from the contents API, no matter how powerful it is elsewhere. So the
fallback to `GITEA_ADMIN_TOKEN` when `CONTENT_TOKEN` is empty keeps the app
*running*, but it does not keep publishing working: with an admin-only token the
editor cannot commit at all. That is exactly what happened here, and it went
undiagnosed for three phases because the refusal escaped as a 500 on
*Contenido* and, when approving a submission, as a message blaming a missing
photograph. Both now say what is wrong, but the fix is this token.
Once `CONTENT_TOKEN` is in place, **revoke `GITEA_ADMIN_TOKEN`**: it can create
and modify every account on the instance, members no longer have accounts to
create, and it has no remaining job.
If *Contenido* says *"El servidor de git rechazó el token del editor"*, this
section is the answer: the token is missing, revoked, or scoped to something
other than the repository.
**Commits still say who wrote them.** One token does the committing, and each
commit names its author, so `git log` shows the member and there is somebody to
@ -426,15 +438,22 @@ If `github` is not a remote yet, add it once — see the end of step 8:
git remote add github https://github.com/pablovolenski/vienalatina.git
```
That rebuilds the image, copies the compose file across, restarts, and prints
the log. It never touches `/srv/board/.env` — that file holds the secrets and
lives only on the server — but it does compare it against `.env.example` and
name any setting that has appeared in the repository and is missing from yours.
New settings are always added by hand.
That takes a backup, rebuilds the image, copies the compose file across,
restarts, and prints the log. It never touches `/srv/board/.env` — that file
holds the secrets and lives only on the server — but it does compare it against
`.env.example` and name any setting that has appeared in the repository and is
missing from yours. New settings are always added by hand.
**The backup is part of the deploy now, not a thing to remember.** The app
applies numbered migrations at start-up and two of them rebuild a table in
place — `attachments`, and `members`, which holds your own account. Neither can
be undone afterwards, and "back up first" works reliably until the one deploy
where it mattered. `BOARD_SKIP_BACKUP=1` skips it if you have just taken one.
The database schema is applied at start-up with `CREATE TABLE IF NOT EXISTS`,
so a release that adds a table needs no migration step: the table appears when
the new code does.
the new code does. Anything that *changes* an existing table is a numbered
migration instead — §11.11 — and the deploy's log tail names each one it ran.
### 11.4 Route it through Caddy
@ -481,17 +500,34 @@ has been archiving air" are otherwise the same empty line.
### 11.6 Who can do what
| | Owner | Admin | User |
|---|---|---|---|
| Post, comment, edit own | ✓ | ✓ | ✓ |
| Delete any post | ✓ | ✓ | — |
| Edit someone else's post | — | — | — |
| Pin and close threads | ✓ | ✓ | — |
| Create users | ✓ | ✓ | — |
| Create admins | ✓ | — | — |
| Suspend a user | ✓ | ✓ | — |
| Suspend an admin | ✓ | — | — |
| Transfer ownership | ✓ | — | — |
| | Responsable | Administrador | Moderador | Miembro |
|---|---|---|---|---|
| Wall: post, comment, edit own | ✓ | ✓ | ✓ | ✓ |
| Private messages, own profile | ✓ | ✓ | ✓ | ✓ |
| Propose a public post | ✓ | ✓ | ✓ | ✓ |
| Publish a public post directly | ✓ | ✓ | ✓ | — |
| Approve or return a proposal | ✓ | ✓ | ✓ | — |
| Edit and delete published posts | ✓ | ✓ | ✓ | — |
| Static pages of the site | ✓ | ✓ | — | — |
| Delete any wall post | ✓ | ✓ | — | — |
| Edit someone else's post | — | — | — | — |
| Pin and close threads | ✓ | ✓ | — | — |
| Create members and moderators | ✓ | ✓ | — | — |
| Change a role (below admin) | ✓ | ✓ | — | — |
| Create admins, promote to admin | ✓ | — | — | — |
| Suspend a member or moderator | ✓ | ✓ | — | — |
| Suspend an admin | ✓ | — | — | — |
| Transfer ownership, erase a member | ✓ | — | — | — |
**A moderator has no power over people.** They decide what the public reads and
nothing else: no creating, suspending, promoting or erasing anybody. That line is
the whole point of having the role — a moderator who could also suspend the
author of a post they had just returned would be a second kind of administrator.
Admins can appoint moderators; only the owner can appoint admins. That rule lives
in one place (`may_create` in `apps/board/members.py`) and the role form on
*Miembros* checks it twice: once for reaching the person, once for the role being
given.
Nobody edits anyone else's words, administrators included. Taking a post down is
visible to the person who wrote it; rewriting it is not, and an admin who could
@ -508,7 +544,11 @@ Members' names, emails and writing are personal data under GDPR.
- **Erasure:** the owner's *Eliminar* removes the member row entirely and
reassigns their threads and comments to a tombstone shown as "Miembro
eliminado", so conversations other people took part in stay readable.
eliminado", so conversations other people took part in stay readable. Private
messages and unapproved proposals are deleted outright, pictures included. An
already-published post stays on the site: what remains of it is a commit in
the content repository carrying their name, and rewriting git history from the
members area is not something this app does.
- **Access:** any member can download everything they have written from
*Descargar mis datos*.
- **Retention:** soft-deleted posts stay in the database until removed by hand.
@ -628,6 +668,24 @@ the conversation would lose its shape; a two-party exchange has no such
remainder. This does destroy the other person's copy — the uncomfortable half
of the choice, and deliberate.
### 11.10b The members' bar on the public site
A signed-in member sees a slim bar above the public header on vienalatina.com,
with the same five sections the members area has. The public pages are files on
disk and get cached, so the bar is drawn in the browser:
`themes/vienalatina/assets/js/memberbar.js` asks `/comunidad/sesion.json` who is
reading, and that endpoint is the only thing that decides anything — a visitor
gets `{"signed_in": false}` and the answer is `Cache-Control: no-store`.
**The hint cookie is why this is not a request per page view.** Signing in also
sets `vl_sesion=1`, readable by scripts, holding nothing but the digit 1; without
it the script makes no request at all, so a stranger reading one article costs
the app nothing. It is never trusted: the session cookie stays `HttpOnly` and
signed, and forging the hint earns a reply saying you are not signed in.
*Comunidad* is in the public menu in all three languages, signed in or not,
because somebody who has an account needs to find the door.
### 11.11 Schema changes: `PRAGMA user_version`
`schema.sql` is all `CREATE TABLE IF NOT EXISTS`, which handles exactly one
@ -655,6 +713,212 @@ the one case it was never needed for.
the proof the rebuild kept real rows. Back up first — `scripts/backup-board.sh`
— as with any migration.
**Step 4 rebuilds `members` for the same reason**, to widen the role CHECK so
`moderator` is a legal value. It is the more delicate of the two: eight tables
point at `members(id)`, and the procedure drops and renames the table with
foreign keys off. The clauses in those tables say `REFERENCES members`, resolved
by name, so they find the new table by themselves — but the partial unique index
that guarantees one owner is *not* carried over by the copy and has to be
recreated, and `PRAGMA foreign_key_check` runs before the transaction commits.
Both are asserted by tests that build a database in the old shape with a row in
every referencing table.
One trap worth recording, because it cost a debugging session: the allowed roles
can only be read back out of the `CREATE TABLE` text in `sqlite_master`, and
SQLite stores that text verbatim — comments included. The comment in `schema.sql`
that explains why `moderator` needed a rebuild contains the word, so the step's
"have I already run?" check found it and skipped itself. Comments are stripped
before the check now.
**Back up before deploying this one in particular**: the table being rebuilt is
the one your own account is in, and it is irreversible in place.
### 11.12 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.
### 11.13 The five sections, and the moderation queue
Signing in lands on **Inicio**, a dashboard of what has happened since the last
visit. The navigation is the same for everybody except the last entry:
| | Where | Who |
|---|---|---|
| **Inicio** | `/comunidad/` | everybody |
| **Muro** | `/comunidad/muro` | everybody |
| **Privados** | `/comunidad/privados` | everybody |
| **Publicaciones** | `/comunidad/publicaciones` | everybody, with two different pages behind it |
| **Gestión** | `/comunidad/gestion` | admins and the owner |
Gestión holds three things: Miembros, the published **Artículos**, and the
site's static **Páginas**. A moderator cannot open it, so their route to the
published articles is the *Ya publicado* link on Publicaciones — the only one
they have, which is why it sits beside the button rather than inside a
paragraph.
*Mi perfil*, *Descargar mis datos* and *Salir* are in the menu under the member's
own name, top right. They are not sections of the site, and while they were in the
navigation three of the five entries were admin-only — which meant an ordinary
member signed in to a wall and a member list, with their own profile and their own
private messages hidden from them. `apps/board/tests/test_navigation.py` asserts
the navigation per role now, so that cannot come back quietly.
The wall moved from `/comunidad/` to `/comunidad/muro`. Thread addresses did not
move, so anything linked from a private message still works.
**Publicaciones is the queue.** A member writes a proposal; it lives in the
`submissions` table and goes nowhere near the site. A moderator or admin reads it
and either approves it — which commits it to the content repository under the
member's own name, so `git log` names the writer and not the approver — or returns
it with a reason the author reads on their own Publicaciones page. Moderators and
admins do not queue: they write in *Contenido* and their post is committed as they
save it.
Three things worth knowing about that design:
- **A pending post is not in git at all.** It could not be: a commit to that
repository *is* publication, because Gitea's webhook starts the translate →
build → deploy pipeline within seconds. There is no draft state on the site.
- **One publish path.** Approval calls `content.publish`, the same function the
editor uses, so an approved proposal is byte-identical to a post written by a
moderator and the pipeline cannot tell them apart.
- **Its picture is private until approval**, served from `/data/uploads` to the
author and the moderators only. Approving commits it to the repository and
deletes the private copy, so there is one file in one place.
- **There is no way to promote a wall thread into a proposal**, deliberately.
Writing for the public is a separate act from talking to the people you already
know, and the site is curated on purpose: fewer posts, each one read by somebody
first.
Editing a returned proposal puts it back in the queue automatically. An approved
one can no longer be edited from there — the file is in the repository, and that
is what *Contenido* is for.
**Published posts carry a byline.** The editor writes `author` into the
frontmatter, and `author_url` only when that member has published their own page
— so the article says *por Fulana* and the name links through when there is
somewhere to go. `scripts/translate.py` copies both into the German and
Portuguese siblings by itself: it carries the whole frontmatter and translates
only the title and the description. Editing a post keeps the author it already
had, so correcting somebody's typo never re-signs their article.
**On the wall itself**: one 👍 per member per post or comment, which clicking
again takes back, and every name is a link to that person's page — but only when
they have published one, so nobody is sent to a 404. Both rules live in one place
each (`templates/_reaction.html`, `templates/_person.html`) so no screen has to
remember them.
**Miembros is a directory**, not an admin table: a card per person with their
photo, username, role, the first line of their bio, somewhere to write to them
and a link to their page. Admins get the controls — suspend, re-invite, change
role, erase — inside a *Gestionar* block on each card, closed by default. A
member's photo shows here even when their public page is unpublished, because
this side is behind the login; `profiles.member_photo` serves it and the profile
form says so in plain words.
### 11.15 The public menu is built from the pages
It used to be three names per language in `config.yaml`, which meant a page
published through *Contenido* never appeared on the site, and that the German and
Portuguese menus had to be edited by hand to match. `partials/header.html` now
builds it from the pages themselves, so a page shows up when it is published,
with its own translated title.
Two fields in the editor decide where it goes:
- **`parent`** — another page's basename (`acerca` for `acerca.es.md`), which puts
this page in the submenu under that one. The basename is what `translate.py`
uses to pair siblings, so a parent chosen once holds in all three languages.
- **`weight`** — the order, lower first, 50 by default.
**URLs do not change.** A subpage is still `/page/<slug>/`; only the menu nests,
so nothing in the Caddyfile, the pipeline or the editor's filename rules has to
learn about folders. The dropdown is the one the theme already had, ported from
WordPress: hover and `:focus-within`, inline on a phone, no script.
Only *Inicio* and *Comunidad* remain in `config.yaml`. Weight under 5 puts a menu
entry before the pages, 5 or more after them.
### 11.16 Sharing, SEO and answer engines
`partials/seo-head.html` was already emitting hreflang, Open Graph, a Twitter
card and `BlogPosting` for articles. What it now also does:
- **Static pages get all of it** — they had none, so *Acerca de* shared as a bare
link. `WebPage` schema, Open Graph, the card
- **`og:image` with an alt**, from the post's own picture or `params.defaultImage`
as a fallback. That param is empty: fill it in when there is a logo, and every
link shared on WhatsApp, Signal, Mastodon or Bluesky starts carrying a picture
- **`Organization`** on the home, with `areaServed: Wien` and a `sameAs` list
ready for social profiles — this is how a search or answer engine knows the
Instagram account and this site are one body
- **`BreadcrumbList`** on every post and page, and the author's profile URL in the
article's structured data
- **Optional `FAQPage`**: `pregunta|respuesta` per line in the editor, rendered at
the foot of the page *and* described in the schema. Current guidance for
generative engines puts a short factual answer to a concrete question at the
top of what gets quoted, and this is the cheapest way to write one
- `llms.txt` lists the static pages as well as the articles
The translation pipeline carries all of it: `image_alt` joins the translated
keys, and `faq` is translated line by line with each half handled separately so
the `|` survives.
### 11.17 Writing boxes
Every box where somebody writes prose — the wall, a comment, a private message, a
proposal, the editor, a profile bio — carries a markdown toolbar and a *Vista
previa*, opted in with `data-markdown` and attached by `static/board.js`. The
preview POSTs to `/comunidad/previsualizar`, which renders with `render.to_html`:
the same function the board and the site use, so the preview cannot promise
something publishing will not deliver. A markdown parser in the browser would be
a second opinion about what somebody's text means.
Choosing a picture shows a thumbnail with its name and size before anything is
uploaded. That is the one reason `blob:` is in the `img-src` policy — a handle to
bytes already in the page, which reaches no network.
## 12. Make Gitea look like the site
Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its
@ -771,7 +1035,7 @@ belonged to the git server, its logout is POST-only and unreachable from
another domain, and one click on *Entrar* signed you straight back in. All of
that followed from delegating identity, and none of it survived taking it back.
### 11.12 When nobody can sign in
### 11.14 When nobody can sign in
Every path to a first password goes through email: the invitation when a member
is added, and *¿olvidaste tu contraseña?* afterwards. If the mailbox is down

View File

@ -14,9 +14,18 @@ BOARD_SECRET_KEY=
# database, and ignored afterwards.
BOARD_OWNER=pablo
# Optional. A site-admin token lets admins create Gitea accounts from inside
# the members area. Without it, everything works except account creation, and
# admins add people who already have a Gitea login.
# Optional, and by now almost certainly unnecessary. It could create accounts on
# the git server for new members, back when a member needed one to sign in. They
# do not: a password lives in this app's own database. Nothing in the members
# area calls it any more.
#
# It CANNOT publish. Gitea's token scopes are per category and `admin` does not
# contain `repository`, so a site-admin token gets a 403 from the contents API —
# leaving this filled in and CONTENT_TOKEN empty is how the editor ends up unable
# to commit a single post while looking configured.
#
# Fill in CONTENT_TOKEN below, then revoke this one: it can create and modify
# every account on the instance, and anything that can read this file can use it.
GITEA_ADMIN_TOKEN=
# What the content editor commits with. Members sign in here, on

View File

@ -37,6 +37,39 @@ vienalatina.com {
@board path /comunidad /comunidad/*
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)
header /llms.txt Content-Type "text/markdown; charset=utf-8"

View File

@ -11,7 +11,7 @@
# This script is the whole update, in the order that matters:
#
# git pull # done by you, first
# sudo bash scripts/deploy-board.sh
# sudo bash scripts/deploy-board.sh # backs up, builds, restarts
#
# It never touches /srv/board/.env. That file holds the secrets and exists only
# on the server; the repository has .env.example instead, and the two drifting
@ -45,10 +45,22 @@ fi
missing="$(comm -23 \
<(grep -oE '^[A-Z][A-Z0-9_]*=' "$TARGET/.env.example" | sort -u) \
<(grep -oE '^[A-Z][A-Z0-9_]*=' "$TARGET/.env" | sort -u) || true)"
note_for() {
case "${1%=}" in
CONTENT_TOKEN) echo "el editor no puede publicar nada en el sitio" ;;
GITEA_ADMIN_TOKEN) echo "sólo para cuentas del servidor de git; NO publica" ;;
MAIL_HOST|MAIL_PASSWORD) echo "no se envían invitaciones ni recuperaciones" ;;
BOARD_SECRET_KEY) echo "LA APP NO ARRANCA" ;;
*) echo "" ;;
esac
}
if [ -n "$missing" ]; then
echo
echo "!! These settings exist in .env.example but not in your .env:"
echo "$missing" | sed 's/^/ /'
while read -r name; do
printf ' %-20s %s\n' "$name" "$(note_for "$name")"
done <<< "$missing"
echo " Add them to $TARGET/.env and run this again if the feature needs them."
echo
fi
@ -62,24 +74,53 @@ if [ -n "$blank" ]; then
echo
echo "!! These are set to nothing in your .env, so their feature is off:"
while read -r name; do
case "$name" in
GITEA_ADMIN_TOKEN) note="no se pueden crear cuentas ni cambiar contraseñas" ;;
MAIL_HOST|MAIL_PASSWORD) note="no se envían invitaciones ni recuperaciones" ;;
BOARD_SECRET_KEY) note="LA APP NO ARRANCA" ;;
*) note="" ;;
esac
printf ' %-20s %s\n' "$name" "$note"
printf ' %-20s %s\n' "$name" "$(note_for "$name")"
done <<< "$blank"
echo
fi
# A backup before every restart, not only before the ones known to migrate.
#
# The app applies numbered migrations at start-up (apps/board/migrations.py), and
# two of them rebuild a table in place: `attachments`, and `members` — the table
# your own account is in. Neither can be undone once it has run. Remembering to
# back up by hand works right up until the deploy that mattered, so it happens
# here. Skipped with BOARD_SKIP_BACKUP=1 if there is no database yet.
if [ -z "${BOARD_SKIP_BACKUP:-}" ] && [ -f "${BOARD_DB:-$TARGET/data/board.db}" ]; then
echo "==> Backing up first (migrations are irreversible in place)"
bash "$REPO/scripts/backup-board.sh"
fi
# The mirror image of the check above: settings your .env holds that
# .env.example no longer documents. Those are what a feature looks like after it
# is removed — the OAuth client id and secret outlived the login they belonged
# to by two phases, sitting in a file as live credentials for a flow nothing
# calls. A commented-out line in the example counts as undocumented, which is
# how a setting is retired: comment it there, and this names it here.
#
# Named, never touched: this script has never written to .env and does not start
# now. Deleting a line is a decision, and the file may hold something deliberate
# that the repository does not know about.
stale="$(comm -13 \
<(grep -oE '^[A-Z][A-Z0-9_]*=' "$TARGET/.env.example" | sort -u) \
<(grep -oE '^[A-Z][A-Z0-9_]*=' "$TARGET/.env" | sort -u) || true)"
if [ -n "$stale" ]; then
echo
echo "!! Your .env has settings the repository no longer documents:"
echo "$stale" | sed 's/^/ /'
echo " Nothing reads them. If one holds a secret, revoke it and delete the line."
echo
fi
echo "==> Restarting"
cd "$TARGET"
docker compose up -d --force-recreate
# The schema is applied at start-up with CREATE TABLE IF NOT EXISTS, so a new
# table arrives with the new code. If the container is not up a few seconds
# later it died during that, and the log says why.
# The schema is applied at start-up with CREATE TABLE IF NOT EXISTS and then the
# numbered migrations run, so a new table and a changed one both arrive with the
# new code. If the container is not up a few seconds later it died during that,
# and the log says why — the log line naming each migration applied is the one
# to read.
sleep 3
docker compose ps
echo

View File

@ -60,7 +60,14 @@ CONTENT_DIR = REPO_ROOT / "content"
# Frontmatter strings translated alongside the body. Note `categories` is
# deliberately absent: the taxonomy terms stay Spanish in every language, or
# Hugo would fork the taxonomy per language.
TRANSLATED_KEYS = ("title", "description")
TRANSLATED_KEYS = ("title", "description", "image_alt")
# `faq` is a list of "question|answer" lines, so it cannot go through the loop
# above: str() on a list would translate the brackets. Each half is translated
# separately and rejoined, because the separator has to survive — a translator
# handed "¿Dónde es?|En la plaza" is free to move or drop that bar, and a line
# without it is dropped on the way out.
FAQ_KEY = "faq"
BOT_NAME = "vienalatina-translations"
BOT_EMAIL = "translations@vienalatina.com"
@ -220,6 +227,20 @@ def orphaned_siblings() -> list[Path]:
return orphans
def translate_faq(entries, src_lang: str, tgt: str, provider) -> list[str]:
"""Translate each half of each `question|answer` line, keeping the bar."""
out = []
for entry in entries or []:
question, separator, answer = str(entry).partition("|")
if not separator:
continue
out.append("{}|{}".format(
translate_text(question.strip(), src_lang, tgt, provider),
translate_text(answer.strip(), src_lang, tgt, provider),
))
return out
def translate_file(source: Path, basename: str, src_lang: str, provider) -> list[Path]:
fm, body = split_frontmatter(source.read_text(encoding="utf-8"))
written: list[Path] = []
@ -237,6 +258,8 @@ def translate_file(source: Path, basename: str, src_lang: str, provider) -> list
for key in TRANSLATED_KEYS:
if fm.get(key):
new_fm[key] = translate_text(str(fm[key]), src_lang, tgt, provider)
if fm.get(FAQ_KEY):
new_fm[FAQ_KEY] = translate_faq(fm[FAQ_KEY], src_lang, tgt, provider)
new_fm["lang"] = tgt
new_fm["translated_from"] = src_lang
new_fm["manual_translation"] = False

View File

@ -1090,6 +1090,18 @@ a.group-pill:hover {
letter-spacing: 0.06em;
}
/* The byline on an article. It sits in the same meta row as the category and
the date, so it inherits their colour and size; only the link needs saying. */
.article-card__by a {
color: var(--brand-dark, #9a2a0f);
text-decoration: none;
border-bottom: 1px dotted currentColor;
}
.article-card__by a:hover {
border-bottom-style: solid;
}
.article-card__title {
margin: 0 0 10px;
font-size: 1.35rem;
@ -3703,3 +3715,104 @@ a.notif-card__message:hover {
.site-bar__inner { padding: 8px 12px; }
.site-bar__btn { padding: 7px 12px; font-size: 0.82rem; }
}
/* --- preguntas frecuentes ---------------------------------------------- */
/*
* Rendered from the `faq` frontmatter, and described by FAQPage structured data
* — which is why it has to be visible: schema for something a reader cannot see
* is what search engines penalise.
*/
.faq {
margin: 40px 0 0;
padding-top: 24px;
border-top: 1px solid var(--border-light, #e0cec8);
}
.faq h2 {
font-size: 1.15rem;
margin: 0 0 16px;
}
.faq dl {
margin: 0;
}
.faq dt {
font-weight: 700;
margin-top: 16px;
}
.faq dd {
margin: 4px 0 0;
color: var(--muted, #5c3d37);
line-height: 1.55;
}
/* --- the members' bar -------------------------------------------------- */
/*
* Drawn by assets/js/memberbar.js when somebody is signed in, above everything
* else. Deliberately in the brand colour and deliberately not subtle: its whole
* job is to answer "am I signed in, and where is the rest of it" from any page
* on the public site.
*/
.member-bar {
background: var(--brand, #c0391c);
color: #fff;
font-size: 0.86rem;
}
.member-bar__inner {
max-width: 1000px;
margin: 0 auto;
padding: 6px 16px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
}
.member-bar__links {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.member-bar a,
.member-bar__out {
color: #fff;
text-decoration: none;
opacity: 0.92;
}
.member-bar a:hover,
.member-bar__out:hover {
opacity: 1;
text-decoration: underline;
}
.member-bar__account {
display: flex;
align-items: center;
gap: 12px;
}
.member-bar__name {
font-weight: 700;
}
.member-bar form {
margin: 0;
}
/* A button that reads as part of the bar rather than as a form control. */
.member-bar__out {
background: none;
border: 0;
padding: 0;
font: inherit;
cursor: pointer;
}

View File

@ -0,0 +1,87 @@
// The signed-in strip on the public site.
//
// vienalatina.com is files on disk. They are the same files for everyone and
// they get cached, so the one thing they cannot contain is who is reading them.
// This asks the members area instead, and draws a bar above the header when the
// answer is somebody.
//
// Three decisions worth knowing before changing anything here:
//
// * **It does nothing without the hint cookie.** `vl_sesion` is set at sign-in
// and cleared at sign-out, holds the digit 1, and exists so that a stranger
// reading one article costs zero requests to the app. It is not trusted for
// anything: the server decides, and a forged hint earns a request that says
// "not signed in".
// * **Every value goes in as text, never as HTML.** A display name is whatever
// somebody typed into a form. textContent makes that a name; innerHTML would
// make it a script.
// * **No frameworks, no build step.** Hugo fingerprints this file and serves it
// from our own domain, which is the only place the site loads anything from.
(function () {
"use strict";
if (document.cookie.indexOf("vl_sesion=1") === -1) {
return;
}
function el(tag, className, text) {
var node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
function draw(state) {
var bar = el("div", "member-bar");
bar.setAttribute("role", "navigation");
bar.setAttribute("aria-label", "Área de miembros");
var inner = el("div", "member-bar__inner");
var links = el("ul", "member-bar__links");
state.sections.forEach(function (section) {
var item = document.createElement("li");
var link = el("a", null, section.label);
link.href = section.url;
item.appendChild(link);
links.appendChild(item);
});
inner.appendChild(links);
var account = el("div", "member-bar__account");
var me = el("a", "member-bar__name", state.name);
me.href = state.profile;
account.appendChild(me);
// A real form, because signing out changes something and a link that
// changes something is a link a prefetching browser will follow by itself.
var form = document.createElement("form");
form.method = "post";
form.action = state.logout;
var token = document.createElement("input");
token.type = "hidden";
token.name = "csrf_token";
token.value = state.csrf;
form.appendChild(token);
var out = el("button", "member-bar__out", "Salir");
out.type = "submit";
form.appendChild(out);
account.appendChild(form);
inner.appendChild(account);
bar.appendChild(inner);
document.body.insertBefore(bar, document.body.firstChild);
document.body.classList.add("has-member-bar");
}
fetch("/comunidad/sesion.json", { credentials: "same-origin" })
.then(function (response) {
return response.ok ? response.json() : null;
})
.then(function (state) {
if (state && state.signed_in) draw(state);
})
.catch(function () {
// The members area being down is not a reason for the public site to
// report anything. No bar, no message, no console noise.
});
})();

View File

@ -11,6 +11,11 @@
{{ range .AlternativeOutputFormats -}}
<link rel="{{ .Rel }}" type="{{ .MediaType.Type }}" href="{{ .Permalink | safeURL }}">
{{ end -}}
{{/* The members' bar, drawn in the browser because these pages are files on
disk and get cached. It makes no request at all unless the reader has a
session — see the comment at the top of the file. */}}
{{ $bar := resources.Get "js/memberbar.js" | minify | fingerprint }}
<script src="{{ $bar.RelPermalink }}" integrity="{{ $bar.Data.Integrity }}" defer></script>
</head>
<body>

View File

@ -13,6 +13,23 @@
<time datetime="{{ .Date.Format "2006-01-02T15:04:05-07:00" }}">
{{ .Date.Format "2 Jan 2006" }}
</time>
{{/* Who wrote it. The members area writes `author` into the
frontmatter when it publishes, and `author_url` only when
that person has published their own page — so the name is
a link when there is somewhere to go and plain text when
there is not. Posts written before this, and anything
migrated from WordPress, simply have neither and show
nothing. */}}
{{ with .Params.author }}
<span class="article-card__by">
por
{{ with $.Params.author_url }}
<a href="{{ . | relURL }}">{{ $.Params.author }}</a>
{{ else }}
{{ . }}
{{ end }}
</span>
{{ end }}
</div>
</div>
</header>
@ -31,6 +48,25 @@
{{ .Content }}
</div>
{{/* Questions and answers, written in the editor as one
`pregunta|respuesta` per line. Rendered here as well as in the
FAQPage schema: structured data describing something a visitor
cannot see is exactly what search engines penalise. */}}
{{ with .Params.faq }}
<section class="faq">
<h2>Preguntas frecuentes</h2>
<dl>
{{ range . }}
{{ $parts := split . "|" }}
{{ if ge (len $parts) 2 }}
<dt>{{ trim (index $parts 0) " " }}</dt>
<dd>{{ trim (delimit (after 1 $parts) "|") " " }}</dd>
{{ end }}
{{ end }}
</dl>
</section>
{{ end }}
<a class="back-link" href="{{ .Site.Home.Permalink }}">
← Volver al inicio
</a>

View File

@ -6,6 +6,11 @@ Site home: {{ .Site.Home.Permalink }}
This site publishes in Spanish. Every article has server-rendered German (/de/) and Brazilian Portuguese (/pt-br/) translations, linked via hreflang.
## About this site
{{ range where .Site.RegularPages "Section" "page" -}}
- [{{ .Title }}]({{ .Permalink }}): {{ .Description | default (.Summary | plainify | truncate 200) }}
{{ end }}
## Recent articles
{{ range first 50 (where .Site.RegularPages "Section" "post") -}}

View File

@ -0,0 +1,34 @@
{{/* BreadcrumbList — where this page sits, for a search result and for an answer
engine deciding what a page is about.
Two levels for a page (Inicio → this), three for an article (Inicio → its
category → this). Nothing is rendered visibly: the site is shallow enough
that a visible trail would be clutter, while the machine-readable one still
answers "what is this page part of".
A subpage says Inicio → its parent → itself, read from the same `parent`
basename the menu is built from, so the trail and the menu cannot disagree. */}}
{{ $items := slice (dict "@type" "ListItem" "position" 1 "name" "Inicio" "item" .Site.Home.Permalink) }}
{{ $position := 2 }}
{{ if eq .Section "post" }}
{{ range first 1 (.GetTerms "categories") }}
{{ $items = $items | append (dict "@type" "ListItem" "position" $position "name" .LinkTitle "item" .Permalink) }}
{{ $position = add $position 1 }}
{{ end }}
{{ else }}
{{ with .Params.parent }}
{{ $base := . }}
{{ range where $.Site.RegularPages "Section" "page" }}
{{ with .File }}{{ if eq .ContentBaseName $base }}
{{ $items = $items | append (dict "@type" "ListItem" "position" $position "name" $.Page.Title "item" $.Permalink) }}
{{ end }}{{ end }}
{{ end }}
{{ end }}
{{ end }}
{{ $items = $items | append (dict "@type" "ListItem" "position" $position "name" .Title "item" .Permalink) }}
<script type="application/ld+json">{{ (dict
"@context" "https://schema.org"
"@type" "BreadcrumbList"
"itemListElement" $items) | jsonify (dict "indent" " ") | safeJS }}</script>

View File

@ -0,0 +1,29 @@
{{/* FAQPage — the single highest-value thing a community page can carry for an
answer engine, because a question with a short factual answer is exactly the
shape those engines quote.
Written in the editor as one `pregunta|respuesta` per line, the same shape
the profile links field uses, and parsed here: a line without a separator is
dropped rather than half-rendered. The questions are also shown on the page
by single.html — schema describing something a visitor cannot see is the
kind of thing search engines penalise, and rightly. */}}
{{ $entries := slice }}
{{ range .Params.faq }}
{{ $parts := split . "|" }}
{{ if ge (len $parts) 2 }}
{{ $question := trim (index $parts 0) " " }}
{{ $answer := trim (delimit (after 1 $parts) "|") " " }}
{{ if and $question $answer }}
{{ $entries = $entries | append (dict
"@type" "Question"
"name" $question
"acceptedAnswer" (dict "@type" "Answer" "text" $answer)) }}
{{ end }}
{{ end }}
{{ end }}
{{ with $entries }}
<script type="application/ld+json">{{ (dict
"@context" "https://schema.org"
"@type" "FAQPage"
"mainEntity" .) | jsonify (dict "indent" " ") | safeJS }}</script>
{{ end }}

View File

@ -12,10 +12,72 @@
</nav>
</div>
{{/* The menu is built from the pages themselves, not from a list in
config.yaml. It used to be three names written there, which meant a page
published from the members area never appeared on the site at all — and
that the German and Portuguese menus had to be kept in step by hand.
Built this way, a new page shows up when it is published, with its own
translated title in each language.
Two levels: a page with `parent: <basename>` in its frontmatter hangs
under the page with that basename. The basename is the one translate.py
already uses to pair siblings — `acerca` for acerca.es.md, acerca.de.md
and acerca.pt-br.md — so a parent set once holds in all three languages.
Only Inicio and Comunidad stay in config.yaml, before and after the
pages, which is what the weight split below is reading. */}}
{{ $current := . }}
{{/* A dict per page rather than sorting the pages directly: `weight` is
optional, and sorting on a key half of them do not carry puts the rest
in an order nobody chose. Defaulted here, once. */}}
{{ $pages := slice }}
{{ range where .Site.RegularPages "Section" "page" }}
{{ $base := "" }}
{{ with .File }}{{ $base = .ContentBaseName }}{{ end }}
{{ $pages = $pages | append (dict
"title" .LinkTitle
"url" .RelPermalink
"page" .
"base" $base
"parent" (.Params.parent | default "")
"w" (.Params.weight | default 50)) }}
{{ end }}
{{ $pages = sort $pages "w" }}
<nav class="site-bar__pages" id="site-bar-pages" aria-label="Secciones">
<ul class="page-nav">
{{ $current := . }}
{{ range .Site.Menus.main }}
{{ range where .Site.Menus.main "Weight" "<" 5 }}
<li{{ if $current.IsMenuCurrent "main" . }} class="current-menu-item"{{ end }}>
<a href="{{ .URL }}">{{ .Name }}</a>
</li>
{{ end }}
{{ range where $pages "parent" "" }}
{{ $children := where $pages "parent" .base }}
{{/* The class names are the ones main.css already styles — ported
from the WordPress theme, dropdown on hover and on focus-within,
inline on a phone, with a ▾ on anything that has children. There
was no reason to invent a second set. */}}
{{ $classes := slice }}
{{ if $children }}{{ $classes = $classes | append "menu-item-has-children" }}{{ end }}
{{ if eq $current.RelPermalink .url }}{{ $classes = $classes | append "current-menu-item" }}{{ end }}
<li{{ with $classes }} class="{{ delimit . " " }}"{{ end }}>
<a href="{{ .url }}">{{ .title }}</a>
{{ with $children }}
{{/* Opens on hover and on focus — CSS only, so it works with a
keyboard and needs no script. */}}
<ul class="sub-menu">
{{ range . }}
<li{{ if eq $current.RelPermalink .url }} class="current-menu-item"{{ end }}>
<a href="{{ .url }}">{{ .title }}</a>
</li>
{{ end }}
</ul>
{{ end }}
</li>
{{ end }}
{{ range where .Site.Menus.main "Weight" ">=" 5 }}
<li{{ if $current.IsMenuCurrent "main" . }} class="current-menu-item"{{ end }}>
<a href="{{ .URL }}">{{ .Name }}</a>
</li>

View File

@ -5,6 +5,20 @@
{{ $locale := index $localeMap .Language.Lang | default "es_ES" }}
{{ $desc := "" }}
{{ if .IsPage }}{{ $desc = .Description | default (.Summary | plainify | truncate 200) }}{{ else }}{{ $desc = .Site.Params.description }}{{ end }}
{{/* One line, always. A summary pulled out of the body arrives with the line
breaks the prose had, and a newline inside og:description is a card that
renders raggedly in some readers and truncated in others. */}}
{{ $desc = trim ($desc | plainify | replaceRE "\\s+" " ") " " }}
{{/* The picture a share card shows. A page's own image when it has one, the
site default when it does not — `params.defaultImage` is empty until the
logo arrives, and a card with no picture is what happens meanwhile, which is
also what happens today. Absolute, because WhatsApp, Signal, Mastodon and
Bluesky all fetch it from outside and a relative path means nothing to
them. */}}
{{ $image := "" }}
{{ with .Params.image }}{{ $image = . | absURL }}
{{ else }}{{ with .Site.Params.defaultImage }}{{ $image = . | absURL }}{{ end }}{{ end }}
<meta name="description" content="{{ $desc }}">
@ -29,11 +43,19 @@
{{ range .Translations }}
{{ with index $localeMap .Language.Lang }}<meta property="og:locale:alternate" content="{{ . }}">{{ end }}
{{ end }}
{{ with .Params.image }}<meta property="og:image" content="{{ . | absURL }}">{{ end }}
{{ with $image }}
<meta property="og:image" content="{{ . }}">
<meta property="og:image:alt" content="{{ $.Params.image_alt | default $.Title }}">
{{ end }}
<meta property="article:published_time" content="{{ .Date.Format "2006-01-02T15:04:05-07:00" }}">
<meta property="article:modified_time" content="{{ .Lastmod.Format "2006-01-02T15:04:05-07:00" }}">
{{ with .Params.author }}<meta property="article:author" content="{{ . }}">{{ end }}
{{ range first 1 (.GetTerms "categories") }}<meta property="article:section" content="{{ .LinkTitle }}">{{ end }}
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:card" content="{{ if $image }}summary_large_image{{ else }}summary{{ end }}">
<meta name="twitter:title" content="{{ .Title }}">
<meta name="twitter:description" content="{{ $desc }}">
{{ with $image }}<meta name="twitter:image" content="{{ . }}">{{ end }}
{{ $schema := dict
"@context" "https://schema.org"
@ -46,10 +68,23 @@
"dateModified" (.Lastmod.Format "2006-01-02T15:04:05-07:00")
"author" (dict "@type" "Person" "name" (.Params.author | default .Site.Title))
"publisher" (dict "@type" "Organization" "name" .Site.Title "url" .Site.Home.Permalink)
"mainEntityOfPage" (dict "@type" "WebPage" "@id" .Permalink)
}}
{{ with .Params.image }}{{ $schema = merge $schema (dict "image" (. | absURL)) }}{{ end }}
{{/* The author's own page, when they have published one. An answer engine
citing this article can then say who wrote it and point somewhere real —
which is the whole reason the byline carries a URL. */}}
{{ with .Params.author_url }}
{{ $schema = merge $schema (dict "author" (dict
"@type" "Person"
"name" ($.Params.author | default $.Site.Title)
"url" (. | absURL))) }}
{{ end }}
{{ with $image }}{{ $schema = merge $schema (dict "image" .) }}{{ end }}
<script type="application/ld+json">{{ $schema | jsonify (dict "indent" " ") | safeJS }}</script>
{{ partial "breadcrumbs-schema.html" . }}
{{ partial "faq-schema.html" . }}
{{ else if .IsHome }}
{{/* ---- Home ---- */}}
<meta property="og:type" content="website">
@ -59,6 +94,18 @@
<meta property="og:url" content="{{ .Permalink }}">
<meta property="og:locale" content="{{ $locale }}">
{{ $org := dict
"@context" "https://schema.org"
"@type" "Organization"
"name" .Site.Title
"url" .Site.Home.Permalink
"description" .Site.Params.description
"areaServed" (dict "@type" "City" "name" "Wien" "addressCountry" "AT")
}}
{{ with .Site.Params.defaultImage }}{{ $org = merge $org (dict "logo" (. | absURL)) }}{{ end }}
{{ with .Site.Params.sameAs }}{{ $org = merge $org (dict "sameAs" .) }}{{ end }}
<script type="application/ld+json">{{ $org | jsonify (dict "indent" " ") | safeJS }}</script>
{{ $posts := first 10 (where .Site.RegularPages "Section" "post") }}
{{ $blogPost := slice }}
{{ range $posts }}
@ -82,4 +129,46 @@
}}
{{ if $blogPost }}{{ $schema = merge $schema (dict "blogPost" $blogPost) }}{{ end }}
<script type="application/ld+json">{{ $schema | jsonify (dict "indent" " ") | safeJS }}</script>
{{ else if .IsPage }}
{{/* ---- A static page: Acerca de, Contacto, their subpages ----
This branch did not exist, so a page shared as a bare link — no title card,
no picture, nothing for an answer engine to read beyond the prose. It is a
document about the organisation rather than an article, hence WebPage
rather than BlogPosting, and no author: a page is the site speaking. */}}
<meta property="og:type" content="website">
<meta property="og:site_name" content="{{ .Site.Title }}">
<meta property="og:title" content="{{ .Title }}">
<meta property="og:description" content="{{ $desc }}">
<meta property="og:url" content="{{ .Permalink }}">
<meta property="og:locale" content="{{ $locale }}">
{{ range .Translations }}
{{ with index $localeMap .Language.Lang }}<meta property="og:locale:alternate" content="{{ . }}">{{ end }}
{{ end }}
{{ with $image }}
<meta property="og:image" content="{{ . }}">
<meta property="og:image:alt" content="{{ $.Params.image_alt | default $.Title }}">
{{ end }}
<meta name="twitter:card" content="{{ if $image }}summary_large_image{{ else }}summary{{ end }}">
<meta name="twitter:title" content="{{ .Title }}">
<meta name="twitter:description" content="{{ $desc }}">
{{ with $image }}<meta name="twitter:image" content="{{ . }}">{{ end }}
{{ $schema := dict
"@context" "https://schema.org"
"@type" "WebPage"
"inLanguage" .Site.Language.LanguageCode
"name" .Title
"description" $desc
"url" .Permalink
"dateModified" (.Lastmod.Format "2006-01-02T15:04:05-07:00")
"isPartOf" (dict "@type" "WebSite" "name" .Site.Title "url" .Site.Home.Permalink)
"publisher" (dict "@type" "Organization" "name" .Site.Title "url" .Site.Home.Permalink)
}}
{{ with $image }}{{ $schema = merge $schema (dict "image" .) }}{{ end }}
<script type="application/ld+json">{{ $schema | jsonify (dict "indent" " ") | safeJS }}</script>
{{ partial "breadcrumbs-schema.html" . }}
{{ partial "faq-schema.html" . }}
{{ end }}