Merge branch 'claude/relaxed-faraday-h4zd09' of https://github.com/pablovolenski/vienalatina
This commit is contained in:
commit
f507a057aa
52
README.md
52
README.md
@ -145,37 +145,51 @@ 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
|
||||
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
|
||||
tokens.py per-member access tokens, refreshed before they expire
|
||||
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, 97 checks — `python3 -m pytest apps/board/tests`
|
||||
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.
|
||||
|
||||
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 +197,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
|
||||
|
||||
@ -94,8 +94,11 @@ 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, profiles, 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)
|
||||
@ -116,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():
|
||||
|
||||
@ -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:
|
||||
@ -63,13 +63,13 @@ def _safe_next(target: str) -> str:
|
||||
own community site.
|
||||
"""
|
||||
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 +98,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()
|
||||
|
||||
@ -176,7 +176,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()
|
||||
|
||||
|
||||
@ -93,9 +93,14 @@ 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,
|
||||
|
||||
@ -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,19 @@ 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,
|
||||
"folder": "content/post", "dated": True, "role": "moderator",
|
||||
},
|
||||
"page": {
|
||||
"label": "Páginas", "singular": "Página",
|
||||
"folder": "content/page", "dated": False,
|
||||
"folder": "content/page", "dated": False, "role": "admin",
|
||||
},
|
||||
}
|
||||
|
||||
@ -166,9 +171,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:
|
||||
@ -212,46 +230,70 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]:
|
||||
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 _upload_image() -> str:
|
||||
upload = request.files.get("picture")
|
||||
if not upload or not upload.filename:
|
||||
return ""
|
||||
return commit_picture(upload.read(), upload.filename)
|
||||
|
||||
|
||||
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.
|
||||
"""
|
||||
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,11 +302,11 @@ 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":
|
||||
@ -280,12 +322,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 +331,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)
|
||||
@ -348,7 +385,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 +405,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.
|
||||
|
||||
|
||||
111
apps/board/home.py
Normal file
111
apps/board/home.py
Normal file
@ -0,0 +1,111 @@
|
||||
"""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, render_template
|
||||
|
||||
from . import submissions
|
||||
from .db import TOMBSTONE_LOGIN, get_db
|
||||
from .render import excerpt
|
||||
from .security import admin_required, login_required
|
||||
|
||||
bp = Blueprint("home", __name__)
|
||||
|
||||
RECENT = 5
|
||||
|
||||
|
||||
@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,
|
||||
(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,
|
||||
(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
|
||||
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("/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)
|
||||
@ -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
|
||||
@ -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,18 @@ REMOVED_ON_ERASE = {
|
||||
("messages", "author_id"),
|
||||
("blocks", "blocker_id"),
|
||||
("blocks", "blocked_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 = ?"
|
||||
@ -150,6 +179,14 @@ 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))
|
||||
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.
|
||||
@ -184,7 +221,8 @@ def index():
|
||||
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)
|
||||
@ -319,11 +357,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")
|
||||
|
||||
@ -122,7 +122,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)
|
||||
@ -165,7 +165,7 @@ def talk(member_id: int):
|
||||
abort(400)
|
||||
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 other is None:
|
||||
|
||||
@ -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.
|
||||
|
||||
@ -122,12 +141,78 @@ def _members_get_a_public_page(db: sqlite3.Connection) -> None:
|
||||
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),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@ -85,7 +85,7 @@ def _published(login: str):
|
||||
"""SELECT * FROM members
|
||||
WHERE gitea_login = ? COLLATE NOCASE
|
||||
AND profile_published = 1 AND active = 1
|
||||
AND role IN ('owner', 'admin', 'user')""",
|
||||
AND role != 'tombstone'""",
|
||||
(login,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
@ -20,7 +20,10 @@ CREATE TABLE IF NOT EXISTS members (
|
||||
bio TEXT,
|
||||
links TEXT, -- JSON array of {label, url}
|
||||
photo_name TEXT,
|
||||
role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')),
|
||||
-- '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),
|
||||
@ -216,3 +219,49 @@ 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);
|
||||
|
||||
@ -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
|
||||
|
||||
@ -324,3 +324,112 @@ 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);
|
||||
}
|
||||
|
||||
/* --- 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;
|
||||
}
|
||||
|
||||
390
apps/board/submissions.py
Normal file
390
apps/board/submissions.py
Normal file
@ -0,0 +1,390 @@
|
||||
"""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,
|
||||
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
|
||||
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"]}
|
||||
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,
|
||||
}
|
||||
try:
|
||||
if row["photo_name"]:
|
||||
data = (uploads.directory() / row["photo_name"]).read_bytes()
|
||||
fields["image"] = content.commit_picture(data, row["photo_name"], author)
|
||||
path = content.publish("post", fields, row["body_md"], author)
|
||||
except gitea.GiteaError as exc:
|
||||
flash(str(exc), "error")
|
||||
return redirect(url_for("submissions.show", submission_id=submission_id))
|
||||
except OSError:
|
||||
current_app.logger.exception("submission %s: picture missing on disk", submission_id)
|
||||
flash("No se encontró la imagen en el disco. Pide al autor que la vuelva a subir.",
|
||||
"error")
|
||||
return redirect(url_for("submissions.show", submission_id=submission_id))
|
||||
|
||||
get_db().execute(
|
||||
"""UPDATE submissions
|
||||
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
|
||||
@ -16,30 +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>
|
||||
{# <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('profiles.edit') }}">Mi perfil</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 %}
|
||||
@ -58,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>
|
||||
|
||||
@ -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 %}
|
||||
|
||||
51
apps/board/templates/gestion.html
Normal file
51
apps/board/templates/gestion.html
Normal file
@ -0,0 +1,51 @@
|
||||
{% 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>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 %}
|
||||
82
apps/board/templates/home.html
Normal file
82
apps/board/templates/home.html
Normal file
@ -0,0 +1,82 @@
|
||||
{% extends "base.html" %}
|
||||
{% 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">{{ item.author }} · {{ 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">{{ t.author }} · {{ 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 %}
|
||||
@ -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">
|
||||
|
||||
@ -48,13 +48,26 @@
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% if is_owner %}
|
||||
<form method="post" action="{{ url_for('members.set_role', member_id=m.id) }}">
|
||||
{# A toggle worked while there were two roles. With three it has to
|
||||
be a choice, and the options are the ones this person may
|
||||
actually grant — the handler checks the same thing. #}
|
||||
{% if is_owner or m.role != 'admin' %}
|
||||
<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() }}">
|
||||
<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>
|
||||
<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?">
|
||||
|
||||
73
apps/board/templates/submission.html
Normal file
73
apps/board/templates/submission.html
Normal file
@ -0,0 +1,73 @@
|
||||
{% extends "base.html" %}
|
||||
{% 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>{{ item.author }}</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 %}
|
||||
55
apps/board/templates/submission_form.html
Normal file
55
apps/board/templates/submission_form.html
Normal 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" 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 %}
|
||||
86
apps/board/templates/submissions.html
Normal file
86
apps/board/templates/submissions.html
Normal file
@ -0,0 +1,86 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Publicaciones{% endblock %}
|
||||
|
||||
{% block main %}
|
||||
<div class="feed-head">
|
||||
<h1>Publicaciones</h1>
|
||||
{% if can_moderate %}
|
||||
<a class="btn" href="{{ url_for('content.new', collection='post') }}">Publicar</a>
|
||||
{% 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.
|
||||
<a href="{{ url_for('content.index') }}">Ver lo ya publicado</a>.
|
||||
{% 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>{{ item.author }}</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 %}
|
||||
@ -1,15 +1,15 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Mensajes{% endblock %}
|
||||
{% 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 %}
|
||||
|
||||
|
||||
@ -308,3 +308,51 @@ 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)
|
||||
|
||||
@ -34,6 +34,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 +267,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_%'")]
|
||||
|
||||
@ -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})
|
||||
|
||||
118
apps/board/tests/test_navigation.py
Normal file
118
apps/board/tests/test_navigation.py
Normal file
@ -0,0 +1,118 @@
|
||||
"""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
|
||||
399
apps/board/tests/test_submissions.py
Normal file
399
apps/board/tests/test_submissions.py
Normal file
@ -0,0 +1,399 @@
|
||||
"""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.")
|
||||
@ -21,8 +21,14 @@ 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}"
|
||||
|
||||
|
||||
|
||||
@ -426,15 +426,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 +488,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 +532,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.
|
||||
@ -655,7 +683,27 @@ 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.
|
||||
|
||||
### 11.13 Public profiles at `vienalatina.com/su-nombre`
|
||||
**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
|
||||
@ -700,6 +748,57 @@ 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 |
|
||||
|
||||
*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.
|
||||
|
||||
## 12. Make Gitea look like the site
|
||||
|
||||
Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its
|
||||
@ -816,7 +915,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
|
||||
|
||||
@ -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
|
||||
@ -73,13 +73,27 @@ if [ -n "$blank" ]; then
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
Loading…
Reference in New Issue
Block a user