Merge branch 'claude/relaxed-faraday-h4zd09' of https://github.com/pablovolenski/vienalatina
This commit is contained in:
commit
388771bba6
95
apps/board/activity.py
Normal file
95
apps/board/activity.py
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
"""Who did what, for the superadministrator to read.
|
||||||
|
|
||||||
|
An audit trail is the natural companion to a role that can do everything: the
|
||||||
|
question "who made them an administrator?" has no other answer, and the moment
|
||||||
|
anybody asks it is exactly the moment nobody can remember.
|
||||||
|
|
||||||
|
**Deliberately not a general event store.** One row per act that changes who can
|
||||||
|
do what, or what the public sees. No page views, no successful sign-ins, no
|
||||||
|
"somebody opened Miembros" — a log that records everything is a log nobody
|
||||||
|
reads, and this one has to be readable by a person scrolling it once a month.
|
||||||
|
|
||||||
|
`log()` never raises. A failure to write the diary must not fail the thing being
|
||||||
|
recorded: an administrator who could not be appointed because the note about it
|
||||||
|
could not be saved is a worse outcome than a gap in the notes.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from flask import Blueprint, current_app, g, render_template, request
|
||||||
|
|
||||||
|
from .db import get_db
|
||||||
|
from .security import superadmin_required
|
||||||
|
|
||||||
|
bp = Blueprint("activity", __name__)
|
||||||
|
|
||||||
|
PER_PAGE = 60
|
||||||
|
|
||||||
|
# action key -> the sentence a person reads. Built here rather than stored,
|
||||||
|
# because the stored key is what a later reader greps for and the wording is
|
||||||
|
# what changes. `{object}` is whatever the act was done to.
|
||||||
|
SENTENCES = {
|
||||||
|
"member.created": "dio de alta a {object}",
|
||||||
|
"member.invited": "envió una invitación a {object}",
|
||||||
|
"member.suspended": "suspendió a {object}",
|
||||||
|
"member.restored": "reactivó a {object}",
|
||||||
|
"member.erased": "eliminó a {object}",
|
||||||
|
"role.changed": "cambió el rol de {object}",
|
||||||
|
"chair.owner": "nombró responsable a {object}",
|
||||||
|
"chair.superadmin": "entregó la plataforma a {object}",
|
||||||
|
"submission.approved": "publicó la propuesta «{object}»",
|
||||||
|
"submission.rejected": "devolvió la propuesta «{object}»",
|
||||||
|
"content.published": "publicó «{object}»",
|
||||||
|
"content.deleted": "retiró «{object}»",
|
||||||
|
"brand.saved": "cambió el aspecto del sitio",
|
||||||
|
"brand.restored": "restauró el aspecto de fábrica",
|
||||||
|
"identity.saved": "cambió la identidad del sitio",
|
||||||
|
"media.deleted": "borró la imagen {object}",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def log(action: str, object_name: str = "", detail: str = "") -> None:
|
||||||
|
"""Record one act. Call it after the thing succeeded, never before.
|
||||||
|
|
||||||
|
Swallows everything on purpose — see the module docstring. The log line it
|
||||||
|
writes instead is what tells somebody the diary is broken.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
get_db().execute(
|
||||||
|
"INSERT INTO activity (actor_id, action, object, detail) VALUES (?, ?, ?, ?)",
|
||||||
|
(g.member["id"] if getattr(g, "member", None) else None,
|
||||||
|
action, str(object_name)[:200], str(detail)[:400]),
|
||||||
|
)
|
||||||
|
except Exception: # pragma: no cover - defensive
|
||||||
|
current_app.logger.warning("could not write activity %r", action, exc_info=True)
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/gestion/registro")
|
||||||
|
@superadmin_required
|
||||||
|
def index():
|
||||||
|
page = max(0, request.args.get("p", type=int) or 0)
|
||||||
|
rows = get_db().execute(
|
||||||
|
"""SELECT a.*, m.display_name AS actor, m.gitea_login AS actor_login
|
||||||
|
FROM activity a
|
||||||
|
LEFT JOIN members m ON m.id = a.actor_id
|
||||||
|
ORDER BY a.created_at DESC, a.id DESC
|
||||||
|
LIMIT ? OFFSET ?""",
|
||||||
|
(PER_PAGE + 1, page * PER_PAGE),
|
||||||
|
).fetchall()
|
||||||
|
# One more than a page, asked for so that "is there another page" is known
|
||||||
|
# without a second COUNT(*) over a table that only grows.
|
||||||
|
more = len(rows) > PER_PAGE
|
||||||
|
|
||||||
|
# The sentence is built here rather than in the template: Jinja's `format`
|
||||||
|
# filter is printf-style, so a `{object}` placeholder would have rendered
|
||||||
|
# literally — and an unknown action falling back to its own key is what
|
||||||
|
# makes a log written by an older version still readable.
|
||||||
|
entries = [{
|
||||||
|
"at": row["created_at"],
|
||||||
|
"actor": row["actor"],
|
||||||
|
"sentence": SENTENCES.get(row["action"], row["action"]).format(
|
||||||
|
object=row["object"] or "—"),
|
||||||
|
"detail": row["detail"],
|
||||||
|
} for row in rows[:PER_PAGE]]
|
||||||
|
|
||||||
|
return render_template("activity.html", rows=entries, page=page, more=more)
|
||||||
@ -14,7 +14,7 @@ from flask import Flask, render_template, request
|
|||||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||||
|
|
||||||
from .db import TOMBSTONE_LOGIN, close_db, init_db
|
from .db import TOMBSTONE_LOGIN, close_db, init_db
|
||||||
from .security import check_csrf, csrf_token
|
from .security import check_csrf, csrf_token, is_at_least
|
||||||
|
|
||||||
URL_PREFIX = "/comunidad"
|
URL_PREFIX = "/comunidad"
|
||||||
|
|
||||||
@ -94,11 +94,16 @@ def create_app(overrides: dict | None = None) -> Flask:
|
|||||||
# restart, which is a confusing way to find out the variable is unset.
|
# restart, which is a confusing way to find out the variable is unset.
|
||||||
raise RuntimeError("BOARD_SECRET_KEY is required (generate one with `openssl rand -hex 32`).")
|
raise RuntimeError("BOARD_SECRET_KEY is required (generate one with `openssl rand -hex 32`).")
|
||||||
|
|
||||||
from . import (auth, board, brand, content, events, home, members,
|
from . import (activity, auth, board, brand, content, events, home,
|
||||||
messages, profiles, submissions, uploads)
|
identity, media, members, messages, profiles, status,
|
||||||
|
submissions, uploads)
|
||||||
app.register_blueprint(auth.bp, url_prefix=URL_PREFIX)
|
app.register_blueprint(auth.bp, url_prefix=URL_PREFIX)
|
||||||
app.register_blueprint(home.bp, url_prefix=URL_PREFIX)
|
app.register_blueprint(home.bp, url_prefix=URL_PREFIX)
|
||||||
app.register_blueprint(brand.bp, url_prefix=URL_PREFIX)
|
app.register_blueprint(brand.bp, url_prefix=URL_PREFIX)
|
||||||
|
app.register_blueprint(identity.bp, url_prefix=URL_PREFIX)
|
||||||
|
app.register_blueprint(status.bp, url_prefix=URL_PREFIX)
|
||||||
|
app.register_blueprint(activity.bp, url_prefix=URL_PREFIX)
|
||||||
|
app.register_blueprint(media.bp, url_prefix=URL_PREFIX)
|
||||||
app.register_blueprint(submissions.bp, url_prefix=URL_PREFIX)
|
app.register_blueprint(submissions.bp, url_prefix=URL_PREFIX)
|
||||||
app.register_blueprint(events.bp, url_prefix=URL_PREFIX)
|
app.register_blueprint(events.bp, url_prefix=URL_PREFIX)
|
||||||
app.register_blueprint(members.bp, url_prefix=URL_PREFIX)
|
app.register_blueprint(members.bp, url_prefix=URL_PREFIX)
|
||||||
@ -118,6 +123,15 @@ def create_app(overrides: dict | None = None) -> Flask:
|
|||||||
# For _person.html: the one login with no page behind it. A literal in the
|
# For _person.html: the one login with no page behind it. A literal in the
|
||||||
# template would be the same string written twice, in two languages.
|
# template would be the same string written twice, in two languages.
|
||||||
app.jinja_env.globals["tombstone_login"] = TOMBSTONE_LOGIN
|
app.jinja_env.globals["tombstone_login"] = TOMBSTONE_LOGIN
|
||||||
|
# For member.html's role picker. The template asking the predicate is what
|
||||||
|
# keeps the picker from offering a role the handler will refuse — with two
|
||||||
|
# levels above admin, a hardcoded list can only be right for one of them.
|
||||||
|
app.jinja_env.globals["assignable_roles"] = members.assignable_roles
|
||||||
|
# The same predicate the handlers use. Templates had their own literal
|
||||||
|
# tuples until a tier appeared above them and Gestión quietly disappeared
|
||||||
|
# from the superadministrator's own navigation — the exact failure
|
||||||
|
# `is_at_least` was introduced to end on the Python side.
|
||||||
|
app.jinja_env.globals["is_at_least"] = is_at_least
|
||||||
|
|
||||||
@app.context_processor
|
@app.context_processor
|
||||||
def _year():
|
def _year():
|
||||||
@ -130,6 +144,12 @@ def create_app(overrides: dict | None = None) -> Flask:
|
|||||||
# that would save the query by deferring it.
|
# that would save the query by deferring it.
|
||||||
return {"brand": brand.state()}
|
return {"brand": brand.state()}
|
||||||
|
|
||||||
|
@app.context_processor
|
||||||
|
def _identity():
|
||||||
|
# Only Gestión draws it, so unlike `brand` this one is lazy: a function
|
||||||
|
# the template calls, costing nothing on the pages that never ask.
|
||||||
|
return {"identity": identity.current}
|
||||||
|
|
||||||
@app.context_processor
|
@app.context_processor
|
||||||
def _badges():
|
def _badges():
|
||||||
# Lazily, as functions: base.html is rendered for signed-out pages and
|
# Lazily, as functions: base.html is rendered for signed-out pages and
|
||||||
|
|||||||
@ -21,7 +21,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect,
|
|||||||
from . import auth, uploads
|
from . import auth, uploads
|
||||||
from .db import get_db
|
from .db import get_db
|
||||||
from .render import excerpt, to_html
|
from .render import excerpt, to_html
|
||||||
from .security import admin_required, login_required
|
from .security import admin_required, is_at_least, login_required
|
||||||
|
|
||||||
bp = Blueprint("board", __name__)
|
bp = Blueprint("board", __name__)
|
||||||
|
|
||||||
@ -31,7 +31,7 @@ BODY_MAX = 20_000
|
|||||||
|
|
||||||
|
|
||||||
def is_admin() -> bool:
|
def is_admin() -> bool:
|
||||||
return g.member["role"] in ("owner", "admin")
|
return is_at_least(g.member["role"], "admin")
|
||||||
|
|
||||||
|
|
||||||
def may_delete(row) -> bool:
|
def may_delete(row) -> bool:
|
||||||
|
|||||||
@ -12,6 +12,14 @@ drifts from it. That is what retires the comment: not by merging the two files
|
|||||||
they are served by different things and each has to stand on its own — but by
|
they are served by different things and each has to stand on its own — but by
|
||||||
making a divergence fail the build instead of going unnoticed for a month.
|
making a divergence fail the build instead of going unnoticed for a month.
|
||||||
|
|
||||||
|
### Whose screen this is
|
||||||
|
|
||||||
|
**The superadministrator's, not an admin's.** The look and the identity are the
|
||||||
|
platform's, and an admin is the association's committee — the same line that
|
||||||
|
makes an admin account the superadministrator's to grant. An admin who wants the
|
||||||
|
colours changed asks the person who installed this, which is the correct
|
||||||
|
conversation to be having.
|
||||||
|
|
||||||
### The two destinations
|
### The two destinations
|
||||||
|
|
||||||
One form, saved to two places, because the two halves cannot read the same
|
One form, saved to two places, because the two halves cannot read the same
|
||||||
@ -41,13 +49,14 @@ from __future__ import annotations
|
|||||||
import colorsys
|
import colorsys
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
|
import secrets
|
||||||
|
|
||||||
from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
|
from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
|
||||||
render_template, request, send_from_directory, url_for)
|
render_template, request, send_from_directory, url_for)
|
||||||
|
|
||||||
from . import gitea, uploads
|
from . import activity, gitea, uploads
|
||||||
from .db import get_db
|
from .db import get_db
|
||||||
from .security import admin_required
|
from .security import superadmin_required
|
||||||
|
|
||||||
bp = Blueprint("brand", __name__)
|
bp = Blueprint("brand", __name__)
|
||||||
|
|
||||||
@ -97,6 +106,50 @@ DERIVED = {
|
|||||||
|
|
||||||
HEX = re.compile(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
|
HEX = re.compile(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
|
||||||
|
|
||||||
|
# --- the typeface ----------------------------------------------------------
|
||||||
|
#
|
||||||
|
# Four stacks of fonts that are already on the reader's machine, and nothing
|
||||||
|
# downloaded from anywhere. The site's freedom from Google Fonts is deliberate
|
||||||
|
# and a GDPR matter: a stylesheet that pulls a font from fonts.gstatic.com tells
|
||||||
|
# Google the IP address of everyone who reads this site, which is a disclosure
|
||||||
|
# an association cannot make on its visitors' behalf without asking them.
|
||||||
|
#
|
||||||
|
# A fifth option, `propia`, uses an uploaded .woff2 and falls back to the sans
|
||||||
|
# stack — so a font that fails to load leaves a readable site rather than a
|
||||||
|
# browser default.
|
||||||
|
TYPEFACES = {
|
||||||
|
"sans": ("Sans (la de ahora)",
|
||||||
|
'"Montserrat", -apple-system, BlinkMacSystemFont, "Segoe UI", '
|
||||||
|
'Roboto, "Helvetica Neue", Arial, sans-serif'),
|
||||||
|
"serif": ("Serif",
|
||||||
|
'Georgia, Cambria, "Times New Roman", Times, serif'),
|
||||||
|
"redonda": ("Redondeada",
|
||||||
|
'"Trebuchet MS", "Segoe UI", Verdana, sans-serif'),
|
||||||
|
"sistema": ("La del sistema",
|
||||||
|
'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif'),
|
||||||
|
}
|
||||||
|
DEFAULT_TYPEFACE = "sans"
|
||||||
|
FONT_STACK_FALLBACK = TYPEFACES["sans"][1]
|
||||||
|
|
||||||
|
# A .woff2 and nothing else. It is the web format — every browser in use takes
|
||||||
|
# it, it is the smallest, and it has a four-byte signature this can check
|
||||||
|
# without a parser. A .ttf or .otf would work in a browser and would also be
|
||||||
|
# two to five times the size for the same letters.
|
||||||
|
FONT_SIGNATURE = b"wOF2"
|
||||||
|
FONT_MAX_BYTES = 400_000
|
||||||
|
|
||||||
|
# How round everything is. One setting driving four tokens, because a site whose
|
||||||
|
# cards are round and whose buttons are square looks like two sites.
|
||||||
|
ROUNDNESS = {
|
||||||
|
"suave": ("Suave (la de ahora)", {"radius-xl": "18px", "radius-lg": "12px",
|
||||||
|
"radius-md": "8px", "radius-sm": "5px"}),
|
||||||
|
"recta": ("Recta", {"radius-xl": "0", "radius-lg": "0",
|
||||||
|
"radius-md": "0", "radius-sm": "0"}),
|
||||||
|
"redonda": ("Redonda", {"radius-xl": "28px", "radius-lg": "20px",
|
||||||
|
"radius-md": "14px", "radius-sm": "10px"}),
|
||||||
|
}
|
||||||
|
DEFAULT_ROUNDNESS = "suave"
|
||||||
|
|
||||||
# The free CSS box takes anything but these. `<` and `>` cannot appear in valid
|
# The free CSS box takes anything but these. `<` and `>` cannot appear in valid
|
||||||
# CSS outside a string, and they are the two characters that could end the
|
# CSS outside a string, and they are the two characters that could end the
|
||||||
# stylesheet context in a consumer that mishandles it. Everything else is left
|
# stylesheet context in a consumer that mishandles it. Everything else is left
|
||||||
@ -228,25 +281,43 @@ def current() -> dict:
|
|||||||
stored = {}
|
stored = {}
|
||||||
if not isinstance(stored, dict):
|
if not isinstance(stored, dict):
|
||||||
stored = {}
|
stored = {}
|
||||||
|
def column(name):
|
||||||
|
return (row[name] if row else None) or None
|
||||||
|
|
||||||
|
typeface = column("typeface")
|
||||||
|
if typeface not in TYPEFACES and typeface != "propia":
|
||||||
|
typeface = DEFAULT_TYPEFACE
|
||||||
|
roundness = column("roundness")
|
||||||
|
if roundness not in ROUNDNESS:
|
||||||
|
roundness = DEFAULT_ROUNDNESS
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"stored": stored,
|
"stored": stored,
|
||||||
"tokens": resolve(stored),
|
"tokens": resolve(stored),
|
||||||
"custom_css": (row["custom_css"] if row else "") or "",
|
"custom_css": (row["custom_css"] if row else "") or "",
|
||||||
"logo_name": row["logo_name"] if row else None,
|
"logo_name": column("logo_name"),
|
||||||
"favicon_name": row["favicon_name"] if row else None,
|
"favicon_name": column("favicon_name"),
|
||||||
|
"font_name": column("font_name"),
|
||||||
|
"typeface": typeface,
|
||||||
|
"roundness": roundness,
|
||||||
"updated_at": row["updated_at"] if row else None,
|
"updated_at": row["updated_at"] if row else None,
|
||||||
"published_at": row["published_at"] if row else None,
|
"published_at": row["published_at"] if row else None,
|
||||||
"stamp": _stamp(row["updated_at"] if row else None),
|
"stamp": _stamp(row["updated_at"] if row else None),
|
||||||
"customised": bool(stored or (row and (row["custom_css"] or row["logo_name"]
|
"customised": bool(stored or (row and (row["custom_css"] or row["logo_name"]
|
||||||
or row["favicon_name"]))),
|
or row["favicon_name"]
|
||||||
|
or column("font_name")
|
||||||
|
or typeface != DEFAULT_TYPEFACE
|
||||||
|
or roundness != DEFAULT_ROUNDNESS))),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def _blank() -> dict:
|
def _blank() -> dict:
|
||||||
"""The factory look, as `current()` would describe it."""
|
"""The factory look, as `current()` would describe it."""
|
||||||
return {"stored": {}, "tokens": dict(FACTORY), "custom_css": "",
|
return {"stored": {}, "tokens": dict(FACTORY), "custom_css": "",
|
||||||
"logo_name": None, "favicon_name": None, "updated_at": None,
|
"logo_name": None, "favicon_name": None, "font_name": None,
|
||||||
"published_at": None, "stamp": "0", "customised": False}
|
"typeface": DEFAULT_TYPEFACE, "roundness": DEFAULT_ROUNDNESS,
|
||||||
|
"updated_at": None, "published_at": None, "stamp": "0",
|
||||||
|
"customised": False}
|
||||||
|
|
||||||
|
|
||||||
def state() -> dict:
|
def state() -> dict:
|
||||||
@ -275,20 +346,74 @@ def _stamp(updated_at: str | None) -> str:
|
|||||||
return re.sub(r"\D", "", updated_at or "") or "0"
|
return re.sub(r"\D", "", updated_at or "") or "0"
|
||||||
|
|
||||||
|
|
||||||
def stylesheet(state: dict | None = None) -> str:
|
def font_stack(state: dict) -> str | None:
|
||||||
"""The `:root` overrides and then the custom CSS, in that order.
|
"""The `font-family` the site should use, or None to leave it alone.
|
||||||
|
|
||||||
Only the tokens that differ from the factory are written, so the file reads
|
None rather than the default string when nothing was chosen, so a site that
|
||||||
as what the admin changed, and an install that has changed nothing serves a
|
has not touched this serves no font rule at all and the stylesheets stay
|
||||||
|
byte-identical to what they were.
|
||||||
|
|
||||||
|
An uploaded face is named first and the sans stack follows it: a font that
|
||||||
|
404s or arrives corrupt then leaves a readable site rather than whatever the
|
||||||
|
browser falls back to on its own.
|
||||||
|
"""
|
||||||
|
if state["typeface"] == "propia" and state["font_name"]:
|
||||||
|
return f'"VLPropia", {FONT_STACK_FALLBACK}'
|
||||||
|
if state["typeface"] in TYPEFACES and state["typeface"] != DEFAULT_TYPEFACE:
|
||||||
|
return TYPEFACES[state["typeface"]][1]
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _radius_tokens(state: dict) -> dict:
|
||||||
|
"""The four radius values, or nothing when the roundness is the built-in."""
|
||||||
|
if state["roundness"] == DEFAULT_ROUNDNESS:
|
||||||
|
return {}
|
||||||
|
return ROUNDNESS[state["roundness"]][1]
|
||||||
|
|
||||||
|
|
||||||
|
def font_face(state: dict, url: str) -> str:
|
||||||
|
"""The `@font-face` for an uploaded typeface, at whatever URL serves it.
|
||||||
|
|
||||||
|
`font-display: swap` deliberately: the alternative shows nothing until the
|
||||||
|
file arrives, and a blank article on a slow phone is worse than an article
|
||||||
|
that changes typeface a moment after it appears.
|
||||||
|
"""
|
||||||
|
return ("@font-face {\n"
|
||||||
|
'\tfont-family: "VLPropia";\n'
|
||||||
|
f"\tsrc: url({url}) format('woff2');\n"
|
||||||
|
"\tfont-weight: 100 900;\n"
|
||||||
|
"\tfont-display: swap;\n"
|
||||||
|
"}\n")
|
||||||
|
|
||||||
|
|
||||||
|
def stylesheet(state: dict | None = None) -> str:
|
||||||
|
"""The `@font-face`, the `:root` overrides, then the custom CSS, in that
|
||||||
|
order.
|
||||||
|
|
||||||
|
Only what differs from the factory is written, so the file reads as what the
|
||||||
|
superadministrator changed, and an install that has changed nothing serves a
|
||||||
comment and no rules at all.
|
comment and no rules at all.
|
||||||
"""
|
"""
|
||||||
state = state or current()
|
state = state or current()
|
||||||
|
css = "/* Generado desde Gestión → Marca. No editar a mano. */\n"
|
||||||
|
|
||||||
|
if state["typeface"] == "propia" and state["font_name"]:
|
||||||
|
css += font_face(state, url_for("brand.picture",
|
||||||
|
stored_name=state["font_name"]))
|
||||||
|
|
||||||
lines = [f"\t--{name}: {value};"
|
lines = [f"\t--{name}: {value};"
|
||||||
for name, value in state["tokens"].items()
|
for name, value in state["tokens"].items()
|
||||||
if value != FACTORY[name]]
|
if value != FACTORY[name]]
|
||||||
css = "/* Generado desde Gestión → Marca. No editar a mano. */\n"
|
lines += [f"\t--{name}: {value};" for name, value in _radius_tokens(state).items()]
|
||||||
if lines:
|
if lines:
|
||||||
css += ":root {\n" + "\n".join(lines) + "\n}\n"
|
css += ":root {\n" + "\n".join(lines) + "\n}\n"
|
||||||
|
|
||||||
|
stack = font_stack(state)
|
||||||
|
if stack:
|
||||||
|
# On `body` rather than `:root`, because the rule it is overriding is on
|
||||||
|
# `body` and a custom property would need every rule to opt in.
|
||||||
|
css += f"body {{ font-family: {stack}; }}\n"
|
||||||
|
|
||||||
if state["custom_css"]:
|
if state["custom_css"]:
|
||||||
# Last, so it wins over everything above it. That is the whole contract
|
# Last, so it wins over everything above it. That is the whole contract
|
||||||
# of the advanced box.
|
# of the advanced box.
|
||||||
@ -361,16 +486,63 @@ def _read_picture(field: str, allowed: tuple[str, ...], errors: list[str]):
|
|||||||
return item
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
def _read_font(errors: list[str]):
|
||||||
|
"""The uploaded typeface, sniffed rather than trusted.
|
||||||
|
|
||||||
|
Not through `uploads.stage`, which knows about pictures: this needs its own
|
||||||
|
four-byte check and its own size limit. Same shape though, and the same
|
||||||
|
rule — the name on the file decides nothing.
|
||||||
|
|
||||||
|
A stored name that ends `.woff2` would not match `uploads.STORED_NAME`,
|
||||||
|
which allows three or four letters; `.wof` would be a lie. So the file is
|
||||||
|
stored as `.bin` and served with an explicit Content-Type, which is what the
|
||||||
|
browser reads anyway.
|
||||||
|
"""
|
||||||
|
upload = request.files.get("font")
|
||||||
|
if not upload or not upload.filename:
|
||||||
|
return None
|
||||||
|
data = upload.read()
|
||||||
|
if not data:
|
||||||
|
return None
|
||||||
|
if len(data) > FONT_MAX_BYTES:
|
||||||
|
errors.append(
|
||||||
|
f"La tipografía pesa {len(data) // 1024}KB y el máximo son "
|
||||||
|
f"{FONT_MAX_BYTES // 1024}KB. Subconjunta la fuente a latín y "
|
||||||
|
"latín extendido antes de subirla."
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
if not data.startswith(FONT_SIGNATURE):
|
||||||
|
errors.append(
|
||||||
|
f"«{upload.filename[:60]}» no es un .woff2. Es el único formato que "
|
||||||
|
"se acepta: es el de la web, lo entienden todos los navegadores y "
|
||||||
|
"es el más pequeño."
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
return {
|
||||||
|
"data": data,
|
||||||
|
"original_name": upload.filename[:200],
|
||||||
|
"stored_name": f"tipografia-{secrets.token_hex(6)}.bin",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _read_choice(form, field: str, table: dict, default: str,
|
||||||
|
extra: tuple[str, ...] = ()) -> str:
|
||||||
|
"""One key from a table of our own, or the default. Never the raw value."""
|
||||||
|
choice = (form.get(field) or "").strip()
|
||||||
|
return choice if choice in table or choice in extra else default
|
||||||
|
|
||||||
|
|
||||||
# --- routes ----------------------------------------------------------------
|
# --- routes ----------------------------------------------------------------
|
||||||
|
|
||||||
@bp.route("/gestion/marca", methods=["GET", "POST"])
|
@bp.route("/gestion/marca", methods=["GET", "POST"])
|
||||||
@admin_required
|
@superadmin_required
|
||||||
def edit():
|
def edit():
|
||||||
if request.method == "GET":
|
if request.method == "GET":
|
||||||
state = current()
|
state = current()
|
||||||
return render_template("brand_form.html", state=state,
|
return render_template("brand_form.html", state=state,
|
||||||
factory=FACTORY, simple=SIMPLE,
|
factory=FACTORY, simple=SIMPLE,
|
||||||
derived=sorted(DERIVED), advanced=_advanced(),
|
derived=sorted(DERIVED), advanced=_advanced(),
|
||||||
|
typefaces=TYPEFACES, roundness=ROUNDNESS,
|
||||||
notes=warnings(state["tokens"]))
|
notes=warnings(state["tokens"]))
|
||||||
|
|
||||||
errors: list[str] = []
|
errors: list[str] = []
|
||||||
@ -378,18 +550,31 @@ def edit():
|
|||||||
css = _read_css(request.form, errors)
|
css = _read_css(request.form, errors)
|
||||||
logo = _read_picture("logo", LOGO_EXTENSIONS, errors)
|
logo = _read_picture("logo", LOGO_EXTENSIONS, errors)
|
||||||
favicon = _read_picture("favicon", FAVICON_EXTENSIONS, errors)
|
favicon = _read_picture("favicon", FAVICON_EXTENSIONS, errors)
|
||||||
|
font = _read_font(errors)
|
||||||
|
typeface = _read_choice(request.form, "typeface", TYPEFACES,
|
||||||
|
DEFAULT_TYPEFACE, extra=("propia",))
|
||||||
|
roundness = _read_choice(request.form, "roundness", ROUNDNESS, DEFAULT_ROUNDNESS)
|
||||||
if errors:
|
if errors:
|
||||||
for message in errors:
|
for message in errors:
|
||||||
flash(message, "error")
|
flash(message, "error")
|
||||||
return redirect(url_for("brand.edit"))
|
return redirect(url_for("brand.edit"))
|
||||||
|
|
||||||
state = current()
|
state = current()
|
||||||
|
if typeface == "propia" and not (font or state["font_name"]):
|
||||||
|
# Chosen without ever uploading one. Refused rather than silently
|
||||||
|
# falling back, because the site would look unchanged and the setting
|
||||||
|
# would say otherwise.
|
||||||
|
flash("Para usar una tipografía propia hay que subir un archivo .woff2.",
|
||||||
|
"error")
|
||||||
|
return redirect(url_for("brand.edit"))
|
||||||
|
|
||||||
# Written before the commits: the members area must not depend on the git
|
# Written before the commits: the members area must not depend on the git
|
||||||
# server being up to change its own colours.
|
# server being up to change its own colours.
|
||||||
_store(stored, css, logo, favicon, state)
|
_store(stored, css, logo, favicon, font, typeface, roundness, state)
|
||||||
for note in warnings(resolve(stored)):
|
for note in warnings(resolve(stored)):
|
||||||
flash(note, "error")
|
flash(note, "error")
|
||||||
|
|
||||||
|
activity.log("brand.saved")
|
||||||
if _publish():
|
if _publish():
|
||||||
flash("Guardado. El sitio público se reconstruye en un par de minutos.", "ok")
|
flash("Guardado. El sitio público se reconstruye en un par de minutos.", "ok")
|
||||||
return redirect(url_for("brand.edit"))
|
return redirect(url_for("brand.edit"))
|
||||||
@ -401,15 +586,19 @@ def _advanced() -> tuple:
|
|||||||
return tuple(name for name in FACTORY if name not in simple)
|
return tuple(name for name in FACTORY if name not in simple)
|
||||||
|
|
||||||
|
|
||||||
def _store(stored: dict, css: str, logo, favicon, state: dict) -> None:
|
def _store(stored: dict, css: str, logo, favicon, font, typeface: str,
|
||||||
"""The row, and the two pictures on disk.
|
roundness: str, state: dict) -> None:
|
||||||
|
"""The row, and the three uploaded files on disk.
|
||||||
|
|
||||||
Files before the row, as `uploads.save` does it and for the same reason: a
|
Files before the row, as `uploads.save` does it and for the same reason: a
|
||||||
row naming a file that is not there renders as a broken image on every
|
row naming a file that is not there renders as a broken image on every
|
||||||
future visit, while a file with no row is invisible.
|
future visit, while a file with no row is invisible.
|
||||||
"""
|
"""
|
||||||
names = {"logo_name": state["logo_name"], "favicon_name": state["favicon_name"]}
|
names = {"logo_name": state["logo_name"],
|
||||||
for field, item in (("logo_name", logo), ("favicon_name", favicon)):
|
"favicon_name": state["favicon_name"],
|
||||||
|
"font_name": state["font_name"]}
|
||||||
|
uploaded = (("logo_name", logo), ("favicon_name", favicon), ("font_name", font))
|
||||||
|
for field, item in uploaded:
|
||||||
if item is None:
|
if item is None:
|
||||||
continue
|
continue
|
||||||
uploads.directory().joinpath(item["stored_name"]).write_bytes(item["data"])
|
uploads.directory().joinpath(item["stored_name"]).write_bytes(item["data"])
|
||||||
@ -417,29 +606,34 @@ def _store(stored: dict, css: str, logo, favicon, state: dict) -> None:
|
|||||||
|
|
||||||
get_db().execute(
|
get_db().execute(
|
||||||
"""INSERT INTO brand (id, tokens_json, custom_css, logo_name, favicon_name,
|
"""INSERT INTO brand (id, tokens_json, custom_css, logo_name, favicon_name,
|
||||||
|
font_name, typeface, roundness,
|
||||||
updated_by, updated_at, published_at)
|
updated_by, updated_at, published_at)
|
||||||
VALUES (1, ?, ?, ?, ?, ?, datetime('now'), NULL)
|
VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), NULL)
|
||||||
ON CONFLICT(id) DO UPDATE SET
|
ON CONFLICT(id) DO UPDATE SET
|
||||||
tokens_json = excluded.tokens_json,
|
tokens_json = excluded.tokens_json,
|
||||||
custom_css = excluded.custom_css,
|
custom_css = excluded.custom_css,
|
||||||
logo_name = excluded.logo_name,
|
logo_name = excluded.logo_name,
|
||||||
favicon_name = excluded.favicon_name,
|
favicon_name = excluded.favicon_name,
|
||||||
|
font_name = excluded.font_name,
|
||||||
|
typeface = excluded.typeface,
|
||||||
|
roundness = excluded.roundness,
|
||||||
updated_by = excluded.updated_by,
|
updated_by = excluded.updated_by,
|
||||||
updated_at = excluded.updated_at,
|
updated_at = excluded.updated_at,
|
||||||
published_at = NULL""",
|
published_at = NULL""",
|
||||||
(json.dumps(stored, sort_keys=True), css,
|
(json.dumps(stored, sort_keys=True), css,
|
||||||
names["logo_name"], names["favicon_name"], g.member["id"]),
|
names["logo_name"], names["favicon_name"], names["font_name"],
|
||||||
|
typeface, roundness, g.member["id"]),
|
||||||
)
|
)
|
||||||
|
|
||||||
# The old pictures, once nothing points at them. After the row, so a
|
# The old files, once nothing points at them. After the row, so a rollback
|
||||||
# rollback cannot leave the row naming a file that has been deleted.
|
# cannot leave the row naming a file that has been deleted.
|
||||||
for field, item in (("logo_name", logo), ("favicon_name", favicon)):
|
for field, item in uploaded:
|
||||||
if item is not None and state[field] and state[field] != names[field]:
|
if item is not None and state[field] and state[field] != names[field]:
|
||||||
uploads.remove(state[field])
|
uploads.remove(state[field])
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/gestion/marca/publicar", methods=["POST"])
|
@bp.route("/gestion/marca/publicar", methods=["POST"])
|
||||||
@admin_required
|
@superadmin_required
|
||||||
def publish():
|
def publish():
|
||||||
"""Try the commits again after the git server was unreachable."""
|
"""Try the commits again after the git server was unreachable."""
|
||||||
if _publish():
|
if _publish():
|
||||||
@ -448,7 +642,7 @@ def publish():
|
|||||||
|
|
||||||
|
|
||||||
@bp.route("/gestion/marca/restaurar", methods=["POST"])
|
@bp.route("/gestion/marca/restaurar", methods=["POST"])
|
||||||
@admin_required
|
@superadmin_required
|
||||||
def restore():
|
def restore():
|
||||||
"""Back to the colours the site was built with.
|
"""Back to the colours the site was built with.
|
||||||
|
|
||||||
@ -457,9 +651,10 @@ def restore():
|
|||||||
"""
|
"""
|
||||||
state = current()
|
state = current()
|
||||||
get_db().execute("DELETE FROM brand WHERE id = 1")
|
get_db().execute("DELETE FROM brand WHERE id = 1")
|
||||||
for name in (state["logo_name"], state["favicon_name"]):
|
for name in (state["logo_name"], state["favicon_name"], state["font_name"]):
|
||||||
if name:
|
if name:
|
||||||
uploads.remove(name)
|
uploads.remove(name)
|
||||||
|
activity.log("brand.restored")
|
||||||
flash("Restaurado lo de fábrica.", "ok")
|
flash("Restaurado lo de fábrica.", "ok")
|
||||||
_publish()
|
_publish()
|
||||||
return redirect(url_for("brand.edit"))
|
return redirect(url_for("brand.edit"))
|
||||||
@ -490,8 +685,16 @@ def picture(stored_name: str):
|
|||||||
if not uploads.STORED_NAME.match(stored_name):
|
if not uploads.STORED_NAME.match(stored_name):
|
||||||
abort(404)
|
abort(404)
|
||||||
state = current()
|
state = current()
|
||||||
if stored_name not in (state["logo_name"], state["favicon_name"]):
|
if stored_name not in (state["logo_name"], state["favicon_name"],
|
||||||
|
state["font_name"]):
|
||||||
abort(404)
|
abort(404)
|
||||||
|
# The typeface is stored `.bin` — `.woff2` is five characters and
|
||||||
|
# `STORED_NAME` allows three or four — so its type is stated here rather
|
||||||
|
# than guessed from the name. A font served as application/octet-stream
|
||||||
|
# loads anyway, but says nothing true in a network panel.
|
||||||
|
if stored_name == state["font_name"]:
|
||||||
|
return send_from_directory(uploads.directory(), stored_name,
|
||||||
|
mimetype="font/woff2")
|
||||||
return send_from_directory(uploads.directory(), stored_name)
|
return send_from_directory(uploads.directory(), stored_name)
|
||||||
|
|
||||||
|
|
||||||
@ -504,10 +707,15 @@ def _repo_path(stored_name: str, kind: str) -> str:
|
|||||||
file instead of leaving every previous one in the repository, deployed and
|
file instead of leaving every previous one in the repository, deployed and
|
||||||
unreferenced.
|
unreferenced.
|
||||||
"""
|
"""
|
||||||
return f"{REPO_FOLDER}/{kind}.{stored_name.rsplit('.', 1)[-1]}"
|
# The typeface is stored locally as `.bin` — see `_read_font` — but the
|
||||||
|
# repository is a web root, where the extension is what a reader's cache and
|
||||||
|
# a CDN go by. It lands as `.woff2`, which is what it is.
|
||||||
|
extension = "woff2" if kind == "font" else stored_name.rsplit(".", 1)[-1]
|
||||||
|
return f"{REPO_FOLDER}/{kind}.{extension}"
|
||||||
|
|
||||||
|
|
||||||
def _yaml(state: dict, logo: str | None, favicon: str | None) -> str:
|
def _yaml(state: dict, logo: str | None, favicon: str | None,
|
||||||
|
font: str | None = None) -> str:
|
||||||
"""`data/brand.yaml`, written rather than dumped.
|
"""`data/brand.yaml`, written rather than dumped.
|
||||||
|
|
||||||
By hand because the values are known: colours matched against a hex
|
By hand because the values are known: colours matched against a hex
|
||||||
@ -523,6 +731,14 @@ def _yaml(state: dict, logo: str | None, favicon: str | None) -> str:
|
|||||||
for name, value in state["tokens"].items():
|
for name, value in state["tokens"].items():
|
||||||
if value != FACTORY[name]:
|
if value != FACTORY[name]:
|
||||||
lines.append(f" {name}: \"{value}\"")
|
lines.append(f" {name}: \"{value}\"")
|
||||||
|
for name, value in _radius_tokens(state).items():
|
||||||
|
lines.append(f" {name}: \"{value}\"")
|
||||||
|
stack = font_stack(state)
|
||||||
|
if stack:
|
||||||
|
# Single-quoted because every stack has double quotes inside it.
|
||||||
|
lines.append(f"font_stack: '{stack}'")
|
||||||
|
if font:
|
||||||
|
lines.append(f"font: \"/{font.removeprefix('static/')}\"")
|
||||||
if logo:
|
if logo:
|
||||||
lines.append(f"logo: \"/{logo.removeprefix('static/')}\"")
|
lines.append(f"logo: \"/{logo.removeprefix('static/')}\"")
|
||||||
if favicon:
|
if favicon:
|
||||||
@ -553,21 +769,21 @@ def _publish() -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logo_path = favicon_path = None
|
paths = {}
|
||||||
for kind, name in (("logo", state["logo_name"]),
|
for kind, name in (("logo", state["logo_name"]),
|
||||||
("favicon", state["favicon_name"])):
|
("favicon", state["favicon_name"]),
|
||||||
|
("font", state["font_name"])):
|
||||||
if not name:
|
if not name:
|
||||||
continue
|
continue
|
||||||
path = _repo_path(name, kind)
|
path = _repo_path(name, kind)
|
||||||
data = uploads.directory().joinpath(name).read_bytes()
|
data = uploads.directory().joinpath(name).read_bytes()
|
||||||
_write(path, data, f"marca: {kind}", token)
|
_write(path, data, f"marca: {kind}", token)
|
||||||
_tidy(kind, path, token)
|
_tidy(kind, path, token)
|
||||||
if kind == "logo":
|
paths[kind] = path
|
||||||
logo_path = path
|
|
||||||
else:
|
|
||||||
favicon_path = path
|
|
||||||
|
|
||||||
_write(DATA_FILE, _yaml(state, logo_path, favicon_path).encode("utf-8"),
|
_write(DATA_FILE,
|
||||||
|
_yaml(state, paths.get("logo"), paths.get("favicon"),
|
||||||
|
paths.get("font")).encode("utf-8"),
|
||||||
"marca: colores", token)
|
"marca: colores", token)
|
||||||
except (gitea.GiteaError, OSError) as exc:
|
except (gitea.GiteaError, OSError) as exc:
|
||||||
current_app.logger.warning("brand publish failed: %s", exc)
|
current_app.logger.warning("brand publish failed: %s", exc)
|
||||||
|
|||||||
@ -33,7 +33,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect,
|
|||||||
from . import gitea
|
from . import gitea
|
||||||
from .db import get_db
|
from .db import get_db
|
||||||
from .render import to_html
|
from .render import to_html
|
||||||
from .security import moderator_required
|
from .security import is_at_least, moderator_required
|
||||||
# One list of accepted formats for the whole app, kept in the module that
|
# 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
|
# knows what each one looks like on the wire, so the editor and the board
|
||||||
# cannot drift apart about what a picture is.
|
# cannot drift apart about what a picture is.
|
||||||
@ -172,17 +172,22 @@ def _cache_read(path: str, sha: str):
|
|||||||
|
|
||||||
def _cache_write(path: str, sha: str, fm: dict) -> None:
|
def _cache_write(path: str, sha: str, fm: dict) -> None:
|
||||||
get_db().execute(
|
get_db().execute(
|
||||||
"""INSERT INTO content_cache (path, sha, title, date, generated,
|
"""INSERT INTO content_cache (path, sha, title, date, generated, image,
|
||||||
event_date, event_time, event_location)
|
event_date, event_time, event_location)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
ON CONFLICT(path) DO UPDATE SET
|
ON CONFLICT(path) DO UPDATE SET
|
||||||
sha = excluded.sha, title = excluded.title, date = excluded.date,
|
sha = excluded.sha, title = excluded.title, date = excluded.date,
|
||||||
generated = excluded.generated,
|
generated = excluded.generated, image = excluded.image,
|
||||||
event_date = excluded.event_date, event_time = excluded.event_time,
|
event_date = excluded.event_date, event_time = excluded.event_time,
|
||||||
event_location = excluded.event_location,
|
event_location = excluded.event_location,
|
||||||
updated_at = datetime('now')""",
|
updated_at = datetime('now')""",
|
||||||
(path, sha, str(fm.get("title", "")), str(fm.get("date", "")),
|
(path, sha, str(fm.get("title", "")), str(fm.get("date", "")),
|
||||||
1 if fm.get("translated_from") else 0,
|
1 if fm.get("translated_from") else 0,
|
||||||
|
# Which picture this post carries, for the media library: without it,
|
||||||
|
# answering "does anything use this image?" means re-reading every
|
||||||
|
# post's frontmatter from the git server on every page view — the exact
|
||||||
|
# cost this cache exists to avoid.
|
||||||
|
str(fm.get("image", "") or ""),
|
||||||
# Cached for the private calendar, which shows public events beside the
|
# Cached for the private calendar, which shows public events beside the
|
||||||
# internal ones and would otherwise read every post's frontmatter on
|
# internal ones and would otherwise read every post's frontmatter on
|
||||||
# every page view to find out when they are.
|
# every page view to find out when they are.
|
||||||
@ -233,7 +238,7 @@ def _collection_or_404(collection: str) -> dict:
|
|||||||
if collection not in COLLECTIONS:
|
if collection not in COLLECTIONS:
|
||||||
abort(404)
|
abort(404)
|
||||||
meta = COLLECTIONS[collection]
|
meta = COLLECTIONS[collection]
|
||||||
if meta["role"] == "admin" and g.member["role"] not in ("owner", "admin"):
|
if meta["role"] == "admin" and not is_at_least(g.member["role"], "admin"):
|
||||||
abort(403)
|
abort(403)
|
||||||
return meta
|
return meta
|
||||||
|
|
||||||
@ -242,7 +247,7 @@ def visible_collections() -> dict:
|
|||||||
"""The collections this member may write to, for the tabs. A tab that only
|
"""The collections this member may write to, for the tabs. A tab that only
|
||||||
ever produces a 403 is worse than no tab."""
|
ever produces a 403 is worse than no tab."""
|
||||||
return {name: meta for name, meta in COLLECTIONS.items()
|
return {name: meta for name, meta in COLLECTIONS.items()
|
||||||
if meta["role"] != "admin" or g.member["role"] in ("owner", "admin")}
|
if meta["role"] != "admin" or is_at_least(g.member["role"], "admin")}
|
||||||
|
|
||||||
|
|
||||||
def _name_or_404(name: str) -> str:
|
def _name_or_404(name: str) -> str:
|
||||||
|
|||||||
@ -65,7 +65,7 @@ def init_db(app) -> None:
|
|||||||
for step in migrations.apply(db):
|
for step in migrations.apply(db):
|
||||||
app.logger.info("Applied migration %s", step)
|
app.logger.info("Applied migration %s", step)
|
||||||
_ensure_tombstone(db)
|
_ensure_tombstone(db)
|
||||||
_seed_owner(db, app)
|
_seed_superadmin(db, app)
|
||||||
finally:
|
finally:
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
@ -79,35 +79,49 @@ def _ensure_tombstone(db: sqlite3.Connection) -> None:
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _seed_owner(db: sqlite3.Connection, app) -> None:
|
def _seed_superadmin(db: sqlite3.Connection, app) -> None:
|
||||||
"""Create the first owner from BOARD_OWNER, once.
|
"""Create the first superadministrator from BOARD_OWNER, once.
|
||||||
|
|
||||||
Deliberately refuses to change an existing owner. Were this to overwrite,
|
Still `BOARD_OWNER` rather than a new name: it is the variable the server's
|
||||||
anyone who could edit the environment could hand themselves ownership by
|
`.env` already carries, and an install that has to edit its environment to
|
||||||
restarting the container — which is a quieter privilege escalation than it
|
survive an upgrade is an install that breaks on upgrade.
|
||||||
looks, since editing a compose file draws far less attention than asking
|
|
||||||
the owner for access.
|
Deliberately refuses to change an existing superadministrator. Were this to
|
||||||
|
overwrite, anyone who could edit the environment could hand themselves the
|
||||||
|
platform by restarting the container — a quieter privilege escalation than
|
||||||
|
it looks, since editing a compose file draws far less attention than asking
|
||||||
|
for access.
|
||||||
|
|
||||||
|
**The `ON CONFLICT` below is the half worth reading twice.** It used to end
|
||||||
|
`SET role = 'owner'`, which was right while owner was the top of the tree.
|
||||||
|
Left that way after migration 7 it would have found the superadministrator's
|
||||||
|
login, matched the conflict, and demoted them back to owner on every
|
||||||
|
container restart — a privilege *reduction* arriving at the least convenient
|
||||||
|
moment and attributable to nothing anybody did. `members_one_superadmin`
|
||||||
|
would then have let somebody else take the chair.
|
||||||
"""
|
"""
|
||||||
login = (app.config.get("OWNER_LOGIN") or "").strip()
|
login = (app.config.get("OWNER_LOGIN") or "").strip()
|
||||||
existing = db.execute("SELECT gitea_login FROM members WHERE role = 'owner'").fetchone()
|
existing = db.execute(
|
||||||
|
"SELECT gitea_login FROM members WHERE role = 'superadmin'").fetchone()
|
||||||
|
|
||||||
if existing:
|
if existing:
|
||||||
if login and existing["gitea_login"].lower() != login.lower():
|
if login and existing["gitea_login"].lower() != login.lower():
|
||||||
app.logger.warning(
|
app.logger.warning(
|
||||||
"BOARD_OWNER is %r but the owner is %r; leaving it alone. "
|
"BOARD_OWNER is %r but the superadministrator is %r; leaving it "
|
||||||
"Transfer ownership from inside the app instead.",
|
"alone. Hand the platform on from inside the app instead.",
|
||||||
login, existing["gitea_login"],
|
login, existing["gitea_login"],
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
if not login:
|
if not login:
|
||||||
app.logger.warning("No owner yet and BOARD_OWNER is unset — nobody can sign in.")
|
app.logger.warning("No superadministrator yet and BOARD_OWNER is unset — "
|
||||||
|
"nobody can sign in.")
|
||||||
return
|
return
|
||||||
|
|
||||||
db.execute(
|
db.execute(
|
||||||
"""INSERT INTO members (gitea_login, display_name, role, active)
|
"""INSERT INTO members (gitea_login, display_name, role, active)
|
||||||
VALUES (?, ?, 'owner', 1)
|
VALUES (?, ?, 'superadmin', 1)
|
||||||
ON CONFLICT(gitea_login) DO UPDATE SET role = 'owner', active = 1""",
|
ON CONFLICT(gitea_login) DO UPDATE SET role = 'superadmin', active = 1""",
|
||||||
(login, login),
|
(login, login),
|
||||||
)
|
)
|
||||||
app.logger.info("Seeded %r as owner.", login)
|
app.logger.info("Seeded %r as superadministrator.", login)
|
||||||
|
|||||||
@ -32,7 +32,7 @@ from flask import (Blueprint, Response, abort, flash, g, redirect,
|
|||||||
from . import content, gitea, uploads
|
from . import content, gitea, uploads
|
||||||
from .db import get_db
|
from .db import get_db
|
||||||
from .render import to_html
|
from .render import to_html
|
||||||
from .security import admin_required, login_required
|
from .security import admin_required, is_at_least, login_required
|
||||||
|
|
||||||
bp = Blueprint("events", __name__)
|
bp = Blueprint("events", __name__)
|
||||||
|
|
||||||
@ -129,7 +129,7 @@ def month():
|
|||||||
this_month=f"{today.year:04d}-{today.month:02d}",
|
this_month=f"{today.year:04d}-{today.month:02d}",
|
||||||
today=today.day if (today.year, today.month) == (year, number) else 0,
|
today=today.day if (today.year, today.month) == (year, number) else 0,
|
||||||
public_missing=public_missing,
|
public_missing=public_missing,
|
||||||
may_edit=g.member["role"] in ("owner", "admin"),
|
may_edit=is_at_least(g.member["role"], "admin"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@ -140,7 +140,7 @@ def show(event_id: int):
|
|||||||
return render_template("event.html", event=row,
|
return render_template("event.html", event=row,
|
||||||
body_html=to_html(row["body_md"] or ""),
|
body_html=to_html(row["body_md"] or ""),
|
||||||
when=_spoken_date(row["starts_on"]),
|
when=_spoken_date(row["starts_on"]),
|
||||||
may_edit=g.member["role"] in ("owner", "admin"))
|
may_edit=is_at_least(g.member["role"], "admin"))
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/calendario/<int:event_id>.ics")
|
@bp.route("/calendario/<int:event_id>.ics")
|
||||||
|
|||||||
@ -18,7 +18,7 @@ from flask import Blueprint, g, jsonify, render_template, request, url_for
|
|||||||
from . import submissions
|
from . import submissions
|
||||||
from .db import TOMBSTONE_LOGIN, get_db
|
from .db import TOMBSTONE_LOGIN, get_db
|
||||||
from .render import excerpt, to_html
|
from .render import excerpt, to_html
|
||||||
from .security import admin_required, csrf_token, login_required
|
from .security import admin_required, csrf_token, is_at_least, login_required
|
||||||
|
|
||||||
bp = Blueprint("home", __name__)
|
bp = Blueprint("home", __name__)
|
||||||
|
|
||||||
@ -126,7 +126,7 @@ def session_state():
|
|||||||
{"label": "Publicaciones", "url": url_for("submissions.index")},
|
{"label": "Publicaciones", "url": url_for("submissions.index")},
|
||||||
{"label": "Calendario", "url": url_for("events.month")},
|
{"label": "Calendario", "url": url_for("events.month")},
|
||||||
]
|
]
|
||||||
if g.member["role"] in ("owner", "admin"):
|
if is_at_least(g.member["role"], "admin"):
|
||||||
sections.append({"label": "Gestión", "url": url_for("home.gestion")})
|
sections.append({"label": "Gestión", "url": url_for("home.gestion")})
|
||||||
|
|
||||||
return _no_store(jsonify({
|
return _no_store(jsonify({
|
||||||
@ -181,7 +181,8 @@ def gestion():
|
|||||||
"SELECT COUNT(*) AS n FROM members WHERE active = 0 AND role != 'tombstone'"
|
"SELECT COUNT(*) AS n FROM members WHERE active = 0 AND role != 'tombstone'"
|
||||||
).fetchone()["n"],
|
).fetchone()["n"],
|
||||||
"moderators": db.execute(
|
"moderators": db.execute(
|
||||||
"SELECT COUNT(*) AS n FROM members WHERE role IN ('owner', 'admin', 'moderator')"
|
"SELECT COUNT(*) AS n FROM members WHERE role IN "
|
||||||
|
"('superadmin', 'owner', 'admin', 'moderator')"
|
||||||
).fetchone()["n"],
|
).fetchone()["n"],
|
||||||
"pending": db.execute(
|
"pending": db.execute(
|
||||||
"SELECT COUNT(*) AS n FROM submissions WHERE state = 'pending'").fetchone()["n"],
|
"SELECT COUNT(*) AS n FROM submissions WHERE state = 'pending'").fetchone()["n"],
|
||||||
|
|||||||
305
apps/board/identity.py
Normal file
305
apps/board/identity.py
Normal file
@ -0,0 +1,305 @@
|
|||||||
|
"""What the site is called, what it says it is, and where to find it.
|
||||||
|
|
||||||
|
Separate from `brand.py`, which is how the site *looks*, because the two have
|
||||||
|
different audiences and different failure modes: a wrong colour is ugly and a
|
||||||
|
wrong contact address is a message nobody receives. They are also published to
|
||||||
|
different files, so an organisation can change its tagline without touching its
|
||||||
|
palette.
|
||||||
|
|
||||||
|
Everything here used to live in `config.yaml`, which means it could only be
|
||||||
|
changed by somebody with the repository — the one thing this phase exists to
|
||||||
|
end. The same arrangement `brand.py` uses carries it: SQLite first for the
|
||||||
|
members area, then a commit of `data/site.yaml` for the public site, in that
|
||||||
|
order so a git outage never blocks a change that does not need git.
|
||||||
|
|
||||||
|
**Hugo cannot have `config.yaml` overridden by a data file**, so the name and
|
||||||
|
the tagline are read through `partials/site-name.html` and
|
||||||
|
`partials/site-tagline.html`, which prefer `site.Data.site` and fall back to the
|
||||||
|
config. Every template that shows either calls one of them, so the two cannot
|
||||||
|
drift — and a site with no `data/site.yaml` renders exactly what it rendered
|
||||||
|
before any of this existed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
|
||||||
|
from flask import (Blueprint, current_app, flash, g, redirect,
|
||||||
|
render_template, request, url_for)
|
||||||
|
|
||||||
|
from . import activity, gitea
|
||||||
|
from .db import get_db
|
||||||
|
from .security import superadmin_required
|
||||||
|
|
||||||
|
bp = Blueprint("identity", __name__)
|
||||||
|
|
||||||
|
DATA_FILE = "data/site.yaml"
|
||||||
|
|
||||||
|
# The languages the site is built in, with the config.yaml values they fall back
|
||||||
|
# to. Written here rather than read from config.yaml because the members area
|
||||||
|
# does not parse the site's configuration — and because a fallback that silently
|
||||||
|
# follows a file somebody edits is a fallback nobody can predict.
|
||||||
|
LANGUAGES = (
|
||||||
|
("es", "Español", "Viena Latina",
|
||||||
|
"Comunidad latinoamericana en Viena — turismo, cultura, gastronomía, "
|
||||||
|
"comunidad y comercio."),
|
||||||
|
("de", "Deutsch", "Viena Latina",
|
||||||
|
"Lateinamerikanische Community in Wien — Tourismus, Kultur, Gastronomie, "
|
||||||
|
"Gemeinschaft und Handel."),
|
||||||
|
("pt-br", "Português (Brasil)", "Viena Latina",
|
||||||
|
"Comunidade latino-americana em Viena — turismo, cultura, gastronomia, "
|
||||||
|
"comunidade e comércio."),
|
||||||
|
)
|
||||||
|
|
||||||
|
# The networks offered, in the order they are drawn. A fixed list rather than a
|
||||||
|
# free "add a link" box: these become `sameAs` in the Organization schema, which
|
||||||
|
# is a claim that an account and this site are the same body — and a list of
|
||||||
|
# arbitrary URLs is not that claim, it is a bookmark bar.
|
||||||
|
NETWORKS = (
|
||||||
|
("instagram", "Instagram", "https://instagram.com/…"),
|
||||||
|
("facebook", "Facebook", "https://facebook.com/…"),
|
||||||
|
("whatsapp", "WhatsApp", "https://chat.whatsapp.com/…"),
|
||||||
|
("youtube", "YouTube", "https://youtube.com/@…"),
|
||||||
|
("mastodon", "Mastodon", "https://mastodon.social/@…"),
|
||||||
|
("bluesky", "Bluesky", "https://bsky.app/profile/…"),
|
||||||
|
)
|
||||||
|
|
||||||
|
NAME_MAX = 80
|
||||||
|
TAGLINE_MAX = 300
|
||||||
|
FOOTER_MAX = 200
|
||||||
|
|
||||||
|
# Same rule as a profile link, and for the same reason: `javascript:` in an href
|
||||||
|
# is a script running on vienalatina.com, and these are rendered in the footer of
|
||||||
|
# every page.
|
||||||
|
URL_RE = re.compile(r"^https?://[^\s<>\"']{3,300}$")
|
||||||
|
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s.]+\.[^@\s]{2,}$")
|
||||||
|
|
||||||
|
|
||||||
|
def _row():
|
||||||
|
return get_db().execute("SELECT * FROM site WHERE id = 1").fetchone()
|
||||||
|
|
||||||
|
|
||||||
|
def _loads(raw) -> dict:
|
||||||
|
try:
|
||||||
|
value = json.loads(raw or "{}")
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return {}
|
||||||
|
return value if isinstance(value, dict) else {}
|
||||||
|
|
||||||
|
|
||||||
|
def current() -> dict:
|
||||||
|
"""Everything the form and both halves of the site read.
|
||||||
|
|
||||||
|
Works with no row at all, which is every install until somebody opens the
|
||||||
|
screen — so the defaults here are the values `config.yaml` has today.
|
||||||
|
"""
|
||||||
|
row = _row()
|
||||||
|
names = _loads(row["names_json"] if row else None)
|
||||||
|
social = _loads(row["social_json"] if row else None)
|
||||||
|
|
||||||
|
languages = {}
|
||||||
|
for code, _label, name, tagline in LANGUAGES:
|
||||||
|
given = names.get(code) if isinstance(names.get(code), dict) else {}
|
||||||
|
languages[code] = {
|
||||||
|
"name": (given.get("name") or "").strip() or name,
|
||||||
|
"tagline": (given.get("tagline") or "").strip() or tagline,
|
||||||
|
# What was actually stored, for the form: a field showing the
|
||||||
|
# fallback as its value would save the fallback the first time
|
||||||
|
# anybody pressed the button, freezing it.
|
||||||
|
"stored_name": (given.get("name") or "").strip(),
|
||||||
|
"stored_tagline": (given.get("tagline") or "").strip(),
|
||||||
|
}
|
||||||
|
|
||||||
|
def column(name, default=""):
|
||||||
|
return ((row[name] if row else None) or default)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"languages": languages,
|
||||||
|
"social": {key: social.get(key, "") for key, _, _ in NETWORKS},
|
||||||
|
"email": column("email"),
|
||||||
|
"phone": column("phone"),
|
||||||
|
"city": column("city"),
|
||||||
|
"street": column("street"),
|
||||||
|
"share_image": column("share_image"),
|
||||||
|
"footer_text": column("footer_text"),
|
||||||
|
"updated_at": row["updated_at"] if row else None,
|
||||||
|
"published_at": row["published_at"] if row else None,
|
||||||
|
"customised": row is not None,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _read(form, errors: list[str]) -> dict:
|
||||||
|
"""The whole form, checked. Nothing here is written as it arrived."""
|
||||||
|
names = {}
|
||||||
|
for code, label, _name, _tagline in LANGUAGES:
|
||||||
|
name = (form.get(f"name-{code}") or "").strip()[:NAME_MAX]
|
||||||
|
tagline = (form.get(f"tagline-{code}") or "").strip()[:TAGLINE_MAX]
|
||||||
|
# One line, always: a tagline with a newline in it is an og:description
|
||||||
|
# that renders raggedly in some readers and truncated in others.
|
||||||
|
tagline = re.sub(r"\s+", " ", tagline)
|
||||||
|
if name or tagline:
|
||||||
|
names[code] = {"name": name, "tagline": tagline}
|
||||||
|
|
||||||
|
social = {}
|
||||||
|
for key, label, _placeholder in NETWORKS:
|
||||||
|
url = (form.get(f"social-{key}") or "").strip()
|
||||||
|
if not url:
|
||||||
|
continue
|
||||||
|
if not URL_RE.match(url):
|
||||||
|
errors.append(f"La dirección de {label} tiene que empezar por https://.")
|
||||||
|
continue
|
||||||
|
social[key] = url
|
||||||
|
|
||||||
|
email = (form.get("email") or "").strip()[:120]
|
||||||
|
if email and not EMAIL_RE.match(email):
|
||||||
|
errors.append("Ese correo de contacto no parece una dirección.")
|
||||||
|
email = ""
|
||||||
|
|
||||||
|
share = (form.get("share_image") or "").strip()
|
||||||
|
if share and not re.match(r"^/uploads/[A-Za-z0-9._-]+$", share):
|
||||||
|
errors.append("La imagen al compartir tiene que ser una de /uploads/.")
|
||||||
|
share = ""
|
||||||
|
|
||||||
|
return {
|
||||||
|
"names": names, "social": social, "email": email,
|
||||||
|
"phone": (form.get("phone") or "").strip()[:40],
|
||||||
|
"city": (form.get("city") or "").strip()[:80],
|
||||||
|
"street": (form.get("street") or "").strip()[:160],
|
||||||
|
"share_image": share,
|
||||||
|
"footer_text": (form.get("footer_text") or "").strip()[:FOOTER_MAX],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# --- routes ----------------------------------------------------------------
|
||||||
|
|
||||||
|
@bp.route("/gestion/identidad", methods=["GET", "POST"])
|
||||||
|
@superadmin_required
|
||||||
|
def edit():
|
||||||
|
if request.method == "GET":
|
||||||
|
return render_template("identity_form.html", state=current(),
|
||||||
|
languages=LANGUAGES, networks=NETWORKS)
|
||||||
|
|
||||||
|
errors: list[str] = []
|
||||||
|
fields = _read(request.form, errors)
|
||||||
|
if errors:
|
||||||
|
for message in errors:
|
||||||
|
flash(message, "error")
|
||||||
|
return redirect(url_for("identity.edit"))
|
||||||
|
|
||||||
|
get_db().execute(
|
||||||
|
"""INSERT INTO site (id, names_json, social_json, email, phone, city,
|
||||||
|
street, share_image, footer_text,
|
||||||
|
updated_by, updated_at, published_at)
|
||||||
|
VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), NULL)
|
||||||
|
ON CONFLICT(id) DO UPDATE SET
|
||||||
|
names_json = excluded.names_json,
|
||||||
|
social_json = excluded.social_json,
|
||||||
|
email = excluded.email, phone = excluded.phone,
|
||||||
|
city = excluded.city, street = excluded.street,
|
||||||
|
share_image = excluded.share_image,
|
||||||
|
footer_text = excluded.footer_text,
|
||||||
|
updated_by = excluded.updated_by,
|
||||||
|
updated_at = excluded.updated_at,
|
||||||
|
published_at = NULL""",
|
||||||
|
(json.dumps(fields["names"], sort_keys=True, ensure_ascii=False),
|
||||||
|
json.dumps(fields["social"], sort_keys=True), fields["email"],
|
||||||
|
fields["phone"], fields["city"], fields["street"],
|
||||||
|
fields["share_image"], fields["footer_text"], g.member["id"]),
|
||||||
|
)
|
||||||
|
activity.log("identity.saved")
|
||||||
|
if _publish():
|
||||||
|
flash("Guardado. El sitio público se reconstruye en un par de minutos.", "ok")
|
||||||
|
return redirect(url_for("identity.edit"))
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/gestion/identidad/publicar", methods=["POST"])
|
||||||
|
@superadmin_required
|
||||||
|
def publish():
|
||||||
|
if _publish():
|
||||||
|
flash("Publicado. El sitio público se reconstruye en un par de minutos.", "ok")
|
||||||
|
return redirect(url_for("identity.edit"))
|
||||||
|
|
||||||
|
|
||||||
|
# --- the public site's copy ------------------------------------------------
|
||||||
|
|
||||||
|
def _quote(value: str) -> str:
|
||||||
|
"""A double-quoted YAML scalar. Backslashes and quotes are the only two
|
||||||
|
characters that can end one, and both are escapable inside it."""
|
||||||
|
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
|
||||||
|
|
||||||
|
|
||||||
|
def yaml_for(state: dict) -> str:
|
||||||
|
"""`data/site.yaml`, written rather than dumped — the same trade `brand.py`
|
||||||
|
makes, for the same reason: PyYAML is not a dependency of the members area
|
||||||
|
and is not worth becoming one for thirty lines of output.
|
||||||
|
|
||||||
|
Only what was actually stored is written. A file repeating `config.yaml`'s
|
||||||
|
own values back at it would make the fallback meaningless and freeze the
|
||||||
|
defaults at whatever this version thought they were.
|
||||||
|
"""
|
||||||
|
lines = ["# Generado desde Gestión → Identidad en vienalatina.com/comunidad.",
|
||||||
|
"# No editar a mano: el próximo guardado lo sobrescribe."]
|
||||||
|
|
||||||
|
languages = {code: data for code, data in state["languages"].items()
|
||||||
|
if data["stored_name"] or data["stored_tagline"]}
|
||||||
|
if languages:
|
||||||
|
lines.append("languages:")
|
||||||
|
for code, data in languages.items():
|
||||||
|
lines.append(f" {code}:")
|
||||||
|
if data["stored_name"]:
|
||||||
|
lines.append(f" name: {_quote(data['stored_name'])}")
|
||||||
|
if data["stored_tagline"]:
|
||||||
|
lines.append(f" tagline: {_quote(data['stored_tagline'])}")
|
||||||
|
|
||||||
|
social = [url for url in state["social"].values() if url]
|
||||||
|
if social:
|
||||||
|
# A flat list, because `sameAs` is a list of URLs and the names of the
|
||||||
|
# networks are nowhere in the schema.
|
||||||
|
lines.append("sameAs:")
|
||||||
|
lines += [f" - {_quote(url)}" for url in social]
|
||||||
|
lines.append("social:")
|
||||||
|
for key, url in state["social"].items():
|
||||||
|
if url:
|
||||||
|
lines.append(f" {key}: {_quote(url)}")
|
||||||
|
|
||||||
|
for key in ("email", "phone", "city", "street", "share_image", "footer_text"):
|
||||||
|
if state[key]:
|
||||||
|
lines.append(f"{key}: {_quote(state[key])}")
|
||||||
|
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
|
|
||||||
|
|
||||||
|
def _publish() -> bool:
|
||||||
|
"""Commit the identity. True if it got there.
|
||||||
|
|
||||||
|
Returns False and says why rather than raising, exactly as `brand._publish`
|
||||||
|
does: the values are already saved here, and a superadministrator whose
|
||||||
|
change took effect in the members area needs to know the public site is a
|
||||||
|
step behind, not to meet a traceback.
|
||||||
|
"""
|
||||||
|
state = current()
|
||||||
|
try:
|
||||||
|
token = gitea.content_token()
|
||||||
|
except gitea.GiteaError as exc:
|
||||||
|
flash(f"Guardado aquí. El sitio público no se ha actualizado: {exc}", "error")
|
||||||
|
return False
|
||||||
|
|
||||||
|
# The contents API wants the current sha to replace a file and refuses one
|
||||||
|
# when creating, so the read comes first and a missing file is the normal
|
||||||
|
# case the first time. Same shape as `brand._write`.
|
||||||
|
try:
|
||||||
|
_, sha = gitea.read_file(DATA_FILE, token)
|
||||||
|
except gitea.GiteaError:
|
||||||
|
sha = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
gitea.write_file(DATA_FILE, yaml_for(state).encode("utf-8"),
|
||||||
|
"identidad: datos del sitio", token, sha=sha)
|
||||||
|
except (gitea.GiteaError, OSError) as exc:
|
||||||
|
current_app.logger.warning("identity publish failed: %s", exc)
|
||||||
|
flash(f"Guardado aquí. El sitio público no se ha actualizado: {exc}", "error")
|
||||||
|
return False
|
||||||
|
|
||||||
|
get_db().execute("UPDATE site SET published_at = datetime('now') WHERE id = 1")
|
||||||
|
return True
|
||||||
104
apps/board/media.py
Normal file
104
apps/board/media.py
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
"""Biblioteca de medios — every picture the public site carries.
|
||||||
|
|
||||||
|
WordPress's Media Library, and the reason it earns a place here is narrower than
|
||||||
|
WordPress's: **nothing has ever been able to see an orphan.** A picture is
|
||||||
|
committed to `static/uploads/` when a post is written; delete the post and the
|
||||||
|
picture stays in the repository, deployed, referenced by nothing, for good.
|
||||||
|
There has been no way to list them, no way to notice, and no way to remove one
|
||||||
|
short of a commit by hand.
|
||||||
|
|
||||||
|
So this is a listing with one question answered per row — which posts use this —
|
||||||
|
and one action: delete the ones nobody uses.
|
||||||
|
|
||||||
|
**Open to administrators**, unlike the rest of Gestión's new screens. They are
|
||||||
|
the people who upload, so they are the people who should be able to see what
|
||||||
|
they have uploaded; and the worst an administrator can do here is remove a
|
||||||
|
picture from a post they could already have edited.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from flask import (Blueprint, abort, flash, redirect, render_template, request,
|
||||||
|
url_for)
|
||||||
|
|
||||||
|
from . import activity, content, gitea
|
||||||
|
from .db import get_db
|
||||||
|
from .security import admin_required
|
||||||
|
|
||||||
|
bp = Blueprint("media", __name__)
|
||||||
|
|
||||||
|
FOLDER = content.UPLOAD_FOLDER # static/uploads
|
||||||
|
|
||||||
|
|
||||||
|
def _users() -> dict[str, list[str]]:
|
||||||
|
"""Which posts reference which picture, from the cache the listing fills.
|
||||||
|
|
||||||
|
From `content_cache.image` rather than by reading every post's frontmatter:
|
||||||
|
the whole point of that cache is that a page like this one costs one
|
||||||
|
directory request to the git server rather than one request per post.
|
||||||
|
|
||||||
|
A path appears in frontmatter as `/uploads/foto-abc.jpg`; the repository
|
||||||
|
calls it `static/uploads/foto-abc.jpg`. The basename is what both agree on.
|
||||||
|
"""
|
||||||
|
rows = get_db().execute(
|
||||||
|
"SELECT title, image FROM content_cache WHERE image IS NOT NULL AND image != ''"
|
||||||
|
).fetchall()
|
||||||
|
used: dict[str, list[str]] = {}
|
||||||
|
for row in rows:
|
||||||
|
used.setdefault(row["image"].rsplit("/", 1)[-1], []).append(row["title"])
|
||||||
|
return used
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/gestion/medios")
|
||||||
|
@admin_required
|
||||||
|
def index():
|
||||||
|
used = _users()
|
||||||
|
try:
|
||||||
|
files = gitea.list_directory(FOLDER, gitea.content_token())
|
||||||
|
except (gitea.GiteaError, OSError) as exc:
|
||||||
|
flash(f"No se pudo leer la carpeta de imágenes: {exc}", "error")
|
||||||
|
files = []
|
||||||
|
|
||||||
|
items = []
|
||||||
|
for entry in files:
|
||||||
|
name = entry.get("name", "")
|
||||||
|
items.append({
|
||||||
|
"name": name,
|
||||||
|
"url": f"/uploads/{name}",
|
||||||
|
"sha": entry.get("sha", ""),
|
||||||
|
"size": (entry.get("size") or 0) // 1024,
|
||||||
|
"posts": used.get(name, []),
|
||||||
|
})
|
||||||
|
# Orphans first: they are the only rows anybody has to act on, and a
|
||||||
|
# listing sorted by name buries them among the ones doing their job.
|
||||||
|
items.sort(key=lambda item: (bool(item["posts"]), item["name"]))
|
||||||
|
return render_template("media.html", items=items,
|
||||||
|
orphans=sum(1 for i in items if not i["posts"]))
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/gestion/medios/<name>/eliminar", methods=["POST"])
|
||||||
|
@admin_required
|
||||||
|
def delete(name: str):
|
||||||
|
"""Remove a picture nobody uses.
|
||||||
|
|
||||||
|
**Refuses one that is in use**, from the handler and not only by hiding the
|
||||||
|
button: deleting a referenced picture leaves a broken image on a published
|
||||||
|
page, which is worse than an orphan nobody sees.
|
||||||
|
"""
|
||||||
|
if "/" in name or name.startswith("."):
|
||||||
|
abort(404)
|
||||||
|
if _users().get(name):
|
||||||
|
flash("Esa imagen está en uso. Quítala del artículo primero.", "error")
|
||||||
|
return redirect(url_for("media.index"))
|
||||||
|
|
||||||
|
sha = (request.form.get("sha") or "").strip()
|
||||||
|
try:
|
||||||
|
gitea.delete_file(f"{FOLDER}/{name}", sha, f"medios: retirar {name}",
|
||||||
|
gitea.content_token())
|
||||||
|
except (gitea.GiteaError, OSError) as exc:
|
||||||
|
flash(f"No se pudo borrar: {exc}", "error")
|
||||||
|
return redirect(url_for("media.index"))
|
||||||
|
|
||||||
|
activity.log("media.deleted", name)
|
||||||
|
flash(f"{name} borrada. El sitio se reconstruye en un par de minutos.", "ok")
|
||||||
|
return redirect(url_for("media.index"))
|
||||||
@ -1,11 +1,14 @@
|
|||||||
"""Members and roles.
|
"""Members and roles.
|
||||||
|
|
||||||
Four roles, and the rules between them are short enough to state in full:
|
Five 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
|
* exactly one **superadministrador**, who runs the platform: admin accounts,
|
||||||
on; nobody can deactivate or demote them, including themselves
|
the look, the identity and the system tools. Nobody can deactivate, demote or
|
||||||
* **admins** create, deactivate and promote members, moderate the board, and
|
erase them, including themselves
|
||||||
publish and edit the static pages of the public site
|
* exactly one **responsable**, who runs the association: members, moderators
|
||||||
|
and invitations. They cannot touch an admin, the look or the identity
|
||||||
|
* **admins** create, deactivate and promote members and moderators, 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,
|
* **moderators** approve or reject what members propose for the public site,
|
||||||
and publish their own posts without waiting for anybody. They have no power
|
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
|
over people: moderating content is not the same authority, and giving one the
|
||||||
@ -27,10 +30,11 @@ import sqlite3
|
|||||||
from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
|
from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
|
||||||
render_template, request, url_for)
|
render_template, request, url_for)
|
||||||
|
|
||||||
from . import auth, invites, mail, messages, profiles, uploads
|
from . import activity, auth, invites, mail, messages, profiles, uploads
|
||||||
from .db import TOMBSTONE_LOGIN, get_db
|
from .db import TOMBSTONE_LOGIN, get_db
|
||||||
from .render import to_html
|
from .render import to_html
|
||||||
from .security import admin_required, login_required, owner_required
|
from .security import (admin_required, login_required, owner_required,
|
||||||
|
superadmin_required)
|
||||||
|
|
||||||
bp = Blueprint("members", __name__)
|
bp = Blueprint("members", __name__)
|
||||||
|
|
||||||
@ -41,20 +45,35 @@ LOGIN_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9._-]{0,38}[A-Za-z0-9])?$")
|
|||||||
# "Miembro" rather than "Usuario" on the screens, while the stored value stays
|
# "Miembro" rather than "Usuario" on the screens, while the stored value stays
|
||||||
# `user`: renaming the value would mean a migration and rewriting every role
|
# `user`: renaming the value would mean a migration and rewriting every role
|
||||||
# check for a word nobody types.
|
# check for a word nobody types.
|
||||||
ROLE_LABELS = {"owner": "Responsable", "admin": "Administrador",
|
ROLE_LABELS = {"superadmin": "Superadministrador", "owner": "Responsable",
|
||||||
"moderator": "Moderador", "user": "Miembro"}
|
"admin": "Administrador", "moderator": "Moderador",
|
||||||
|
"user": "Miembro"}
|
||||||
|
|
||||||
# Who may be given which role on the Miembros screen, most trusted first, so
|
# Who may be given which role, by whom. A function rather than the constant it
|
||||||
# the form and the predicates below cannot disagree about the list.
|
# used to be, because the answer now depends on who is asking: the role picker
|
||||||
ASSIGNABLE_ROLES = ("admin", "moderator", "user")
|
# must never offer what the handler will refuse, and with two levels above admin
|
||||||
|
# a single list can only be right for one of them.
|
||||||
|
def assignable_roles(actor_role: str) -> tuple[str, ...]:
|
||||||
|
return tuple(role for role in ("admin", "moderator", "user")
|
||||||
|
if may_create(actor_role, role))
|
||||||
|
|
||||||
|
|
||||||
def may_create(actor_role: str, target_role: str) -> bool:
|
def may_create(actor_role: str, target_role: str) -> bool:
|
||||||
"""Who may bring whom in. Admins cannot mint more admins."""
|
"""Who may bring whom in.
|
||||||
|
|
||||||
|
**An admin account is the superadministrator's alone** — that is the line
|
||||||
|
this phase exists to draw. The responsable runs the association and can fill
|
||||||
|
it with members and moderators; who administers the platform is not theirs
|
||||||
|
to decide, which is what makes it safe to hand the responsable chair to a
|
||||||
|
customer organisation's president.
|
||||||
|
|
||||||
|
Nobody creates a superadministrator or a responsable here. Both are single
|
||||||
|
chairs held by a unique index, and both change hands by transfer, below.
|
||||||
|
"""
|
||||||
if target_role == "admin":
|
if target_role == "admin":
|
||||||
return actor_role == "owner"
|
return actor_role == "superadmin"
|
||||||
if target_role in ("moderator", "user"):
|
if target_role in ("moderator", "user"):
|
||||||
return actor_role in ("owner", "admin")
|
return actor_role in ("superadmin", "owner", "admin")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
@ -64,12 +83,20 @@ def may_manage(actor_role: str, target_role: str) -> bool:
|
|||||||
A moderator appears nowhere in this function, deliberately: they approve
|
A moderator appears nowhere in this function, deliberately: they approve
|
||||||
posts and nothing else. Being trusted to judge what the public reads is not
|
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.
|
the same as being trusted to suspend the person who wrote it.
|
||||||
|
|
||||||
|
The two chairs are out of reach by the same rule that put them there. A
|
||||||
|
superadministrator cannot be suspended or demoted by anybody, themselves
|
||||||
|
included — the way out is to hand the platform on. The responsable is out of
|
||||||
|
reach of everyone below, and of the superadministrator too: the chair is the
|
||||||
|
association's, and a platform administrator quietly removing the president
|
||||||
|
of the organisation they host is exactly the move this separation exists to
|
||||||
|
make impossible. Transferring it is the association's own act.
|
||||||
"""
|
"""
|
||||||
if target_role == "owner":
|
if target_role in ("superadmin", "owner"):
|
||||||
return False # the owner is out of reach of everyone, themselves included
|
return False
|
||||||
if target_role == "admin":
|
if target_role == "admin":
|
||||||
return actor_role == "owner"
|
return actor_role == "superadmin"
|
||||||
return actor_role in ("owner", "admin")
|
return actor_role in ("superadmin", "owner", "admin")
|
||||||
|
|
||||||
|
|
||||||
def tombstone_id(db: sqlite3.Connection) -> int:
|
def tombstone_id(db: sqlite3.Connection) -> int:
|
||||||
@ -77,17 +104,28 @@ def tombstone_id(db: sqlite3.Connection) -> int:
|
|||||||
return row["id"]
|
return row["id"]
|
||||||
|
|
||||||
|
|
||||||
def transfer_ownership(db: sqlite3.Connection, owner_id: int, target_id: int) -> None:
|
def transfer_ownership(db: sqlite3.Connection, holder_id: int, target_id: int,
|
||||||
"""Hand ownership to an admin, atomically.
|
chair: str) -> None:
|
||||||
|
"""Hand one of the two chairs on, atomically.
|
||||||
|
|
||||||
The demotion has to come first. With the partial unique index in place, a
|
The demotion has to come first. With the partial unique index in place, a
|
||||||
promote-then-demote order would momentarily ask for two owners and the
|
promote-then-demote order would momentarily ask for two holders of the chair
|
||||||
database would refuse — correctly, but confusingly.
|
and the database would refuse — correctly, but confusingly.
|
||||||
|
|
||||||
|
`chair` is 'superadmin' or 'owner' and comes from the route, never from a
|
||||||
|
request. The person giving it up becomes an admin, which is the most they
|
||||||
|
can be left with: there is no role above the one they just gave away.
|
||||||
|
|
||||||
|
Filling an empty chair is the same call with nobody to demote — the first
|
||||||
|
UPDATE matches no row and the transaction is one statement shorter.
|
||||||
"""
|
"""
|
||||||
|
if chair not in ("superadmin", "owner"):
|
||||||
|
raise ValueError(f"not a chair: {chair!r}")
|
||||||
db.execute("BEGIN IMMEDIATE")
|
db.execute("BEGIN IMMEDIATE")
|
||||||
try:
|
try:
|
||||||
db.execute("UPDATE members SET role = 'admin' WHERE id = ?", (owner_id,))
|
db.execute("UPDATE members SET role = 'admin' WHERE id = ? AND role = ?",
|
||||||
db.execute("UPDATE members SET role = 'owner' WHERE id = ?", (target_id,))
|
(holder_id, chair))
|
||||||
|
db.execute("UPDATE members SET role = ? WHERE id = ?", (chair, target_id))
|
||||||
db.execute("COMMIT")
|
db.execute("COMMIT")
|
||||||
except Exception:
|
except Exception:
|
||||||
db.execute("ROLLBACK")
|
db.execute("ROLLBACK")
|
||||||
@ -115,9 +153,15 @@ CLEARED_ON_ERASE = {
|
|||||||
# admin who typed it in: the meeting still happens after they leave, so the
|
# admin who typed it in: the meeting still happens after they leave, so the
|
||||||
# row stays and the name goes.
|
# row stays and the name goes.
|
||||||
("events", "created_by"),
|
("events", "created_by"),
|
||||||
# Same for the colours and the logo. An admin leaving is not a reason for
|
# Same for the colours and the logo. Whoever set them leaving is not a
|
||||||
# the site to go back to looking like a default install.
|
# reason for the site to go back to looking like a default install.
|
||||||
("brand", "updated_by"),
|
("brand", "updated_by"),
|
||||||
|
("site", "updated_by"),
|
||||||
|
# That a role was changed is the association's record; whose name was on it
|
||||||
|
# is the erased person's data. The row stays, the name goes — which is also
|
||||||
|
# why the log is not a cascade: an audit trail that deletes itself when the
|
||||||
|
# person who triggered it leaves is not an audit trail.
|
||||||
|
("activity", "actor_id"),
|
||||||
}
|
}
|
||||||
|
|
||||||
# Private correspondence is not reassigned to the tombstone, it goes. A thread
|
# Private correspondence is not reassigned to the tombstone, it goes. A thread
|
||||||
@ -319,7 +363,7 @@ def new():
|
|||||||
if request.method == "GET":
|
if request.method == "GET":
|
||||||
return render_template(
|
return render_template(
|
||||||
"member_new.html",
|
"member_new.html",
|
||||||
can_make_admin=g.member["role"] == "owner",
|
can_make_admin=may_create(g.member["role"], "admin"),
|
||||||
# Without mail the invitation cannot leave the building, so the
|
# Without mail the invitation cannot leave the building, so the
|
||||||
# admin has to pass the link on by hand. Worth knowing before
|
# admin has to pass the link on by hand. Worth knowing before
|
||||||
# filling the form rather than after.
|
# filling the form rather than after.
|
||||||
@ -384,6 +428,8 @@ def new():
|
|||||||
except mail.MailFailed:
|
except mail.MailFailed:
|
||||||
invite_link, mail_problem = link, "failed"
|
invite_link, mail_problem = link, "failed"
|
||||||
|
|
||||||
|
activity.log("member.created", display_name or login,
|
||||||
|
f"rol: {ROLE_LABELS[role]}")
|
||||||
return render_template("member_created.html", login=login,
|
return render_template("member_created.html", login=login,
|
||||||
email=email, created=True,
|
email=email, created=True,
|
||||||
invite_link=invite_link, mail_problem=mail_problem,
|
invite_link=invite_link, mail_problem=mail_problem,
|
||||||
@ -425,6 +471,7 @@ def invite(member_id: int):
|
|||||||
flash(f"No se pudo enviar el correo. Pásale este enlace: {link}", "error")
|
flash(f"No se pudo enviar el correo. Pásale este enlace: {link}", "error")
|
||||||
return redirect(_page(target))
|
return redirect(_page(target))
|
||||||
|
|
||||||
|
activity.log("member.invited", target["display_name"], target["email"])
|
||||||
flash(f"Invitación enviada a {target['email']}.", "ok")
|
flash(f"Invitación enviada a {target['email']}.", "ok")
|
||||||
return redirect(_page(target))
|
return redirect(_page(target))
|
||||||
|
|
||||||
@ -437,6 +484,8 @@ def set_active(member_id: int):
|
|||||||
abort(403)
|
abort(403)
|
||||||
active = 1 if request.form.get("active") == "1" else 0
|
active = 1 if request.form.get("active") == "1" else 0
|
||||||
get_db().execute("UPDATE members SET active = ? WHERE id = ?", (active, member_id))
|
get_db().execute("UPDATE members SET active = ? WHERE id = ?", (active, member_id))
|
||||||
|
activity.log("member.restored" if active else "member.suspended",
|
||||||
|
target["display_name"])
|
||||||
flash(f"{target['display_name']}: acceso {'restaurado' if active else 'suspendido'}.", "ok")
|
flash(f"{target['display_name']}: acceso {'restaurado' if active else 'suspendido'}.", "ok")
|
||||||
return redirect(_page(target))
|
return redirect(_page(target))
|
||||||
|
|
||||||
@ -454,13 +503,15 @@ def set_role(member_id: int):
|
|||||||
"""
|
"""
|
||||||
target = _load(member_id)
|
target = _load(member_id)
|
||||||
role = request.form.get("role", "")
|
role = request.form.get("role", "")
|
||||||
if role not in ASSIGNABLE_ROLES:
|
if role not in assignable_roles(g.member["role"]):
|
||||||
abort(403)
|
abort(403)
|
||||||
if not may_manage(g.member["role"], target["role"]):
|
if not may_manage(g.member["role"], target["role"]):
|
||||||
abort(403)
|
abort(403)
|
||||||
if not may_create(g.member["role"], role):
|
if not may_create(g.member["role"], role):
|
||||||
abort(403)
|
abort(403)
|
||||||
get_db().execute("UPDATE members SET role = ? WHERE id = ?", (role, member_id))
|
get_db().execute("UPDATE members SET role = ? WHERE id = ?", (role, member_id))
|
||||||
|
activity.log("role.changed", target["display_name"],
|
||||||
|
f"{ROLE_LABELS[target['role']]} → {ROLE_LABELS[role]}")
|
||||||
flash(f"{target['display_name']} ahora es {ROLE_LABELS[role].lower()}.", "ok")
|
flash(f"{target['display_name']} ahora es {ROLE_LABELS[role].lower()}.", "ok")
|
||||||
return redirect(_page(target))
|
return redirect(_page(target))
|
||||||
|
|
||||||
@ -468,12 +519,36 @@ def set_role(member_id: int):
|
|||||||
@bp.route("/miembros/<int:member_id>/transferir", methods=["POST"])
|
@bp.route("/miembros/<int:member_id>/transferir", methods=["POST"])
|
||||||
@owner_required
|
@owner_required
|
||||||
def transfer(member_id: int):
|
def transfer(member_id: int):
|
||||||
|
"""Hand the association on. The responsable's own act, or the
|
||||||
|
superadministrator filling an empty chair."""
|
||||||
|
target = _load(member_id)
|
||||||
|
if target["role"] not in ("admin", "moderator", "user") or not target["active"]:
|
||||||
|
flash("Solo puedes nombrar responsable a un miembro activo.", "error")
|
||||||
|
return redirect(_page(target))
|
||||||
|
transfer_ownership(get_db(), g.member["id"], target["id"], "owner")
|
||||||
|
activity.log("chair.owner", target["display_name"])
|
||||||
|
flash(f"{target['display_name']} es ahora el responsable.", "ok")
|
||||||
|
return redirect(_page(target))
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/miembros/<int:member_id>/transferir-plataforma", methods=["POST"])
|
||||||
|
@superadmin_required
|
||||||
|
def transfer_platform(member_id: int):
|
||||||
|
"""Hand the platform on.
|
||||||
|
|
||||||
|
Separate from the route above because they are different jobs, and because
|
||||||
|
conflating them is how somebody hands away more than they meant to: this one
|
||||||
|
is irreversible from the giver's side — the moment it commits, the person
|
||||||
|
running it is an admin and cannot take it back.
|
||||||
|
"""
|
||||||
target = _load(member_id)
|
target = _load(member_id)
|
||||||
if target["role"] != "admin" or not target["active"]:
|
if target["role"] != "admin" or not target["active"]:
|
||||||
flash("Solo puedes transferir la titularidad a un administrador activo.", "error")
|
flash("Solo puedes entregar la plataforma a un administrador activo.", "error")
|
||||||
return redirect(_page(target))
|
return redirect(_page(target))
|
||||||
transfer_ownership(get_db(), g.member["id"], target["id"])
|
transfer_ownership(get_db(), g.member["id"], target["id"], "superadmin")
|
||||||
flash(f"{target['display_name']} es ahora el responsable. Tú eres administrador.", "ok")
|
activity.log("chair.superadmin", target["display_name"])
|
||||||
|
flash(f"{target['display_name']} es ahora el superadministrador. "
|
||||||
|
"Tú eres administrador.", "ok")
|
||||||
return redirect(_page(target))
|
return redirect(_page(target))
|
||||||
|
|
||||||
|
|
||||||
@ -481,12 +556,18 @@ def transfer(member_id: int):
|
|||||||
@owner_required
|
@owner_required
|
||||||
def erase(member_id: int):
|
def erase(member_id: int):
|
||||||
target = _load(member_id)
|
target = _load(member_id)
|
||||||
if target["role"] == "owner":
|
# Through the predicate rather than a bare role test: the two chairs are
|
||||||
|
# unreachable by exactly the rule that protects them everywhere else, and a
|
||||||
|
# second spelling of it here is a second place to get it wrong.
|
||||||
|
if not may_manage(g.member["role"], target["role"]):
|
||||||
abort(403)
|
abort(403)
|
||||||
# Files only after the transaction has committed: a rollback can put the
|
# Files only after the transaction has committed: a rollback can put the
|
||||||
# rows back, and nothing can put the pictures back.
|
# rows back, and nothing can put the pictures back.
|
||||||
for stored_name in erase_member(get_db(), member_id):
|
for stored_name in erase_member(get_db(), member_id):
|
||||||
uploads.remove(stored_name)
|
uploads.remove(stored_name)
|
||||||
|
# After the transaction: a row recording an erasure that rolled back is a
|
||||||
|
# worse record than no row.
|
||||||
|
activity.log("member.erased", target["display_name"])
|
||||||
flash(f"{target['display_name']} eliminado. Sus mensajes quedan como «Miembro eliminado».", "ok")
|
flash(f"{target['display_name']} eliminado. Sus mensajes quedan como «Miembro eliminado».", "ok")
|
||||||
return redirect(url_for("members.index"))
|
return redirect(url_for("members.index"))
|
||||||
|
|
||||||
|
|||||||
@ -249,6 +249,95 @@ def _no_more_categories(db: sqlite3.Connection) -> None:
|
|||||||
db.execute(f"ALTER TABLE {table} DROP COLUMN categories")
|
db.execute(f"ALTER TABLE {table} DROP COLUMN categories")
|
||||||
|
|
||||||
|
|
||||||
|
def _a_superadmin_above_the_owner(db: sqlite3.Connection) -> None:
|
||||||
|
"""Add the `superadmin` role, and give it to whoever is the owner today.
|
||||||
|
|
||||||
|
The same rebuild as step 4, for the same reason — `role` carries a CHECK and
|
||||||
|
SQLite has no DROP CONSTRAINT — so the notes there about the eight tables
|
||||||
|
that reference `members`, about the rename, and about foreign keys being off
|
||||||
|
outside the transaction all apply here unchanged. Two things are particular
|
||||||
|
to this step:
|
||||||
|
|
||||||
|
* **Both partial unique indexes have to be created afterwards.** The copy
|
||||||
|
carries neither. Losing `members_one_owner` would quietly allow a second
|
||||||
|
responsable, and never creating `members_one_superadmin` would allow two
|
||||||
|
superadministrators — which is the one rule this whole phase rests on.
|
||||||
|
* **The existing owner is promoted.** Nobody has to type anything, nothing
|
||||||
|
is erased, and the person who could already do everything keeps being able
|
||||||
|
to. It leaves the responsable chair empty, which breaks nothing: a
|
||||||
|
superadministrator passes every check an owner passes, and the chair is
|
||||||
|
filled from inside the app whenever there is somebody to put in it.
|
||||||
|
"""
|
||||||
|
if "superadmin" 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 ('superadmin', '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")
|
||||||
|
# Promoted before the indexes exist, so the row is never momentarily both
|
||||||
|
# the only owner and the only superadmin under two rules at once.
|
||||||
|
db.execute("UPDATE members SET role = 'superadmin' WHERE role = 'owner'")
|
||||||
|
db.execute("""CREATE UNIQUE INDEX IF NOT EXISTS members_one_superadmin
|
||||||
|
ON members(role) WHERE role = 'superadmin'""")
|
||||||
|
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}")
|
||||||
|
|
||||||
|
|
||||||
|
def _room_for_identity_and_a_typeface(db: sqlite3.Connection) -> None:
|
||||||
|
"""Columns for the style half's new settings and for the media library.
|
||||||
|
|
||||||
|
Plain ADD COLUMNs — none of these is in a CHECK, an index or a foreign key,
|
||||||
|
which is what separates this from steps 1, 4 and 7.
|
||||||
|
|
||||||
|
`content_cache.image` is what turns "which post uses this picture?" into a
|
||||||
|
query. Without it the media library would re-read every post's frontmatter
|
||||||
|
from the git server on every page view, which is the exact cost that cache
|
||||||
|
was built to avoid.
|
||||||
|
|
||||||
|
The three new tables — `activity`, `site`, and nothing else — need no step
|
||||||
|
at all: `CREATE TABLE IF NOT EXISTS` in schema.sql runs before these and
|
||||||
|
creates them on any database that lacks them.
|
||||||
|
"""
|
||||||
|
for table, columns in (("brand", ("typeface", "font_name", "roundness")),
|
||||||
|
("content_cache", ("image",))):
|
||||||
|
existing = _columns(db, table)
|
||||||
|
if not existing:
|
||||||
|
continue
|
||||||
|
for column in columns:
|
||||||
|
if column not in existing:
|
||||||
|
db.execute(f"ALTER TABLE {table} ADD COLUMN {column} TEXT")
|
||||||
|
|
||||||
|
|
||||||
# (number, description, function). The number is the value written to
|
# (number, description, function). The number is the value written to
|
||||||
# user_version once the step succeeds.
|
# user_version once the step succeeds.
|
||||||
STEPS = [
|
STEPS = [
|
||||||
@ -258,6 +347,9 @@ STEPS = [
|
|||||||
(4, "members can be moderators", _members_can_moderate),
|
(4, "members can be moderators", _members_can_moderate),
|
||||||
(5, "events carry a date of their own", _rooms_for_a_date_of_its_own),
|
(5, "events carry a date of their own", _rooms_for_a_date_of_its_own),
|
||||||
(6, "there are no categories any more", _no_more_categories),
|
(6, "there are no categories any more", _no_more_categories),
|
||||||
|
(7, "a superadministrator above the responsable", _a_superadmin_above_the_owner),
|
||||||
|
(8, "room for the identity, a typeface and the media library",
|
||||||
|
_room_for_identity_and_a_typeface),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -20,9 +20,10 @@ CREATE TABLE IF NOT EXISTS members (
|
|||||||
bio TEXT,
|
bio TEXT,
|
||||||
links TEXT, -- JSON array of {label, url}
|
links TEXT, -- JSON array of {label, url}
|
||||||
photo_name TEXT,
|
photo_name TEXT,
|
||||||
-- 'moderator' arrived with migration 4, which had to rebuild this table:
|
-- 'moderator' arrived with migration 4 and 'superadmin' with migration 7,
|
||||||
-- SQLite has no DROP CONSTRAINT, so widening a CHECK is never an ALTER.
|
-- each of which had to rebuild this table: SQLite has no DROP CONSTRAINT, so
|
||||||
role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'moderator',
|
-- widening a CHECK is never an ALTER.
|
||||||
|
role TEXT NOT NULL CHECK (role IN ('superadmin', 'owner', 'admin', 'moderator',
|
||||||
'user', 'tombstone')),
|
'user', 'tombstone')),
|
||||||
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
|
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
|
||||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||||
@ -30,9 +31,17 @@ CREATE TABLE IF NOT EXISTS members (
|
|||||||
last_seen_at TEXT
|
last_seen_at TEXT
|
||||||
);
|
);
|
||||||
|
|
||||||
-- The one-owner rule, held by the database rather than by the application, so
|
-- Two chairs, one person each, held by the database rather than by the
|
||||||
-- a mistake in a handler cannot produce a second owner. SQLite enforces a
|
-- application, so a mistake in a handler cannot produce a second of either.
|
||||||
-- partial unique index exactly like a full one.
|
-- SQLite enforces a partial unique index exactly like a full one.
|
||||||
|
-- The superadministrator runs the platform — admin accounts, the look
|
||||||
|
-- and the identity — and the responsable runs the association — the members,
|
||||||
|
-- the moderators and the invitations. Installed for a second organisation, the
|
||||||
|
-- first is whoever maintains the box and the second is their president, which
|
||||||
|
-- is the whole reason the two are separate rows rather than one.
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS members_one_superadmin
|
||||||
|
ON members(role) WHERE role = 'superadmin';
|
||||||
|
|
||||||
CREATE UNIQUE INDEX IF NOT EXISTS members_one_owner
|
CREATE UNIQUE INDEX IF NOT EXISTS members_one_owner
|
||||||
ON members(role) WHERE role = 'owner';
|
ON members(role) WHERE role = 'owner';
|
||||||
|
|
||||||
@ -343,9 +352,70 @@ CREATE TABLE IF NOT EXISTS brand (
|
|||||||
custom_css TEXT NOT NULL DEFAULT '',
|
custom_css TEXT NOT NULL DEFAULT '',
|
||||||
logo_name TEXT,
|
logo_name TEXT,
|
||||||
favicon_name TEXT,
|
favicon_name TEXT,
|
||||||
|
-- A key from brand.TYPEFACES, or 'propia' when `font_name` holds an uploaded
|
||||||
|
-- .woff2. Null means the one the site was built with.
|
||||||
|
typeface TEXT,
|
||||||
|
font_name TEXT,
|
||||||
|
-- A key from brand.ROUNDNESS. One setting driving four radius tokens: a site
|
||||||
|
-- whose cards are round and whose buttons are square looks like two sites.
|
||||||
|
roundness TEXT,
|
||||||
-- Cleared rather than reassigned when that member is erased: the colours
|
-- Cleared rather than reassigned when that member is erased: the colours
|
||||||
-- belong to the association, like an event in the calendar.
|
-- belong to the association, like an event in the calendar.
|
||||||
updated_by INTEGER REFERENCES members(id),
|
updated_by INTEGER REFERENCES members(id),
|
||||||
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||||
published_at TEXT
|
published_at TEXT
|
||||||
);
|
);
|
||||||
|
|
||||||
|
-- What somebody did, for the superadministrator to read.
|
||||||
|
--
|
||||||
|
-- An audit trail is the natural companion to a role that can do everything: the
|
||||||
|
-- question "who made them an administrator?" has no other answer, and asking it
|
||||||
|
-- after the fact is exactly when nobody can remember.
|
||||||
|
--
|
||||||
|
-- `actor_id` is cleared and not cascaded when that member is erased. That a
|
||||||
|
-- role was changed is the association's record; whose name was on it is the
|
||||||
|
-- erased person's data, and the two can be separated.
|
||||||
|
--
|
||||||
|
-- Deliberately not a general event store. One row per act that changes who can
|
||||||
|
-- do what, or what the public sees — not page views, not sign-ins that worked.
|
||||||
|
CREATE TABLE IF NOT EXISTS activity (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
actor_id INTEGER REFERENCES members(id),
|
||||||
|
-- A short stable key: 'role.changed', 'member.erased', 'brand.saved'. Stable
|
||||||
|
-- because it is what a later reader greps for; short because the sentence a
|
||||||
|
-- person reads is built from it in the template, not stored here in Spanish.
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
-- What it was done to, as a display name or a title. A copy on purpose: the
|
||||||
|
-- row it names may be gone, and "erased Miembro eliminado" is not a record.
|
||||||
|
object TEXT NOT NULL DEFAULT '',
|
||||||
|
detail TEXT NOT NULL DEFAULT '',
|
||||||
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS activity_recent ON activity(created_at DESC);
|
||||||
|
|
||||||
|
-- The site's identity, as opposed to its look: what it is called, what it says
|
||||||
|
-- it is, where to find it. One row, pinned like `brand`.
|
||||||
|
--
|
||||||
|
-- Separate from `brand` because the two have different audiences and different
|
||||||
|
-- failure modes: a wrong colour is ugly, a wrong contact address is a message
|
||||||
|
-- nobody receives. They are also published to different files.
|
||||||
|
CREATE TABLE IF NOT EXISTS site (
|
||||||
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
|
-- {"es": {"name": …, "tagline": …}, "de": …}: per language, because the
|
||||||
|
-- tagline is prose and prose is not the same in three languages.
|
||||||
|
names_json TEXT NOT NULL DEFAULT '{}',
|
||||||
|
-- {"instagram": "https://…", …} → `sameAs` in the Organization schema, which
|
||||||
|
-- is how a search or answer engine knows an account and this site are one
|
||||||
|
-- body.
|
||||||
|
social_json TEXT NOT NULL DEFAULT '{}',
|
||||||
|
email TEXT NOT NULL DEFAULT '',
|
||||||
|
phone TEXT NOT NULL DEFAULT '',
|
||||||
|
city TEXT NOT NULL DEFAULT '',
|
||||||
|
street TEXT NOT NULL DEFAULT '',
|
||||||
|
share_image TEXT NOT NULL DEFAULT '',
|
||||||
|
footer_text TEXT NOT NULL DEFAULT '',
|
||||||
|
updated_by INTEGER REFERENCES members(id),
|
||||||
|
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||||
|
published_at TEXT
|
||||||
|
);
|
||||||
|
|||||||
@ -43,12 +43,38 @@ def login_required(view):
|
|||||||
return wrapped
|
return wrapped
|
||||||
|
|
||||||
|
|
||||||
|
# Most trusted first. Every decorator below is "this role or anything above it",
|
||||||
|
# which is the one rule worth keeping in a list rather than in four functions:
|
||||||
|
# adding a tier then means adding a word here, not auditing every check.
|
||||||
|
LADDER = ("superadmin", "owner", "admin", "moderator", "user")
|
||||||
|
|
||||||
|
|
||||||
|
def _at_least(rank: str):
|
||||||
|
"""The roles that pass a check for `rank` — it and everything above it."""
|
||||||
|
return LADDER[:LADDER.index(rank) + 1]
|
||||||
|
|
||||||
|
|
||||||
|
def is_at_least(role: str, rank: str) -> bool:
|
||||||
|
"""`role` is `rank` or anything above it.
|
||||||
|
|
||||||
|
Exported because seven places outside this module had the same question
|
||||||
|
written as a literal tuple — `g.member["role"] in ("owner", "admin")` — and
|
||||||
|
every one of them silently excluded the superadministrator the moment a tier
|
||||||
|
was added above owner. A tuple is a copy of a rule; this is the rule.
|
||||||
|
"""
|
||||||
|
return role in _at_least(rank)
|
||||||
|
|
||||||
|
|
||||||
def admin_required(view):
|
def admin_required(view):
|
||||||
"""Owner counts as an admin. Admin does not count as owner."""
|
"""The superadministrator and the responsable both count as admins.
|
||||||
|
|
||||||
|
Not the other way round: an admin is not a responsable, and neither is a
|
||||||
|
responsable the superadministrator.
|
||||||
|
"""
|
||||||
@wraps(view)
|
@wraps(view)
|
||||||
@login_required
|
@login_required
|
||||||
def wrapped(*args, **kwargs):
|
def wrapped(*args, **kwargs):
|
||||||
if g.member["role"] not in ("owner", "admin"):
|
if g.member["role"] not in _at_least("admin"):
|
||||||
abort(403)
|
abort(403)
|
||||||
return view(*args, **kwargs)
|
return view(*args, **kwargs)
|
||||||
return wrapped
|
return wrapped
|
||||||
@ -65,17 +91,39 @@ def moderator_required(view):
|
|||||||
@wraps(view)
|
@wraps(view)
|
||||||
@login_required
|
@login_required
|
||||||
def wrapped(*args, **kwargs):
|
def wrapped(*args, **kwargs):
|
||||||
if g.member["role"] not in ("owner", "admin", "moderator"):
|
if g.member["role"] not in _at_least("moderator"):
|
||||||
abort(403)
|
abort(403)
|
||||||
return view(*args, **kwargs)
|
return view(*args, **kwargs)
|
||||||
return wrapped
|
return wrapped
|
||||||
|
|
||||||
|
|
||||||
def owner_required(view):
|
def owner_required(view):
|
||||||
|
"""The association's chair. The superadministrator passes it too.
|
||||||
|
|
||||||
|
Everything the responsable may do, the superadministrator may do; the
|
||||||
|
reverse is the whole point of there being two roles, and is
|
||||||
|
`superadmin_required` below.
|
||||||
|
"""
|
||||||
@wraps(view)
|
@wraps(view)
|
||||||
@login_required
|
@login_required
|
||||||
def wrapped(*args, **kwargs):
|
def wrapped(*args, **kwargs):
|
||||||
if g.member["role"] != "owner":
|
if g.member["role"] not in _at_least("owner"):
|
||||||
|
abort(403)
|
||||||
|
return view(*args, **kwargs)
|
||||||
|
return wrapped
|
||||||
|
|
||||||
|
|
||||||
|
def superadmin_required(view):
|
||||||
|
"""The platform: admin accounts, the look, the identity, the system tools.
|
||||||
|
|
||||||
|
The only check with nothing above it. A responsable who wants one of these
|
||||||
|
screens is a responsable who should be asking the person who installed this,
|
||||||
|
which is exactly the line the two roles are drawn along.
|
||||||
|
"""
|
||||||
|
@wraps(view)
|
||||||
|
@login_required
|
||||||
|
def wrapped(*args, **kwargs):
|
||||||
|
if g.member["role"] != "superadmin":
|
||||||
abort(403)
|
abort(403)
|
||||||
return view(*args, **kwargs)
|
return view(*args, **kwargs)
|
||||||
return wrapped
|
return wrapped
|
||||||
|
|||||||
@ -816,3 +816,66 @@ input[type="file"] {
|
|||||||
|
|
||||||
.btn--danger { background: var(--danger); }
|
.btn--danger { background: var(--danger); }
|
||||||
.btn--danger:hover { background: var(--danger); filter: brightness(0.9); }
|
.btn--danger:hover { background: var(--danger); filter: brightness(0.9); }
|
||||||
|
|
||||||
|
/* --- the typeface picker ------------------------------------------------ */
|
||||||
|
|
||||||
|
/* Each option shown in the face it offers. Classes rather than a style
|
||||||
|
attribute on the label, because the Content-Security-Policy has no
|
||||||
|
'unsafe-inline' and style-src falls under default-src: an inline style here
|
||||||
|
is dropped and all four options render identically, which is a picker that
|
||||||
|
tells you nothing. The stacks are the ones in brand.TYPEFACES. */
|
||||||
|
.face { font-size: 1.05rem; }
|
||||||
|
.face--sans { font-family: "Montserrat", -apple-system, BlinkMacSystemFont,
|
||||||
|
"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; }
|
||||||
|
.face--serif { font-family: Georgia, Cambria, "Times New Roman", Times, serif; }
|
||||||
|
.face--redonda { font-family: "Trebuchet MS", "Segoe UI", Verdana, sans-serif; }
|
||||||
|
.face--sistema { font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
|
||||||
|
|
||||||
|
/* The font warning. One line closed, which is the point: it is four paragraphs
|
||||||
|
nobody needs until the moment they are uploading a typeface. */
|
||||||
|
.brand-warning {
|
||||||
|
margin: 0.75rem 0 1.5rem;
|
||||||
|
border: 1px solid var(--border-light);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
padding: 0.6rem 0.9rem;
|
||||||
|
background: var(--surface-soft);
|
||||||
|
}
|
||||||
|
.brand-warning summary { cursor: pointer; font-weight: 600; font-size: 0.9rem; }
|
||||||
|
.brand-warning p { font-size: 0.9rem; color: var(--muted); margin: 0.75rem 0 0; }
|
||||||
|
.brand-warning p:last-child { margin-bottom: 0.25rem; }
|
||||||
|
|
||||||
|
/* --- the media library -------------------------------------------------- */
|
||||||
|
|
||||||
|
.media-grid {
|
||||||
|
list-style: none;
|
||||||
|
margin: 1rem 0 0;
|
||||||
|
padding: 0;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
.media-item {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border-light);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
padding: 0.75rem;
|
||||||
|
}
|
||||||
|
/* Orphans are the only rows anybody has to act on, so they say so twice: first
|
||||||
|
in the order (they sort to the top) and then in the colour. */
|
||||||
|
.media-item--orphan { border-color: var(--brand); background: var(--brand-softer); }
|
||||||
|
.media-item img {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 120px;
|
||||||
|
object-fit: cover;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
background: var(--surface-soft);
|
||||||
|
}
|
||||||
|
.media-item p { margin: 0.4rem 0 0; word-break: break-all; }
|
||||||
|
.media-item form { margin-top: 0.5rem; }
|
||||||
|
|
||||||
|
/* --- the status screen -------------------------------------------------- */
|
||||||
|
|
||||||
|
.tag--ok { background: #e4f2e4; color: #1b5e20; }
|
||||||
|
.tag--warn { background: var(--brand-soft); color: var(--brand-dark); }
|
||||||
|
.tag--bad { background: #f6dcdc; color: var(--danger); }
|
||||||
|
|||||||
191
apps/board/status.py
Normal file
191
apps/board/status.py
Normal file
@ -0,0 +1,191 @@
|
|||||||
|
"""Estado del sistema — what is actually true of this server right now.
|
||||||
|
|
||||||
|
WordPress calls it Site Health. It earns its place here for a specific reason:
|
||||||
|
**every outage in this project has been a configuration fact that was invisible
|
||||||
|
until somebody hit it.** A `CONTENT_TOKEN` with the wrong scope looked exactly
|
||||||
|
like a working one until an editor pressed save and got a 500. Mail was
|
||||||
|
unconfigured for a week while invitations were "sent". The settings were right
|
||||||
|
in `.env.example` and absent from the container.
|
||||||
|
|
||||||
|
So this page asks the questions nobody thinks to ask, and asks them of the
|
||||||
|
running system rather than of a file:
|
||||||
|
|
||||||
|
* the content token is **exercised**, not merely checked for emptiness — the
|
||||||
|
single most valuable line here, because "present" was never the problem
|
||||||
|
* the mail host is resolved and connected to
|
||||||
|
* the newest backup, with its age and size
|
||||||
|
* free disk, which is the one that ends everything at once
|
||||||
|
* every setting `.env.example` documents that the container does not have
|
||||||
|
|
||||||
|
**It changes nothing.** No buttons, no fixes, no restarts — a page that answers
|
||||||
|
questions. That is deliberate: a diagnostic screen that can also act is a screen
|
||||||
|
somebody uses to act without reading, and the actions here are the ones with the
|
||||||
|
longest reach on the box.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import smtplib
|
||||||
|
import socket
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from flask import Blueprint, current_app, render_template
|
||||||
|
|
||||||
|
from . import gitea, mail, uploads
|
||||||
|
from .db import get_db
|
||||||
|
from .security import superadmin_required
|
||||||
|
|
||||||
|
bp = Blueprint("status", __name__)
|
||||||
|
|
||||||
|
# Where deploy-board.sh puts them. Read-only, and missing is an answer.
|
||||||
|
BACKUP_DIR = "/srv/board/backups"
|
||||||
|
|
||||||
|
# Settings whose absence turns a feature off rather than breaking the app. The
|
||||||
|
# names are the ones in infra/board/.env.example; the sentence is what stops
|
||||||
|
# working. Checked against os.environ because the container cannot read
|
||||||
|
# /srv/board/.env — compose substitutes it in and the file never arrives.
|
||||||
|
EXPECTED = (
|
||||||
|
("BOARD_SECRET_KEY", "las sesiones (sin esto la app no arranca)"),
|
||||||
|
("CONTENT_TOKEN", "publicar en el sitio: el editor y la marca"),
|
||||||
|
("MAIL_HOST", "invitaciones y recuperar contraseña"),
|
||||||
|
("MAIL_USER", "autenticarse en el servidor de correo"),
|
||||||
|
("MAIL_PASSWORD", "autenticarse en el servidor de correo"),
|
||||||
|
("BOARD_OWNER", "sembrar al superadministrador en el primer arranque"),
|
||||||
|
("GITEA_URL", "hablar con el servidor de git"),
|
||||||
|
("CONTENT_REPO", "saber en qué repositorio se publica"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _ok(label, detail=""):
|
||||||
|
return {"state": "ok", "label": label, "detail": detail}
|
||||||
|
|
||||||
|
|
||||||
|
def _warn(label, detail=""):
|
||||||
|
return {"state": "warn", "label": label, "detail": detail}
|
||||||
|
|
||||||
|
|
||||||
|
def _bad(label, detail=""):
|
||||||
|
return {"state": "bad", "label": label, "detail": detail}
|
||||||
|
|
||||||
|
|
||||||
|
def _content_token() -> dict:
|
||||||
|
"""Not "is it set" — "does it work".
|
||||||
|
|
||||||
|
A token with `admin` scope and no `repository` scope is present, non-empty,
|
||||||
|
and cannot write a single file; that exact configuration broke publishing
|
||||||
|
for three phases while every check anybody thought to run said it was fine.
|
||||||
|
So this one reads the content directory through the API and reports what
|
||||||
|
came back.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
token = gitea.content_token()
|
||||||
|
except gitea.GiteaError as exc:
|
||||||
|
return _bad("No hay token para publicar", str(exc))
|
||||||
|
|
||||||
|
which = "CONTENT_TOKEN" if os.environ.get("CONTENT_TOKEN") else "GITEA_ADMIN_TOKEN"
|
||||||
|
try:
|
||||||
|
gitea.list_directory("content/post", token)
|
||||||
|
except gitea.GiteaError as exc:
|
||||||
|
return _bad(f"El token ({which}) no puede leer el repositorio", str(exc))
|
||||||
|
except OSError as exc:
|
||||||
|
return _warn("No se pudo contactar con el servidor de git", str(exc))
|
||||||
|
|
||||||
|
if which == "GITEA_ADMIN_TOKEN":
|
||||||
|
return _warn(
|
||||||
|
"Publicando con el token de administración",
|
||||||
|
"Funciona, pero ese token puede modificar cualquier cuenta del "
|
||||||
|
"servidor de git. Crea uno con permiso de repositorio y ponlo en "
|
||||||
|
"CONTENT_TOKEN.")
|
||||||
|
return _ok("El token de publicación funciona", f"{which}, con acceso de lectura")
|
||||||
|
|
||||||
|
|
||||||
|
def _mail() -> dict:
|
||||||
|
if not mail.configured():
|
||||||
|
return _warn("Sin correo saliente",
|
||||||
|
"Nadie puede ser invitado ni recuperar su contraseña.")
|
||||||
|
host = current_app.config["MAIL_HOST"]
|
||||||
|
port = int(current_app.config["MAIL_PORT"] or 587)
|
||||||
|
try:
|
||||||
|
with smtplib.SMTP(host, port, timeout=5) as server:
|
||||||
|
server.ehlo()
|
||||||
|
except (OSError, smtplib.SMTPException) as exc:
|
||||||
|
return _bad(f"{host}:{port} no responde", str(exc))
|
||||||
|
return _ok(f"{host}:{port} responde", "La conexión se abre; no se envía nada.")
|
||||||
|
|
||||||
|
|
||||||
|
def _backups() -> dict:
|
||||||
|
folder = Path(BACKUP_DIR)
|
||||||
|
if not folder.is_dir():
|
||||||
|
return _warn("No hay carpeta de copias", f"{BACKUP_DIR} no existe.")
|
||||||
|
files = sorted(folder.glob("board-*.db.gz"), key=lambda f: f.stat().st_mtime)
|
||||||
|
if not files:
|
||||||
|
return _bad("Ninguna copia de seguridad", f"{BACKUP_DIR} está vacía.")
|
||||||
|
newest = files[-1]
|
||||||
|
age = datetime.now(timezone.utc) - datetime.fromtimestamp(
|
||||||
|
newest.stat().st_mtime, timezone.utc)
|
||||||
|
size = newest.stat().st_size // 1024
|
||||||
|
detail = f"{newest.name}, {size} KB, {len(files)} en total"
|
||||||
|
if age.days >= 2:
|
||||||
|
return _warn(f"La copia más reciente tiene {age.days} días", detail)
|
||||||
|
return _ok("Copia reciente", detail)
|
||||||
|
|
||||||
|
|
||||||
|
def _disk() -> dict:
|
||||||
|
"""The one that ends everything at once, and silently: SQLite cannot write,
|
||||||
|
uploads fail, and the log that would say so cannot be written either."""
|
||||||
|
# Through `uploads.directory()`, which creates it: asking statvfs about a
|
||||||
|
# path that does not exist raises, and "the uploads folder has not been made
|
||||||
|
# yet" is not a disk problem.
|
||||||
|
usage = shutil.disk_usage(uploads.directory())
|
||||||
|
free_mb = usage.free // (1024 * 1024)
|
||||||
|
detail = f"{free_mb} MB libres de {usage.total // (1024 * 1024)} MB"
|
||||||
|
if free_mb < 200:
|
||||||
|
return _bad("Queda muy poco disco", detail)
|
||||||
|
if free_mb < 1000:
|
||||||
|
return _warn("Queda poco disco", detail)
|
||||||
|
return _ok("Disco suficiente", detail)
|
||||||
|
|
||||||
|
|
||||||
|
def _settings() -> dict:
|
||||||
|
missing = [(name, why) for name, why in EXPECTED if not os.environ.get(name)]
|
||||||
|
if not missing:
|
||||||
|
return _ok("Todos los ajustes esperados están puestos")
|
||||||
|
return _warn(
|
||||||
|
f"{len(missing)} ajuste{'s' if len(missing) > 1 else ''} sin poner",
|
||||||
|
"; ".join(f"{name} — {why}" for name, why in missing))
|
||||||
|
|
||||||
|
|
||||||
|
def _counts() -> dict:
|
||||||
|
db = get_db()
|
||||||
|
one = lambda sql: db.execute(sql).fetchone()[0] # noqa: E731
|
||||||
|
return {
|
||||||
|
"members": one("SELECT COUNT(*) FROM members WHERE role != 'tombstone'"),
|
||||||
|
"admins": one("SELECT COUNT(*) FROM members WHERE role IN "
|
||||||
|
"('superadmin', 'owner', 'admin', 'moderator')"),
|
||||||
|
# `role != 'tombstone'` because the row erased members are reassigned
|
||||||
|
# to is inactive by construction and is not a suspended person.
|
||||||
|
"suspended": one("SELECT COUNT(*) FROM members "
|
||||||
|
"WHERE active = 0 AND role != 'tombstone'"),
|
||||||
|
"threads": one("SELECT COUNT(*) FROM threads WHERE deleted_at IS NULL"),
|
||||||
|
"pending": one("SELECT COUNT(*) FROM submissions WHERE state = 'pending'"),
|
||||||
|
"events": one("SELECT COUNT(*) FROM events"),
|
||||||
|
"posts": one("SELECT COUNT(*) FROM content_cache WHERE generated = 0"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@bp.route("/gestion/estado")
|
||||||
|
@superadmin_required
|
||||||
|
def index():
|
||||||
|
checks = [
|
||||||
|
("Publicar en el sitio", _content_token()),
|
||||||
|
("Correo saliente", _mail()),
|
||||||
|
("Copias de seguridad", _backups()),
|
||||||
|
("Disco", _disk()),
|
||||||
|
("Ajustes del contenedor", _settings()),
|
||||||
|
]
|
||||||
|
return render_template("status.html", checks=checks, counts=_counts(),
|
||||||
|
worst=min((c[1]["state"] for c in checks),
|
||||||
|
key=["bad", "warn", "ok"].index))
|
||||||
@ -30,10 +30,10 @@ from datetime import date as date_type
|
|||||||
from flask import (Blueprint, abort, current_app, flash, g, redirect,
|
from flask import (Blueprint, abort, current_app, flash, g, redirect,
|
||||||
render_template, request, send_from_directory, url_for)
|
render_template, request, send_from_directory, url_for)
|
||||||
|
|
||||||
from . import content, gitea, uploads
|
from . import activity, content, gitea, uploads
|
||||||
from .db import get_db
|
from .db import get_db
|
||||||
from .render import excerpt, to_html
|
from .render import excerpt, to_html
|
||||||
from .security import login_required, moderator_required
|
from .security import is_at_least, login_required, moderator_required
|
||||||
|
|
||||||
bp = Blueprint("submissions", __name__)
|
bp = Blueprint("submissions", __name__)
|
||||||
|
|
||||||
@ -54,7 +54,7 @@ STATE_LABELS = {
|
|||||||
|
|
||||||
def may_moderate(member=None) -> bool:
|
def may_moderate(member=None) -> bool:
|
||||||
member = member or g.member
|
member = member or g.member
|
||||||
return member is not None and member["role"] in ("owner", "admin", "moderator")
|
return member is not None and is_at_least(member["role"], "moderator")
|
||||||
|
|
||||||
|
|
||||||
def pending_count() -> int:
|
def pending_count() -> int:
|
||||||
@ -360,6 +360,7 @@ def approve(submission_id: int):
|
|||||||
# in one place, and no orphan in /data/uploads that nothing will ever serve.
|
# in one place, and no orphan in /data/uploads that nothing will ever serve.
|
||||||
if row["photo_name"]:
|
if row["photo_name"]:
|
||||||
uploads.remove(row["photo_name"])
|
uploads.remove(row["photo_name"])
|
||||||
|
activity.log("submission.approved", row["title"], f"de {row['author']}")
|
||||||
flash(f"Publicado «{row['title']}». La traducción tarda un par de minutos.", "ok")
|
flash(f"Publicado «{row['title']}». La traducción tarda un par de minutos.", "ok")
|
||||||
return redirect(url_for("submissions.index"))
|
return redirect(url_for("submissions.index"))
|
||||||
|
|
||||||
@ -387,6 +388,7 @@ def reject(submission_id: int):
|
|||||||
WHERE id = ?""",
|
WHERE id = ?""",
|
||||||
(note, g.member["id"], submission_id),
|
(note, g.member["id"], submission_id),
|
||||||
)
|
)
|
||||||
|
activity.log("submission.rejected", row["title"], f"de {row['author']}")
|
||||||
flash("Devuelto al autor con tu motivo.", "ok")
|
flash("Devuelto al autor con tu motivo.", "ok")
|
||||||
return redirect(url_for("submissions.index"))
|
return redirect(url_for("submissions.index"))
|
||||||
|
|
||||||
|
|||||||
51
apps/board/templates/activity.html
Normal file
51
apps/board/templates/activity.html
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
{# Gestión → Registro de actividad. Read-only by construction: there is nothing
|
||||||
|
here to press, because an audit trail you can edit is not one. #}
|
||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Registro{% endblock %}
|
||||||
|
|
||||||
|
{% block main %}
|
||||||
|
<div class="feed-head">
|
||||||
|
<h1>Registro de actividad</h1>
|
||||||
|
<a class="linkish" href="{{ url_for('home.gestion') }}">Volver a Gestión</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="muted">
|
||||||
|
Lo que se ha hecho que cambia quién puede hacer qué, o qué ve el público. No
|
||||||
|
están las visitas ni los inicios de sesión correctos: un registro que lo
|
||||||
|
apunta todo es un registro que nadie lee.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{% if not rows %}
|
||||||
|
<p class="muted">Todavía no hay nada apuntado.</p>
|
||||||
|
{% else %}
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th>Cuándo</th><th>Quién</th><th>Qué</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for row in rows %}
|
||||||
|
<tr>
|
||||||
|
<td class="mono small">{{ row.at }}</td>
|
||||||
|
<td>
|
||||||
|
{# A name that is simply gone, rather than a tombstone: the row stays
|
||||||
|
when somebody is erased and the name does not, which is the whole
|
||||||
|
arrangement. #}
|
||||||
|
{{ row.actor or 'Alguien que ya no está' }}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{{ row.sentence }}
|
||||||
|
{% if row.detail %}<span class="muted small"> · {{ row.detail }}</span>{% endif %}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<div class="actions">
|
||||||
|
{% if page > 0 %}
|
||||||
|
<a class="linkish" href="{{ url_for('activity.index', p=page - 1) }}">← Más reciente</a>
|
||||||
|
{% endif %}
|
||||||
|
{% if more %}
|
||||||
|
<a class="linkish" href="{{ url_for('activity.index', p=page + 1) }}">Más antiguo →</a>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
@ -80,7 +80,7 @@
|
|||||||
<a href="{{ url_for('submissions.index') }}">Publicaciones{% set waiting = pending_review() %}{% if waiting %} <span class="tag">{{ waiting }}</span>{% endif %}</a>
|
<a href="{{ url_for('submissions.index') }}">Publicaciones{% set waiting = pending_review() %}{% if waiting %} <span class="tag">{{ waiting }}</span>{% endif %}</a>
|
||||||
</li>
|
</li>
|
||||||
<li><a href="{{ url_for('events.month') }}">Calendario</a></li>
|
<li><a href="{{ url_for('events.month') }}">Calendario</a></li>
|
||||||
{% if g.member.role in ('owner', 'admin') %}
|
{% if is_at_least(g.member.role, 'admin') %}
|
||||||
<li><a href="{{ url_for('home.gestion') }}">Gestión</a></li>
|
<li><a href="{{ url_for('home.gestion') }}">Gestión</a></li>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@ -108,6 +108,97 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
<input id="favicon" name="favicon" type="file" accept="image/png">
|
<input id="favicon" name="favicon" type="file" accept="image/png">
|
||||||
|
|
||||||
|
<h2 class="section-title">Tipografía</h2>
|
||||||
|
<p class="muted small">
|
||||||
|
Las cuatro primeras ya están en el ordenador de quien lee: no se descarga
|
||||||
|
nada de ningún sitio. Eso es a propósito — una hoja de estilos que pide una
|
||||||
|
fuente a Google le cuenta a Google la dirección IP de todo el que entra, y
|
||||||
|
eso no se puede consentir en nombre de quien visita la página.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="choices">
|
||||||
|
{% for key, (label, stack) in typefaces.items() %}
|
||||||
|
<label class="choice">
|
||||||
|
<input type="radio" name="typeface" value="{{ key }}"
|
||||||
|
{{ 'checked' if state.typeface == key }}>
|
||||||
|
{# The class, not a style attribute: `default-src 'self'` covers
|
||||||
|
style-src, so an inline style on this label would be dropped and
|
||||||
|
every option would look identical. The four classes are in
|
||||||
|
board.css beside the form rules. #}
|
||||||
|
<span class="face face--{{ key }}">{{ label }}</span>
|
||||||
|
</label>
|
||||||
|
{% endfor %}
|
||||||
|
<label class="choice">
|
||||||
|
<input type="radio" name="typeface" value="propia"
|
||||||
|
{{ 'checked' if state.typeface == 'propia' }}>
|
||||||
|
Propia (subida aquí)
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if state.font_name %}
|
||||||
|
<p class="muted small">Ya hay una tipografía subida. Si eliges otra, la sustituye.</p>
|
||||||
|
{% endif %}
|
||||||
|
<label for="font">Archivo .woff2 <span class="muted small">(sólo para «Propia»)</span></label>
|
||||||
|
<input id="font" name="font" type="file" accept=".woff2,font/woff2">
|
||||||
|
|
||||||
|
{# Closed by default and one line tall, as asked. Everything in it is a way
|
||||||
|
this goes wrong in practice rather than in theory. #}
|
||||||
|
<details class="brand-warning">
|
||||||
|
<summary>Antes de subir una tipografía, lee esto</summary>
|
||||||
|
|
||||||
|
<p><strong>Lo que hace una fuente mala.</strong> Una tipografía sin
|
||||||
|
<span class="mono">ñ á ü ç ã</span> dibuja esas letras con otra distinta, así
|
||||||
|
que el español y el portugués salen visiblemente remendados — y nadie te
|
||||||
|
avisa. Un archivo de 2 MB retrasa cada página en un móvil. Una fuente de
|
||||||
|
titulares puesta a 16px no se lee.</p>
|
||||||
|
|
||||||
|
<p><strong>Cómo hacerlo bien.</strong> Sube un solo archivo, el peso normal:
|
||||||
|
la negrita y la cursiva las fabrica el navegador a partir de él, lo cual
|
||||||
|
está bien para un sitio con logotipo y mal para textos largos. Subconjunta
|
||||||
|
la fuente a latín y latín extendido-A. Que no pase de unos 100 KB. Sólo
|
||||||
|
<span class="mono">.woff2</span>: es el formato de la web, lo entienden
|
||||||
|
todos los navegadores y es el que este formulario comprueba por su firma,
|
||||||
|
no por el nombre del archivo. Antes de guardar, mira cómo quedan
|
||||||
|
<span class="mono">ñ á ü ç ã</span> en la vista previa de arriba.</p>
|
||||||
|
|
||||||
|
<p><strong>La licencia, que es lo único de aquí que cuesta dinero.</strong>
|
||||||
|
Una tipografía es software, y una licencia de escritorio no es una licencia
|
||||||
|
web: servir desde tu propio servidor una fuente que compraste para el
|
||||||
|
ordenador suele incumplirla, y esa responsabilidad viaja con la plataforma
|
||||||
|
a cada organización donde la instales. Busca
|
||||||
|
<strong>SIL OFL</strong> o <strong>Apache 2.0</strong>: las dos permiten
|
||||||
|
alojarla uno mismo y redistribuirla.</p>
|
||||||
|
|
||||||
|
<p><strong>Dónde buscarlas sin riesgo.</strong>
|
||||||
|
<a href="https://fonts.google.com/" rel="nofollow noopener">Google Fonts</a>
|
||||||
|
(descargándolas, no enlazándolas, por lo del párrafo primero),
|
||||||
|
<a href="https://fontsource.org/" rel="nofollow noopener">Fontsource</a>
|
||||||
|
(las mismas familias ya empaquetadas en <span class="mono">.woff2</span>),
|
||||||
|
<a href="https://www.fontsquirrel.com/" rel="nofollow noopener">Font Squirrel</a>,
|
||||||
|
<a href="https://www.theleagueofmoveabletype.com/" rel="nofollow noopener">The League of Moveable Type</a>,
|
||||||
|
<a href="https://velvetyne.fr/" rel="nofollow noopener">Velvetyne</a>,
|
||||||
|
<a href="https://open-foundry.com/" rel="nofollow noopener">Open Foundry</a> y
|
||||||
|
<a href="https://usemodify.com/" rel="nofollow noopener">Use & Modify</a>.
|
||||||
|
Comprueba la licencia del archivo que te has descargado, no la de la página
|
||||||
|
desde la que llegaste a él.</p>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<h2 class="section-title">Esquinas</h2>
|
||||||
|
<p class="muted small">
|
||||||
|
Lo redondeadas que son las tarjetas, los botones y las fotos. Un solo ajuste
|
||||||
|
para todo: un sitio con tarjetas redondas y botones cuadrados parece dos
|
||||||
|
sitios.
|
||||||
|
</p>
|
||||||
|
<div class="choices">
|
||||||
|
{% for key, (label, values) in roundness.items() %}
|
||||||
|
<label class="choice">
|
||||||
|
<input type="radio" name="roundness" value="{{ key }}"
|
||||||
|
{{ 'checked' if state.roundness == key }}>
|
||||||
|
{{ label }}
|
||||||
|
</label>
|
||||||
|
{% endfor %}
|
||||||
|
</div>
|
||||||
|
|
||||||
<details class="brand-advanced">
|
<details class="brand-advanced">
|
||||||
<summary>Avanzado</summary>
|
<summary>Avanzado</summary>
|
||||||
|
|
||||||
|
|||||||
@ -53,6 +53,18 @@
|
|||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel__head">
|
||||||
|
<h2>Biblioteca de medios</h2>
|
||||||
|
<a class="linkish" href="{{ url_for('media.index') }}">Abrir</a>
|
||||||
|
</div>
|
||||||
|
<p class="muted small">
|
||||||
|
Todas las imágenes del sitio público y qué artículo usa cada una. Las que
|
||||||
|
no usa nadie —de artículos que se borraron— se pueden quitar desde ahí.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{% if g.member.role == 'superadmin' %}
|
||||||
<section class="panel">
|
<section class="panel">
|
||||||
<div class="panel__head">
|
<div class="panel__head">
|
||||||
<h2>Marca</h2>
|
<h2>Marca</h2>
|
||||||
@ -68,6 +80,43 @@
|
|||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel__head">
|
||||||
|
<h2>Identidad</h2>
|
||||||
|
<a class="linkish" href="{{ url_for('identity.edit') }}">Abrir</a>
|
||||||
|
</div>
|
||||||
|
{% set site = identity() %}{% if site.updated_at and not site.published_at %}
|
||||||
|
<p class="panel__row">Hay cambios guardados que no han llegado al sitio público.</p>
|
||||||
|
{% endif %}
|
||||||
|
<p class="muted small">
|
||||||
|
El nombre y el lema en los tres idiomas, los perfiles de la asociación en
|
||||||
|
otros sitios, el contacto y el pie de página.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel__head">
|
||||||
|
<h2>Estado del sistema</h2>
|
||||||
|
<a class="linkish" href="{{ url_for('status.index') }}">Abrir</a>
|
||||||
|
</div>
|
||||||
|
<p class="muted small">
|
||||||
|
Si el token para publicar funciona de verdad, si el correo sale, cuándo fue
|
||||||
|
la última copia de seguridad y cuánto disco queda. No cambia nada: responde.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel__head">
|
||||||
|
<h2>Registro de actividad</h2>
|
||||||
|
<a class="linkish" href="{{ url_for('activity.index') }}">Abrir</a>
|
||||||
|
</div>
|
||||||
|
<p class="muted small">
|
||||||
|
Quién cambió un rol, aprobó una publicación, tocó el aspecto del sitio o
|
||||||
|
eliminó a alguien.
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
{% if counts.pending %}
|
{% if counts.pending %}
|
||||||
<section class="panel panel--attention">
|
<section class="panel panel--attention">
|
||||||
<div class="panel__head">
|
<div class="panel__head">
|
||||||
|
|||||||
112
apps/board/templates/identity_form.html
Normal file
112
apps/board/templates/identity_form.html
Normal file
@ -0,0 +1,112 @@
|
|||||||
|
{# Gestión → Identidad: what the site is called and where to find it.
|
||||||
|
|
||||||
|
Everything here used to be in config.yaml, which meant it could only be
|
||||||
|
changed by somebody with the repository. The fields show their current value
|
||||||
|
as a placeholder rather than as a value, deliberately: a form prefilled with
|
||||||
|
the fallback saves the fallback the first time anybody presses the button,
|
||||||
|
and the default is frozen from then on. #}
|
||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Identidad{% endblock %}
|
||||||
|
|
||||||
|
{% block main %}
|
||||||
|
<div class="feed-head">
|
||||||
|
<h1>Identidad</h1>
|
||||||
|
<a class="linkish" href="{{ url_for('home.gestion') }}">Volver a Gestión</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="muted">
|
||||||
|
Cómo se llama el sitio, qué dice que es y dónde encontrarlo. Lo de aquí
|
||||||
|
alimenta también los datos estructurados: es lo que lee un buscador —o una IA
|
||||||
|
que responde preguntas— para saber que esta asociación y esas cuentas son el
|
||||||
|
mismo cuerpo.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{% if state.updated_at and not state.published_at %}
|
||||||
|
<section class="panel panel--attention">
|
||||||
|
<div class="panel__head"><h2>Pendiente de publicar</h2></div>
|
||||||
|
<p class="panel__row">
|
||||||
|
Guardado aquí, pero no ha llegado al sitio público: no se pudo contactar
|
||||||
|
con el servidor de git la última vez.
|
||||||
|
</p>
|
||||||
|
<form method="post" action="{{ url_for('identity.publish') }}">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<button class="btn" type="submit">Reintentar publicar</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
<form class="card" method="post" action="{{ url_for('identity.edit') }}">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
|
||||||
|
<h2 class="section-title">Nombre y lema</h2>
|
||||||
|
<p class="muted small">
|
||||||
|
Uno por idioma. El lema es la frase que sale al compartir un enlace, la que
|
||||||
|
describe al sitio en los buscadores y la primera línea de
|
||||||
|
<span class="mono">llms.txt</span>. Déjalo vacío para no cambiar lo que hay.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{% for code, label, _name, _tagline in languages %}
|
||||||
|
<fieldset class="fieldset">
|
||||||
|
<legend>{{ label }}</legend>
|
||||||
|
<label for="name-{{ code }}">Nombre</label>
|
||||||
|
<input id="name-{{ code }}" name="name-{{ code }}" type="text" maxlength="80"
|
||||||
|
value="{{ state.languages[code].stored_name }}"
|
||||||
|
placeholder="{{ state.languages[code].name }}">
|
||||||
|
|
||||||
|
<label for="tagline-{{ code }}">Lema</label>
|
||||||
|
<textarea id="tagline-{{ code }}" name="tagline-{{ code }}" rows="2"
|
||||||
|
maxlength="300"
|
||||||
|
placeholder="{{ state.languages[code].tagline }}">{{ state.languages[code].stored_tagline }}</textarea>
|
||||||
|
</fieldset>
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
<h2 class="section-title">Perfiles</h2>
|
||||||
|
<p class="muted small">
|
||||||
|
Las cuentas de la asociación en otros sitios. Salen en el pie de página y
|
||||||
|
como <span class="mono">sameAs</span> en los datos estructurados, que es
|
||||||
|
como un buscador sabe que esa cuenta de Instagram y esta web son lo mismo.
|
||||||
|
</p>
|
||||||
|
{% for key, label, placeholder in networks %}
|
||||||
|
<label for="social-{{ key }}">{{ label }}</label>
|
||||||
|
<input id="social-{{ key }}" name="social-{{ key }}" type="url" maxlength="300"
|
||||||
|
value="{{ state.social[key] }}" placeholder="{{ placeholder }}">
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
<h2 class="section-title">Contacto y lugar</h2>
|
||||||
|
<p class="muted small">
|
||||||
|
Público, y pensado para que lo lea una persona tanto como un buscador: una
|
||||||
|
dirección y una ciudad son lo que pone a una asociación en un resultado
|
||||||
|
local y no sólo en uno web.
|
||||||
|
</p>
|
||||||
|
<label for="email">Correo público</label>
|
||||||
|
<input id="email" name="email" type="email" maxlength="120" value="{{ state.email }}"
|
||||||
|
placeholder="hola@vienalatina.com">
|
||||||
|
|
||||||
|
<label for="phone">Teléfono <span class="muted small">(opcional)</span></label>
|
||||||
|
<input id="phone" name="phone" type="text" maxlength="40" value="{{ state.phone }}">
|
||||||
|
|
||||||
|
<label for="city">Ciudad</label>
|
||||||
|
<input id="city" name="city" type="text" maxlength="80" value="{{ state.city }}"
|
||||||
|
placeholder="Wien">
|
||||||
|
|
||||||
|
<label for="street">Calle <span class="muted small">(opcional)</span></label>
|
||||||
|
<input id="street" name="street" type="text" maxlength="160" value="{{ state.street }}">
|
||||||
|
|
||||||
|
<h2 class="section-title">Al compartir, y el pie</h2>
|
||||||
|
<label for="share_image">Imagen por defecto <span class="muted small">(opcional)</span></label>
|
||||||
|
<input id="share_image" name="share_image" type="text" maxlength="200"
|
||||||
|
value="{{ state.share_image }}" placeholder="/uploads/algo.png">
|
||||||
|
<p class="muted small">
|
||||||
|
La que sale al compartir un artículo que no tiene foto propia. Si la dejas
|
||||||
|
vacía se usa el logotipo, que casi siempre es lo que quieres: esto es para
|
||||||
|
cuando prefieres otra cosa —una foto de la ciudad, por ejemplo.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<label for="footer_text">Texto del pie <span class="muted small">(opcional)</span></label>
|
||||||
|
<input id="footer_text" name="footer_text" type="text" maxlength="200"
|
||||||
|
value="{{ state.footer_text }}">
|
||||||
|
<p class="muted small">Si lo dejas vacío, el pie pone el nombre y el año.</p>
|
||||||
|
|
||||||
|
<button class="btn" type="submit">Guardar</button>
|
||||||
|
</form>
|
||||||
|
{% endblock %}
|
||||||
47
apps/board/templates/media.html
Normal file
47
apps/board/templates/media.html
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
{# Gestión → Biblioteca de medios.
|
||||||
|
|
||||||
|
Orphans first, because they are the only rows anybody has to act on: a
|
||||||
|
listing sorted by name buries them among the pictures doing their job, which
|
||||||
|
is how they went unnoticed for the life of the site. #}
|
||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Medios{% endblock %}
|
||||||
|
|
||||||
|
{% block main %}
|
||||||
|
<div class="feed-head">
|
||||||
|
<h1>Biblioteca de medios</h1>
|
||||||
|
<a class="linkish" href="{{ url_for('home.gestion') }}">Volver a Gestión</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="muted">
|
||||||
|
Todas las imágenes que lleva el sitio público, y qué artículo usa cada una.
|
||||||
|
{% if orphans %}
|
||||||
|
<strong>{{ orphans }} no la usa nadie</strong>: se subieron con un artículo que
|
||||||
|
luego se borró, y siguen ahí ocupando sitio.
|
||||||
|
{% endif %}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{% if not items %}
|
||||||
|
<p class="muted">No hay imágenes todavía.</p>
|
||||||
|
{% else %}
|
||||||
|
<ul class="media-grid">
|
||||||
|
{% for item in items %}
|
||||||
|
<li class="media-item {{ 'media-item--orphan' if not item.posts }}">
|
||||||
|
<img src="{{ item.url }}" alt="" loading="lazy">
|
||||||
|
<p class="mono small">{{ item.name }}</p>
|
||||||
|
<p class="muted small">{{ item.size }} KB</p>
|
||||||
|
{% if item.posts %}
|
||||||
|
<p class="muted small">{{ item.posts|join(', ') }}</p>
|
||||||
|
{% else %}
|
||||||
|
<p class="muted small">No la usa ningún artículo.</p>
|
||||||
|
<form method="post" action="{{ url_for('media.delete', name=item.name) }}"
|
||||||
|
data-confirm="Se borrará {{ item.name }} del repositorio. ¿Seguro?">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<input type="hidden" name="sha" value="{{ item.sha }}">
|
||||||
|
<button class="linkish linkish--danger" type="submit">Borrar</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
</li>
|
||||||
|
{% endfor %}
|
||||||
|
</ul>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock %}
|
||||||
@ -14,8 +14,13 @@
|
|||||||
{% block title %}{{ member.display_name }}{% endblock %}
|
{% block title %}{{ member.display_name }}{% endblock %}
|
||||||
|
|
||||||
{% set me = g.member %}
|
{% set me = g.member %}
|
||||||
{% set is_owner = me.role == 'owner' %}
|
{# The template mirrors the predicates in members.py rather than restating
|
||||||
{% set is_admin = me.role in ('owner', 'admin') %}
|
them: `can_assign` is the same list the handler will accept, so the picker
|
||||||
|
cannot offer a role that comes back 403. #}
|
||||||
|
{% set is_super = me.role == 'superadmin' %}
|
||||||
|
{% set is_chair = me.role in ('superadmin', 'owner') %}
|
||||||
|
{% set is_admin = is_at_least(me.role, 'admin') %}
|
||||||
|
{% set can_assign = assignable_roles(me.role) %}
|
||||||
|
|
||||||
{% block main %}
|
{% block main %}
|
||||||
<div class="feed-head">
|
<div class="feed-head">
|
||||||
@ -139,7 +144,7 @@
|
|||||||
{% endif %}
|
{% endif %}
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
{% if is_admin and member.role != 'owner' and not is_me %}
|
{% if is_admin and member.role not in ('superadmin', 'owner') and not is_me %}
|
||||||
{# Moved here from the directory cards. A <details>, not a script: the CSP has
|
{# Moved here from the directory cards. A <details>, not a script: the CSP has
|
||||||
no 'unsafe-inline'. Every button is still checked in its handler — this block
|
no 'unsafe-inline'. Every button is still checked in its handler — this block
|
||||||
being hidden from a moderator is a courtesy, not the rule. #}
|
being hidden from a moderator is a courtesy, not the rule. #}
|
||||||
@ -164,36 +169,48 @@
|
|||||||
</form>
|
</form>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
{% if is_owner or member.role != 'admin' %}
|
{% if member.role in can_assign or member.role not in ('admin',) %}
|
||||||
<form class="inline-form" method="post"
|
<form class="inline-form" method="post"
|
||||||
action="{{ url_for('members.set_role', member_id=member.id) }}">
|
action="{{ url_for('members.set_role', member_id=member.id) }}">
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
<label class="sr-only" for="role">Rol de {{ member.display_name }}</label>
|
<label class="sr-only" for="role">Rol de {{ member.display_name }}</label>
|
||||||
<select id="role" name="role">
|
<select id="role" name="role">
|
||||||
<option value="user" {{ 'selected' if member.role == 'user' }}>Miembro</option>
|
{% for role in can_assign %}
|
||||||
<option value="moderator" {{ 'selected' if member.role == 'moderator' }}>Moderador</option>
|
<option value="{{ role }}" {{ 'selected' if member.role == role }}>{{ labels[role] }}</option>
|
||||||
{% if is_owner %}
|
{% endfor %}
|
||||||
<option value="admin" {{ 'selected' if member.role == 'admin' }}>Administrador</option>
|
|
||||||
{% endif %}
|
|
||||||
</select>
|
</select>
|
||||||
<button class="linkish" type="submit">Cambiar rol</button>
|
<button class="linkish" type="submit">Cambiar rol</button>
|
||||||
</form>
|
</form>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
{% if is_owner %}
|
{% if is_chair and member.active %}
|
||||||
{% if member.role == 'admin' and member.active %}
|
{# Naming the responsable: the association's chair. The superadministrator
|
||||||
<form method="post" action="{{ url_for('members.transfer', member_id=member.id) }}"
|
can fill it when it is empty — a fresh install has nobody in it — and
|
||||||
data-confirm="Vas a dejar de ser el responsable y {{ member.display_name }} pasará a serlo. ¿Seguro?">
|
the responsable can hand it on. #}
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
<form method="post" action="{{ url_for('members.transfer', member_id=member.id) }}"
|
||||||
<button class="linkish" type="submit">Transferir titularidad</button>
|
data-confirm="{{ member.display_name }} pasará a ser el responsable de la asociación. ¿Seguro?">
|
||||||
</form>
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
{% endif %}
|
<button class="linkish" type="submit">Nombrar responsable</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
<form method="post" action="{{ url_for('members.erase', member_id=member.id) }}"
|
{% if is_super and member.role == 'admin' and member.active %}
|
||||||
data-confirm="Se borrarán sus datos personales. Sus mensajes quedarán como «Miembro eliminado». ¿Seguro?">
|
{# Handing the platform on. Its own button, and its own sentence, because
|
||||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
it is irreversible from this side: the moment it commits you are an
|
||||||
<button class="linkish linkish--danger" type="submit">Eliminar</button>
|
administrator and cannot take it back. #}
|
||||||
</form>
|
<form method="post" action="{{ url_for('members.transfer_platform', member_id=member.id) }}"
|
||||||
|
data-confirm="{{ member.display_name }} pasará a ser el superadministrador y tú pasarás a ser administrador. No podrás deshacerlo tú mismo. ¿Seguro?">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<button class="linkish linkish--danger" type="submit">Entregar la plataforma</button>
|
||||||
|
</form>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% if is_chair %}
|
||||||
|
<form method="post" action="{{ url_for('members.erase', member_id=member.id) }}"
|
||||||
|
data-confirm="Se borrarán sus datos personales. Sus mensajes quedarán como «Miembro eliminado». ¿Seguro?">
|
||||||
|
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||||
|
<button class="linkish linkish--danger" type="submit">Eliminar</button>
|
||||||
|
</form>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
{% if member.email %}<p class="muted small">{{ member.email }}</p>{% endif %}
|
{% if member.email %}<p class="muted small">{{ member.email }}</p>{% endif %}
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
{% block title %}Miembros{% endblock %}
|
{% block title %}Miembros{% endblock %}
|
||||||
|
|
||||||
{% set me = g.member %}
|
{% set me = g.member %}
|
||||||
{% set is_admin = me.role in ('owner', 'admin') %}
|
{% set is_admin = is_at_least(me.role, 'admin') %}
|
||||||
|
|
||||||
{% block main %}
|
{% block main %}
|
||||||
<div class="feed-head">
|
<div class="feed-head">
|
||||||
@ -64,10 +64,11 @@
|
|||||||
|
|
||||||
{% if is_admin %}
|
{% if is_admin %}
|
||||||
<p class="muted small">
|
<p class="muted small">
|
||||||
Hay un solo responsable. El responsable da de alta administradores; los
|
Hay un solo superadministrador y un solo responsable. El superadministrador
|
||||||
administradores dan de alta miembros y moderadores. Suspender, cambiar el rol,
|
lleva la plataforma: las cuentas de administrador, el aspecto y la identidad
|
||||||
reenviar la invitación y eliminar están en la ficha de cada persona, bajo
|
del sitio. El responsable lleva la asociación: los miembros, los moderadores
|
||||||
«Gestionar».
|
y las invitaciones. Suspender, cambiar el rol, reenviar la invitación y
|
||||||
|
eliminar están en la ficha de cada persona, bajo «Gestionar».
|
||||||
</p>
|
</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
|
|||||||
49
apps/board/templates/status.html
Normal file
49
apps/board/templates/status.html
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
{# Gestión → Estado del sistema.
|
||||||
|
|
||||||
|
Nothing on this page changes anything, deliberately: a diagnostic screen that
|
||||||
|
can also act is a screen somebody uses to act without reading, and the actions
|
||||||
|
it would offer are the ones with the longest reach on this box. #}
|
||||||
|
{% extends "base.html" %}
|
||||||
|
{% block title %}Estado{% endblock %}
|
||||||
|
|
||||||
|
{% block main %}
|
||||||
|
<div class="feed-head">
|
||||||
|
<h1>Estado del sistema</h1>
|
||||||
|
<a class="linkish" href="{{ url_for('home.gestion') }}">Volver a Gestión</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="muted">
|
||||||
|
Lo que es verdad del servidor ahora mismo, preguntado al sistema y no a un
|
||||||
|
archivo. Esta página no cambia nada: sólo responde.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{% if worst == 'ok' %}
|
||||||
|
<p class="flash flash--ok">Todo responde.</p>
|
||||||
|
{% endif %}
|
||||||
|
|
||||||
|
{% for title, check in checks %}
|
||||||
|
<section class="panel panel--{{ 'attention' if check.state != 'ok' }}">
|
||||||
|
<div class="panel__head">
|
||||||
|
<h2>{{ title }}</h2>
|
||||||
|
<span class="tag tag--{{ check.state }}">
|
||||||
|
{{ {'ok': 'Bien', 'warn': 'Atención', 'bad': 'Mal'}[check.state] }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p class="panel__row">{{ check.label }}</p>
|
||||||
|
{% if check.detail %}<p class="muted small">{{ check.detail }}</p>{% endif %}
|
||||||
|
</section>
|
||||||
|
{% endfor %}
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel__head"><h2>Cuántas cosas hay</h2></div>
|
||||||
|
<p class="panel__row">
|
||||||
|
{{ counts.members }} miembros · {{ counts.admins }} con algún cargo
|
||||||
|
{% if counts.suspended %} · {{ counts.suspended }} suspendido{{ '' if counts.suspended == 1 else 's' }}{% endif %}
|
||||||
|
</p>
|
||||||
|
<p class="panel__row">
|
||||||
|
{{ counts.posts }} artículos publicados · {{ counts.threads }} hilos en el muro ·
|
||||||
|
{{ counts.events }} eventos en el calendario
|
||||||
|
{% if counts.pending %} · {{ counts.pending }} propuesta{{ '' if counts.pending == 1 else 's' }} esperando{% endif %}
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
{% endblock %}
|
||||||
@ -65,9 +65,23 @@ def make_member(db):
|
|||||||
return _make
|
return _make
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def superadmin_id(db):
|
||||||
|
"""The account BOARD_OWNER seeds: the superadministrator, who runs the
|
||||||
|
platform and passes every check below them."""
|
||||||
|
return db.execute(
|
||||||
|
"SELECT id FROM members WHERE role = 'superadmin'").fetchone()["id"]
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def owner_id(db):
|
def owner_id(db):
|
||||||
return db.execute("SELECT id FROM members WHERE role = 'owner'").fetchone()["id"]
|
"""A responsable — the association's chair, which is empty on a fresh
|
||||||
|
install. Minted here because the two roles are deliberately different
|
||||||
|
people, and a test that means one should not reach for the other."""
|
||||||
|
return db.execute(
|
||||||
|
"""INSERT INTO members (gitea_login, display_name, email, role)
|
||||||
|
VALUES ('presidenta', 'Presidenta', 'presidenta@example.com', 'owner')"""
|
||||||
|
).lastrowid
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
|
|||||||
@ -99,10 +99,12 @@ def test_an_unreadable_pair_warns_and_a_readable_one_does_not():
|
|||||||
# --- the form -------------------------------------------------------------
|
# --- the form -------------------------------------------------------------
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def admin(make_member, sign_in):
|
def admin(superadmin_id, sign_in):
|
||||||
member_id = make_member("admina", role="admin")
|
"""The superadministrator. Named `admin` because every test below reads
|
||||||
sign_in(member_id)
|
"signed in as the person who may change this", and that person is no longer
|
||||||
return member_id
|
an administrator: the look and the identity are the platform's."""
|
||||||
|
sign_in(superadmin_id)
|
||||||
|
return superadmin_id
|
||||||
|
|
||||||
|
|
||||||
# Arguments for the test client rather than fields of the form. Separated by
|
# Arguments for the test client rather than fields of the form. Separated by
|
||||||
@ -125,8 +127,11 @@ def save(post, **fields):
|
|||||||
return post("/comunidad/gestion/marca", data, **sent)
|
return post("/comunidad/gestion/marca", data, **sent)
|
||||||
|
|
||||||
|
|
||||||
def test_only_admins_reach_it(client, post, make_member, sign_in):
|
def test_only_the_superadmin_reaches_it(client, post, make_member, sign_in):
|
||||||
for role in ("user", "moderator"):
|
"""An administrator is refused too, which is the change: the colours and the
|
||||||
|
identity belong to whoever runs the platform, not to the association's
|
||||||
|
committee."""
|
||||||
|
for role in ("user", "moderator", "admin", "owner"):
|
||||||
sign_in(make_member(f"persona-{role}", role=role))
|
sign_in(make_member(f"persona-{role}", role=role))
|
||||||
assert client.get("/comunidad/gestion/marca").status_code == 403
|
assert client.get("/comunidad/gestion/marca").status_code == 403
|
||||||
assert save(post, **{"token-brand": "#1b5e20"}).status_code == 403
|
assert save(post, **{"token-brand": "#1b5e20"}).status_code == 403
|
||||||
@ -370,18 +375,134 @@ def test_restoring_empties_the_row_and_the_disk(app, client, db, post, admin):
|
|||||||
|
|
||||||
# --- erasure --------------------------------------------------------------
|
# --- erasure --------------------------------------------------------------
|
||||||
|
|
||||||
def test_erasing_the_admin_leaves_the_brand_standing(client, db, post, owner_id,
|
def test_erasing_whoever_set_the_brand_leaves_it_standing(client, db, post, admin,
|
||||||
make_member, sign_in):
|
make_member):
|
||||||
"""The colours belong to the association, like an event in the calendar.
|
"""The colours belong to the association, like an event in the calendar.
|
||||||
An admin leaving is not a reason for the site to look like a default
|
Whoever set them leaving is not a reason for the site to look like a default
|
||||||
install again."""
|
install again.
|
||||||
admin_id = make_member("admina", role="admin")
|
|
||||||
sign_in(admin_id)
|
|
||||||
save(post, **{"token-brand": "#1b5e20"})
|
|
||||||
|
|
||||||
sign_in(owner_id)
|
The row erased is a former superadministrator who has since handed the
|
||||||
post(f"/comunidad/miembros/{admin_id}/eliminar")
|
platform on and is an admin again — which is the only way a row that set the
|
||||||
|
brand can become erasable at all, since neither chair can be erased."""
|
||||||
|
former = make_member("anterior", role="admin")
|
||||||
|
save(post, **{"token-brand": "#1b5e20"})
|
||||||
|
db.execute("UPDATE brand SET updated_by = ? WHERE id = 1", (former,))
|
||||||
|
|
||||||
|
post(f"/comunidad/miembros/{former}/eliminar")
|
||||||
|
|
||||||
row = db.execute("SELECT tokens_json, updated_by FROM brand").fetchone()
|
row = db.execute("SELECT tokens_json, updated_by FROM brand").fetchone()
|
||||||
assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"}
|
assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"}
|
||||||
assert row["updated_by"] is None
|
assert row["updated_by"] is None
|
||||||
|
|
||||||
|
|
||||||
|
# --- the typeface and the corners -----------------------------------------
|
||||||
|
|
||||||
|
WOFF2 = b"wOF2" + b"\x00" * 200
|
||||||
|
TTF = b"\x00\x01\x00\x00" + b"\x00" * 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_preset_typeface_reaches_the_stylesheet(client, post, admin):
|
||||||
|
save(post, typeface="serif")
|
||||||
|
|
||||||
|
css = client.get("/comunidad/marca.css").get_data(as_text=True)
|
||||||
|
|
||||||
|
assert "body { font-family: Georgia" in css
|
||||||
|
assert "@font-face" not in css # nothing is downloaded for a preset
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_default_typeface_writes_no_rule_at_all(client, post, admin):
|
||||||
|
"""An install that has not touched this serves what it always served."""
|
||||||
|
save(post, typeface="sans")
|
||||||
|
|
||||||
|
css = client.get("/comunidad/marca.css").get_data(as_text=True)
|
||||||
|
|
||||||
|
assert "font-family" not in css
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_font_that_is_not_a_woff2_is_refused(client, db, post, admin):
|
||||||
|
"""By its signature, not its name — the same rule every other upload here
|
||||||
|
follows. A .ttf renders fine in a browser and is two to five times the size
|
||||||
|
for the same letters."""
|
||||||
|
response = save(post, typeface="propia", font=(io.BytesIO(TTF), "bonita.woff2"),
|
||||||
|
content_type="multipart/form-data", follow_redirects=True)
|
||||||
|
|
||||||
|
assert "no es un .woff2" in response.get_data(as_text=True)
|
||||||
|
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_enormous_font_is_refused(client, db, post, admin):
|
||||||
|
big = b"wOF2" + b"\x00" * 500_000
|
||||||
|
response = save(post, typeface="propia", font=(io.BytesIO(big), "gorda.woff2"),
|
||||||
|
content_type="multipart/form-data", follow_redirects=True)
|
||||||
|
|
||||||
|
assert "Subconjunta" in response.get_data(as_text=True)
|
||||||
|
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_choosing_propia_without_a_file_is_refused(client, db, post, admin):
|
||||||
|
"""Rather than falling back silently: the site would look unchanged and the
|
||||||
|
setting would say otherwise."""
|
||||||
|
response = save(post, typeface="propia", follow_redirects=True)
|
||||||
|
|
||||||
|
assert "hay que subir un archivo" in response.get_data(as_text=True)
|
||||||
|
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_uploaded_font_is_declared_served_and_falls_back(client, db, post, admin):
|
||||||
|
save(post, typeface="propia", font=(io.BytesIO(WOFF2), "bonita.woff2"),
|
||||||
|
content_type="multipart/form-data")
|
||||||
|
|
||||||
|
name = db.execute("SELECT font_name FROM brand").fetchone()["font_name"]
|
||||||
|
css = client.get("/comunidad/marca.css").get_data(as_text=True)
|
||||||
|
|
||||||
|
assert "@font-face" in css and name in css
|
||||||
|
# Named first, with the old stack behind it: a font that 404s or arrives
|
||||||
|
# corrupt must leave a readable site, not a browser default.
|
||||||
|
assert 'body { font-family: "VLPropia", "Montserrat"' in css
|
||||||
|
|
||||||
|
served = client.get(f"/comunidad/marca/{name}")
|
||||||
|
assert served.status_code == 200
|
||||||
|
assert served.mimetype == "font/woff2"
|
||||||
|
|
||||||
|
|
||||||
|
def test_roundness_writes_the_four_radius_tokens(client, post, admin):
|
||||||
|
save(post, roundness="recta")
|
||||||
|
|
||||||
|
css = client.get("/comunidad/marca.css").get_data(as_text=True)
|
||||||
|
|
||||||
|
for token in ("--radius-xl", "--radius-lg", "--radius-md", "--radius-sm"):
|
||||||
|
assert f"{token}: 0;" in css, token
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_made_up_choice_falls_back_rather_than_being_stored(client, db, post, admin):
|
||||||
|
"""Both pickers read a key from a table in this module, never the value that
|
||||||
|
arrived."""
|
||||||
|
save(post, typeface="../../etc/passwd", roundness="DROP TABLE brand")
|
||||||
|
|
||||||
|
row = db.execute("SELECT typeface, roundness FROM brand").fetchone()
|
||||||
|
assert (row["typeface"], row["roundness"]) == ("sans", "suave")
|
||||||
|
|
||||||
|
|
||||||
|
def test_restoring_takes_the_font_with_it(app, client, db, post, admin):
|
||||||
|
save(post, typeface="propia", font=(io.BytesIO(WOFF2), "bonita.woff2"),
|
||||||
|
content_type="multipart/form-data")
|
||||||
|
name = db.execute("SELECT font_name FROM brand").fetchone()["font_name"]
|
||||||
|
|
||||||
|
post("/comunidad/gestion/marca/restaurar")
|
||||||
|
|
||||||
|
with app.app_context():
|
||||||
|
from apps.board import uploads
|
||||||
|
assert not uploads.directory().joinpath(name).exists()
|
||||||
|
assert "font-family" not in client.get("/comunidad/marca.css").get_data(as_text=True)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_font_and_the_radii_reach_the_public_site(db, post, admin, repo):
|
||||||
|
save(post, typeface="propia", roundness="redonda",
|
||||||
|
font=(io.BytesIO(WOFF2), "bonita.woff2"),
|
||||||
|
content_type="multipart/form-data")
|
||||||
|
|
||||||
|
assert "static/brand/font.woff2" in repo.files
|
||||||
|
yaml = repo.files["data/brand.yaml"].decode("utf-8")
|
||||||
|
assert 'font: "/brand/font.woff2"' in yaml
|
||||||
|
assert "font_stack: '\"VLPropia\"" in yaml
|
||||||
|
assert ' radius-xl: "28px"' in yaml
|
||||||
|
|||||||
@ -24,9 +24,9 @@ def quiet_gitea(monkeypatch):
|
|||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def an_event(post, owner_id, sign_in, quiet_gitea):
|
def an_event(post, superadmin_id, sign_in, quiet_gitea):
|
||||||
def _add(title="Asamblea", starts_on="2026-10-24", **extra):
|
def _add(title="Asamblea", starts_on="2026-10-24", **extra):
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
data = {"title": title, "starts_on": starts_on}
|
data = {"title": title, "starts_on": starts_on}
|
||||||
data.update(extra)
|
data.update(extra)
|
||||||
post("/comunidad/calendario/nuevo", data)
|
post("/comunidad/calendario/nuevo", data)
|
||||||
@ -72,19 +72,19 @@ def test_the_calendar_itself_is_behind_the_login(client):
|
|||||||
# --- the month -----------------------------------------------------------
|
# --- the month -----------------------------------------------------------
|
||||||
|
|
||||||
def test_the_month_shows_its_own_events_and_not_the_neighbours(
|
def test_the_month_shows_its_own_events_and_not_the_neighbours(
|
||||||
client, an_event, owner_id, sign_in):
|
client, an_event, superadmin_id, sign_in):
|
||||||
an_event("Asamblea", "2026-10-24")
|
an_event("Asamblea", "2026-10-24")
|
||||||
an_event("Ensayo", "2026-11-03")
|
an_event("Ensayo", "2026-11-03")
|
||||||
|
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
october = client.get("/comunidad/calendario?mes=2026-10").get_data(as_text=True)
|
october = client.get("/comunidad/calendario?mes=2026-10").get_data(as_text=True)
|
||||||
|
|
||||||
assert "Asamblea" in october
|
assert "Asamblea" in october
|
||||||
assert "Ensayo" not in october
|
assert "Ensayo" not in october
|
||||||
|
|
||||||
|
|
||||||
def test_the_arrows_cross_the_year(client, an_event, owner_id, sign_in):
|
def test_the_arrows_cross_the_year(client, an_event, superadmin_id, sign_in):
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
page = client.get("/comunidad/calendario?mes=2026-12").get_data(as_text=True)
|
page = client.get("/comunidad/calendario?mes=2026-12").get_data(as_text=True)
|
||||||
|
|
||||||
assert "mes=2027-01" in page
|
assert "mes=2027-01" in page
|
||||||
@ -98,10 +98,10 @@ def test_shifting_months_wraps_properly():
|
|||||||
|
|
||||||
|
|
||||||
def test_a_mistyped_month_shows_today_rather_than_an_error(
|
def test_a_mistyped_month_shows_today_rather_than_an_error(
|
||||||
client, owner_id, sign_in, quiet_gitea):
|
client, superadmin_id, sign_in, quiet_gitea):
|
||||||
"""A calendar that refuses to draw because a query string was mistyped is
|
"""A calendar that refuses to draw because a query string was mistyped is
|
||||||
worse than one that shows now."""
|
worse than one that shows now."""
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
today = date.today()
|
today = date.today()
|
||||||
|
|
||||||
page = client.get("/comunidad/calendario?mes=pumpkin")
|
page = client.get("/comunidad/calendario?mes=pumpkin")
|
||||||
@ -110,8 +110,8 @@ def test_a_mistyped_month_shows_today_rather_than_an_error(
|
|||||||
assert events.month_label(today.year, today.month) in page.get_data(as_text=True)
|
assert events.month_label(today.year, today.month) in page.get_data(as_text=True)
|
||||||
|
|
||||||
|
|
||||||
def test_february_in_a_leap_year_has_twenty_nine_days(client, owner_id, sign_in, quiet_gitea):
|
def test_february_in_a_leap_year_has_twenty_nine_days(client, superadmin_id, sign_in, quiet_gitea):
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
page = client.get("/comunidad/calendario?mes=2028-02").get_data(as_text=True)
|
page = client.get("/comunidad/calendario?mes=2028-02").get_data(as_text=True)
|
||||||
assert ">29<" in page
|
assert ">29<" in page
|
||||||
assert ">30<" not in page
|
assert ">30<" not in page
|
||||||
@ -120,13 +120,13 @@ def test_february_in_a_leap_year_has_twenty_nine_days(client, owner_id, sign_in,
|
|||||||
# --- what the git server does to this ------------------------------------
|
# --- what the git server does to this ------------------------------------
|
||||||
|
|
||||||
def test_the_private_events_survive_a_git_server_that_is_down(
|
def test_the_private_events_survive_a_git_server_that_is_down(
|
||||||
client, post, owner_id, sign_in, monkeypatch):
|
client, post, superadmin_id, sign_in, monkeypatch):
|
||||||
"""The half that only exists here must not be taken down by the half that
|
"""The half that only exists here must not be taken down by the half that
|
||||||
does not. A refused connection reaches this module as a GiteaError because
|
does not. A refused connection reaches this module as a GiteaError because
|
||||||
gitea.py translates it — before that it was a bare OSError and this page
|
gitea.py translates it — before that it was a bare OSError and this page
|
||||||
would have 500ed."""
|
would have 500ed."""
|
||||||
import requests
|
import requests
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"})
|
post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"})
|
||||||
|
|
||||||
def refuse(*args, **kwargs):
|
def refuse(*args, **kwargs):
|
||||||
@ -143,10 +143,10 @@ def test_the_private_events_survive_a_git_server_that_is_down(
|
|||||||
|
|
||||||
# --- the .ics -------------------------------------------------------------
|
# --- the .ics -------------------------------------------------------------
|
||||||
|
|
||||||
def test_the_ics_is_a_calendar_a_phone_understands(client, an_event, owner_id, sign_in):
|
def test_the_ics_is_a_calendar_a_phone_understands(client, an_event, superadmin_id, sign_in):
|
||||||
an_event("Asamblea", "2026-10-24", starts_at="19:00",
|
an_event("Asamblea", "2026-10-24", starts_at="19:00",
|
||||||
location="Local de la asociación")
|
location="Local de la asociación")
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
response = client.get("/comunidad/calendario/1.ics")
|
response = client.get("/comunidad/calendario/1.ics")
|
||||||
|
|
||||||
@ -159,22 +159,22 @@ def test_the_ics_is_a_calendar_a_phone_understands(client, an_event, owner_id, s
|
|||||||
assert "UID:evento-1@vienalatina.com" in body # stable, so re-adding updates
|
assert "UID:evento-1@vienalatina.com" in body # stable, so re-adding updates
|
||||||
|
|
||||||
|
|
||||||
def test_an_event_with_no_time_lasts_the_whole_day(client, an_event, owner_id, sign_in):
|
def test_an_event_with_no_time_lasts_the_whole_day(client, an_event, superadmin_id, sign_in):
|
||||||
"""VALUE=DATE rather than inventing midnight, which is how a calendar shows
|
"""VALUE=DATE rather than inventing midnight, which is how a calendar shows
|
||||||
it as a band across the top of the day."""
|
it as a band across the top of the day."""
|
||||||
an_event("Jornada", "2026-10-24")
|
an_event("Jornada", "2026-10-24")
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True)
|
body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True)
|
||||||
|
|
||||||
assert "DTSTART;VALUE=DATE:20261024" in body
|
assert "DTSTART;VALUE=DATE:20261024" in body
|
||||||
|
|
||||||
|
|
||||||
def test_a_comma_in_the_place_is_escaped(client, an_event, owner_id, sign_in):
|
def test_a_comma_in_the_place_is_escaped(client, an_event, superadmin_id, sign_in):
|
||||||
"""An unescaped comma in LOCATION makes the rest of the line a second
|
"""An unescaped comma in LOCATION makes the rest of the line a second
|
||||||
value, and the address arrives truncated."""
|
value, and the address arrives truncated."""
|
||||||
an_event("Asamblea", "2026-10-24", location="Plaza de Ottakring, junto al mercado")
|
an_event("Asamblea", "2026-10-24", location="Plaza de Ottakring, junto al mercado")
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True)
|
body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True)
|
||||||
|
|
||||||
@ -196,8 +196,8 @@ def test_the_ics_needs_a_session(client, an_event):
|
|||||||
|
|
||||||
# --- refusals -------------------------------------------------------------
|
# --- refusals -------------------------------------------------------------
|
||||||
|
|
||||||
def test_an_event_without_a_date_is_refused(client, db, post, owner_id, sign_in, quiet_gitea):
|
def test_an_event_without_a_date_is_refused(client, db, post, superadmin_id, sign_in, quiet_gitea):
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
response = post("/comunidad/calendario/nuevo", {"title": "Algún día"})
|
response = post("/comunidad/calendario/nuevo", {"title": "Algún día"})
|
||||||
|
|
||||||
@ -205,8 +205,8 @@ def test_an_event_without_a_date_is_refused(client, db, post, owner_id, sign_in,
|
|||||||
assert db.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"] == 0
|
assert db.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"] == 0
|
||||||
|
|
||||||
|
|
||||||
def test_a_nonsense_time_is_refused(client, db, post, owner_id, sign_in, quiet_gitea):
|
def test_a_nonsense_time_is_refused(client, db, post, superadmin_id, sign_in, quiet_gitea):
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
post("/comunidad/calendario/nuevo",
|
post("/comunidad/calendario/nuevo",
|
||||||
{"title": "Asamblea", "starts_on": "2026-10-24", "starts_at": "25:99"})
|
{"title": "Asamblea", "starts_on": "2026-10-24", "starts_at": "25:99"})
|
||||||
@ -217,14 +217,14 @@ def test_a_nonsense_time_is_refused(client, db, post, owner_id, sign_in, quiet_g
|
|||||||
# --- erasure --------------------------------------------------------------
|
# --- erasure --------------------------------------------------------------
|
||||||
|
|
||||||
def test_erasing_the_admin_leaves_the_event_standing(
|
def test_erasing_the_admin_leaves_the_event_standing(
|
||||||
db, post, an_event, owner_id, make_member, sign_in, quiet_gitea):
|
db, post, an_event, superadmin_id, make_member, sign_in, quiet_gitea):
|
||||||
"""The meeting still happens after they leave: the event belongs to the
|
"""The meeting still happens after they leave: the event belongs to the
|
||||||
association, so the row stays and the name goes."""
|
association, so the row stays and the name goes."""
|
||||||
admin = make_member("admina", role="admin")
|
admin = make_member("admina", role="admin")
|
||||||
sign_in(admin)
|
sign_in(admin)
|
||||||
post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"})
|
post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"})
|
||||||
|
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post(f"/comunidad/miembros/{admin}/eliminar")
|
post(f"/comunidad/miembros/{admin}/eliminar")
|
||||||
|
|
||||||
row = db.execute("SELECT title, created_by FROM events").fetchone()
|
row = db.execute("SELECT title, created_by FROM events").fetchone()
|
||||||
|
|||||||
@ -222,10 +222,10 @@ def test_a_suspended_member_gets_no_reset(client, post, make_member, outbox):
|
|||||||
# --- inviting from the members screen -------------------------------------
|
# --- inviting from the members screen -------------------------------------
|
||||||
|
|
||||||
def test_creating_a_member_emails_them_instead_of_showing_a_password(
|
def test_creating_a_member_emails_them_instead_of_showing_a_password(
|
||||||
app, client, post, owner_id, sign_in, outbox, monkeypatch):
|
app, client, post, superadmin_id, sign_in, outbox, monkeypatch):
|
||||||
monkeypatch.setattr(gitea, "admin_create_user",
|
monkeypatch.setattr(gitea, "admin_create_user",
|
||||||
lambda login, email, name, password: None)
|
lambda login, email, name, password: None)
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
response = post("/comunidad/miembros/nuevo", {
|
response = post("/comunidad/miembros/nuevo", {
|
||||||
"login": "maria", "display_name": "María", "email": "m@example.com",
|
"login": "maria", "display_name": "María", "email": "m@example.com",
|
||||||
@ -241,7 +241,7 @@ def test_creating_a_member_emails_them_instead_of_showing_a_password(
|
|||||||
|
|
||||||
|
|
||||||
def test_when_mail_fails_the_admin_is_given_the_link(
|
def test_when_mail_fails_the_admin_is_given_the_link(
|
||||||
app, client, post, owner_id, sign_in, monkeypatch):
|
app, client, post, superadmin_id, sign_in, monkeypatch):
|
||||||
"""Otherwise the account exists and the member simply never gets in."""
|
"""Otherwise the account exists and the member simply never gets in."""
|
||||||
monkeypatch.setattr(gitea, "admin_create_user",
|
monkeypatch.setattr(gitea, "admin_create_user",
|
||||||
lambda login, email, name, password: None)
|
lambda login, email, name, password: None)
|
||||||
@ -249,7 +249,7 @@ def test_when_mail_fails_the_admin_is_given_the_link(
|
|||||||
def explode(to, subject, body):
|
def explode(to, subject, body):
|
||||||
raise mail.MailFailed("connection refused")
|
raise mail.MailFailed("connection refused")
|
||||||
monkeypatch.setattr(mail, "send", explode)
|
monkeypatch.setattr(mail, "send", explode)
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
response = post("/comunidad/miembros/nuevo", {
|
response = post("/comunidad/miembros/nuevo", {
|
||||||
"login": "maria", "display_name": "María", "email": "m@example.com",
|
"login": "maria", "display_name": "María", "email": "m@example.com",
|
||||||
@ -265,13 +265,13 @@ def test_when_mail_fails_the_admin_is_given_the_link(
|
|||||||
# --- when the server cannot send at all -----------------------------------
|
# --- when the server cannot send at all -----------------------------------
|
||||||
|
|
||||||
def test_an_unconfigured_server_does_not_blame_the_mail_server(
|
def test_an_unconfigured_server_does_not_blame_the_mail_server(
|
||||||
app, client, post, owner_id, sign_in, monkeypatch):
|
app, client, post, superadmin_id, sign_in, monkeypatch):
|
||||||
"""No MAIL_HOST is not a failure, and saying "no se pudo enviar" sends the
|
"""No MAIL_HOST is not a failure, and saying "no se pudo enviar" sends the
|
||||||
admin hunting for an SMTP error that was never produced."""
|
admin hunting for an SMTP error that was never produced."""
|
||||||
monkeypatch.setattr(gitea, "admin_create_user",
|
monkeypatch.setattr(gitea, "admin_create_user",
|
||||||
lambda login, email, name, password: None)
|
lambda login, email, name, password: None)
|
||||||
app.config["MAIL_HOST"] = ""
|
app.config["MAIL_HOST"] = ""
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
page = post("/comunidad/miembros/nuevo", {
|
page = post("/comunidad/miembros/nuevo", {
|
||||||
"login": "maria", "display_name": "María", "email": "m@example.com",
|
"login": "maria", "display_name": "María", "email": "m@example.com",
|
||||||
@ -283,9 +283,9 @@ def test_an_unconfigured_server_does_not_blame_the_mail_server(
|
|||||||
assert "/comunidad/invitacion/" in page
|
assert "/comunidad/invitacion/" in page
|
||||||
|
|
||||||
|
|
||||||
def test_the_form_warns_before_it_is_filled_in(app, client, owner_id, sign_in):
|
def test_the_form_warns_before_it_is_filled_in(app, client, superadmin_id, sign_in):
|
||||||
app.config["MAIL_HOST"] = ""
|
app.config["MAIL_HOST"] = ""
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
assert "no envía correo" in client.get(
|
assert "no envía correo" in client.get(
|
||||||
"/comunidad/miembros/nuevo").get_data(as_text=True)
|
"/comunidad/miembros/nuevo").get_data(as_text=True)
|
||||||
|
|
||||||
@ -323,13 +323,13 @@ def test_recovery_is_always_offered_now(app, client):
|
|||||||
# member added any other way had no route in at all: no invitation was ever
|
# member added any other way had no route in at all: no invitation was ever
|
||||||
# issued for them and nothing could issue one later.
|
# issued for them and nothing could issue one later.
|
||||||
|
|
||||||
def test_an_existing_member_can_be_invited(app, client, post, owner_id, make_member,
|
def test_an_existing_member_can_be_invited(app, client, post, superadmin_id, make_member,
|
||||||
sign_in, outbox):
|
sign_in, outbox):
|
||||||
"""The case that prompted this: the admin made the account by hand, added
|
"""The case that prompted this: the admin made the account by hand, added
|
||||||
the member with the box unticked, and nobody could reach the account —
|
the member with the box unticked, and nobody could reach the account —
|
||||||
including the admin, who never knew the password."""
|
including the admin, who never knew the password."""
|
||||||
member_id = make_member("salvador")
|
member_id = make_member("salvador")
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
post(f"/comunidad/miembros/{member_id}/invitar")
|
post(f"/comunidad/miembros/{member_id}/invitar")
|
||||||
|
|
||||||
@ -339,12 +339,12 @@ def test_an_existing_member_can_be_invited(app, client, post, owner_id, make_mem
|
|||||||
assert invites.lookup(token_in(outbox[0]["body"])) is not None
|
assert invites.lookup(token_in(outbox[0]["body"])) is not None
|
||||||
|
|
||||||
|
|
||||||
def test_re_inviting_kills_the_previous_link(app, client, post, owner_id, make_member,
|
def test_re_inviting_kills_the_previous_link(app, client, post, superadmin_id, make_member,
|
||||||
sign_in, outbox):
|
sign_in, outbox):
|
||||||
"""A link that was forwarded, or is sitting in a mailbox somebody else can
|
"""A link that was forwarded, or is sitting in a mailbox somebody else can
|
||||||
read, must stop working the moment a replacement is sent."""
|
read, must stop working the moment a replacement is sent."""
|
||||||
member_id = make_member("salvador")
|
member_id = make_member("salvador")
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
post(f"/comunidad/miembros/{member_id}/invitar")
|
post(f"/comunidad/miembros/{member_id}/invitar")
|
||||||
post(f"/comunidad/miembros/{member_id}/invitar")
|
post(f"/comunidad/miembros/{member_id}/invitar")
|
||||||
@ -370,13 +370,13 @@ def test_a_plain_user_cannot_invite(client, post, make_member, sign_in, outbox):
|
|||||||
|
|
||||||
|
|
||||||
def test_a_member_with_no_address_is_refused_before_a_token_is_made(
|
def test_a_member_with_no_address_is_refused_before_a_token_is_made(
|
||||||
app, client, db, post, owner_id, sign_in, outbox):
|
app, client, db, post, superadmin_id, sign_in, outbox):
|
||||||
"""Issuing the token first would invalidate a previous, working invitation
|
"""Issuing the token first would invalidate a previous, working invitation
|
||||||
in exchange for one that cannot be delivered."""
|
in exchange for one that cannot be delivered."""
|
||||||
member_id = db.execute(
|
member_id = db.execute(
|
||||||
"INSERT INTO members (gitea_login, display_name, role) VALUES ('sincorreo', 'Sin', 'user')"
|
"INSERT INTO members (gitea_login, display_name, role) VALUES ('sincorreo', 'Sin', 'user')"
|
||||||
).lastrowid
|
).lastrowid
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
post(f"/comunidad/miembros/{member_id}/invitar", follow_redirects=True)
|
post(f"/comunidad/miembros/{member_id}/invitar", follow_redirects=True)
|
||||||
|
|
||||||
@ -384,9 +384,9 @@ def test_a_member_with_no_address_is_refused_before_a_token_is_made(
|
|||||||
assert db.execute("SELECT 1 FROM invites").fetchone() is None
|
assert db.execute("SELECT 1 FROM invites").fetchone() is None
|
||||||
|
|
||||||
|
|
||||||
def test_a_suspended_member_cannot_be_invited(client, post, owner_id, make_member,
|
def test_a_suspended_member_cannot_be_invited(client, post, superadmin_id, make_member,
|
||||||
sign_in, outbox):
|
sign_in, outbox):
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
response = post(f"/comunidad/miembros/{make_member('fuera', active=0)}/invitar")
|
response = post(f"/comunidad/miembros/{make_member('fuera', active=0)}/invitar")
|
||||||
|
|
||||||
assert response.status_code == 403
|
assert response.status_code == 403
|
||||||
@ -394,11 +394,11 @@ def test_a_suspended_member_cannot_be_invited(client, post, owner_id, make_membe
|
|||||||
|
|
||||||
|
|
||||||
def test_when_the_mail_fails_the_admin_is_handed_the_link(
|
def test_when_the_mail_fails_the_admin_is_handed_the_link(
|
||||||
app, client, post, owner_id, make_member, sign_in, monkeypatch):
|
app, client, post, superadmin_id, make_member, sign_in, monkeypatch):
|
||||||
def explode(to, subject, body):
|
def explode(to, subject, body):
|
||||||
raise mail.MailFailed("connection refused")
|
raise mail.MailFailed("connection refused")
|
||||||
monkeypatch.setattr(mail, "send", explode)
|
monkeypatch.setattr(mail, "send", explode)
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
page = post(f"/comunidad/miembros/{make_member('salvador')}/invitar",
|
page = post(f"/comunidad/miembros/{make_member('salvador')}/invitar",
|
||||||
follow_redirects=True).get_data(as_text=True)
|
follow_redirects=True).get_data(as_text=True)
|
||||||
|
|||||||
@ -11,31 +11,53 @@ from apps.board.members import may_create, may_manage
|
|||||||
|
|
||||||
# --- the rules as plain functions ---------------------------------------
|
# --- the rules as plain functions ---------------------------------------
|
||||||
|
|
||||||
def test_only_the_owner_makes_admins():
|
def test_only_the_superadmin_makes_admins():
|
||||||
assert may_create("owner", "admin")
|
"""The line this phase draws. An admin account is the platform's, not the
|
||||||
|
association's — which is what makes it safe to hand the responsable chair to
|
||||||
|
a customer organisation's president."""
|
||||||
|
assert may_create("superadmin", "admin")
|
||||||
|
assert not may_create("owner", "admin")
|
||||||
assert not may_create("admin", "admin")
|
assert not may_create("admin", "admin")
|
||||||
assert not may_create("user", "admin")
|
assert not may_create("user", "admin")
|
||||||
|
|
||||||
|
|
||||||
def test_admins_and_the_owner_make_users():
|
def test_everyone_above_a_moderator_makes_users():
|
||||||
|
assert may_create("superadmin", "user")
|
||||||
assert may_create("owner", "user")
|
assert may_create("owner", "user")
|
||||||
assert may_create("admin", "user")
|
assert may_create("admin", "user")
|
||||||
assert not may_create("user", "user")
|
assert not may_create("user", "user")
|
||||||
|
|
||||||
|
|
||||||
def test_the_owner_is_beyond_everyone_including_themselves():
|
def test_neither_chair_can_be_touched_by_anybody():
|
||||||
assert not may_manage("owner", "owner")
|
"""Both single chairs, both unreachable, for different reasons. The
|
||||||
assert not may_manage("admin", "owner")
|
superadministrator because there is nothing above them; the responsable
|
||||||
|
because the chair belongs to the association, and a platform administrator
|
||||||
|
quietly removing the president of the organisation they host is the move the
|
||||||
|
separation exists to prevent."""
|
||||||
|
for actor in ("superadmin", "owner", "admin", "moderator", "user"):
|
||||||
|
assert not may_manage(actor, "superadmin"), actor
|
||||||
|
assert not may_manage(actor, "owner"), actor
|
||||||
|
|
||||||
|
|
||||||
def test_only_the_owner_manages_admins():
|
def test_only_the_superadmin_manages_admins():
|
||||||
assert may_manage("owner", "admin")
|
assert may_manage("superadmin", "admin")
|
||||||
|
assert not may_manage("owner", "admin")
|
||||||
assert not may_manage("admin", "admin")
|
assert not may_manage("admin", "admin")
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_role_picker_offers_exactly_what_the_handler_allows():
|
||||||
|
"""They used to be one constant and one predicate, which could only agree
|
||||||
|
for one actor once there were two levels above admin."""
|
||||||
|
from apps.board.members import assignable_roles
|
||||||
|
for actor in ("superadmin", "owner", "admin", "moderator", "user"):
|
||||||
|
for role in ("admin", "moderator", "user"):
|
||||||
|
assert (role in assignable_roles(actor)) == may_create(actor, role), (actor, role)
|
||||||
|
|
||||||
|
|
||||||
# --- the moderator, who curates content and not people -------------------
|
# --- the moderator, who curates content and not people -------------------
|
||||||
|
|
||||||
def test_admins_and_the_owner_make_moderators():
|
def test_admins_and_the_chairs_make_moderators():
|
||||||
|
assert may_create("superadmin", "moderator")
|
||||||
assert may_create("owner", "moderator")
|
assert may_create("owner", "moderator")
|
||||||
assert may_create("admin", "moderator")
|
assert may_create("admin", "moderator")
|
||||||
assert not may_create("moderator", "moderator")
|
assert not may_create("moderator", "moderator")
|
||||||
@ -46,7 +68,7 @@ def test_a_moderator_has_no_power_over_anybody():
|
|||||||
"""The line the whole role rests on. Being trusted to judge what the public
|
"""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
|
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."""
|
moderator who could do both would be a second kind of admin."""
|
||||||
for target in ("owner", "admin", "moderator", "user"):
|
for target in ("superadmin", "owner", "admin", "moderator", "user"):
|
||||||
assert not may_manage("moderator", target), target
|
assert not may_manage("moderator", target), target
|
||||||
assert not may_create("moderator", target), target
|
assert not may_create("moderator", target), target
|
||||||
|
|
||||||
@ -64,9 +86,8 @@ def test_an_admin_may_promote_a_member_to_moderator(client, db, post, make_membe
|
|||||||
|
|
||||||
def test_an_admin_still_cannot_mint_an_admin_through_the_role_form(
|
def test_an_admin_still_cannot_mint_an_admin_through_the_role_form(
|
||||||
client, db, post, make_member, sign_in):
|
client, db, post, make_member, sign_in):
|
||||||
"""`set_role` moved from owner-only to admin-level so moderators can be
|
"""`set_role` is admin-level so moderators can be appointed routinely. That
|
||||||
appointed routinely. That must not quietly hand admins the one power the
|
must not quietly hand admins the one power the superadministrator keeps."""
|
||||||
owner keeps."""
|
|
||||||
admin = make_member("admina", role="admin")
|
admin = make_member("admina", role="admin")
|
||||||
maria = make_member("maria")
|
maria = make_member("maria")
|
||||||
sign_in(admin)
|
sign_in(admin)
|
||||||
@ -84,10 +105,10 @@ def test_a_moderator_cannot_change_a_role_at_all(client, db, post, make_member,
|
|||||||
|
|
||||||
|
|
||||||
def test_the_role_form_refuses_a_role_that_is_not_offered(
|
def test_the_role_form_refuses_a_role_that_is_not_offered(
|
||||||
client, db, post, owner_id, make_member, sign_in):
|
client, db, post, superadmin_id, make_member, sign_in):
|
||||||
"""`tombstone` is a real value in the CHECK constraint and would make the
|
"""`tombstone` is a real value in the CHECK constraint and would make the
|
||||||
member vanish from every listing while keeping their row."""
|
member vanish from every listing while keeping their row."""
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
maria = make_member("maria")
|
maria = make_member("maria")
|
||||||
|
|
||||||
assert post(f"/comunidad/miembros/{maria}/rol", {"role": "tombstone"}).status_code == 403
|
assert post(f"/comunidad/miembros/{maria}/rol", {"role": "tombstone"}).status_code == 403
|
||||||
@ -96,24 +117,44 @@ def test_the_role_form_refuses_a_role_that_is_not_offered(
|
|||||||
|
|
||||||
# --- the database holds the line ----------------------------------------
|
# --- the database holds the line ----------------------------------------
|
||||||
|
|
||||||
def test_a_second_owner_is_impossible(db):
|
def test_a_second_superadmin_is_impossible(db, superadmin_id):
|
||||||
"""Not a route check — a direct insert, because the point of the partial
|
"""Not a route check — a direct insert, because the point of the partial
|
||||||
unique index is to survive a bug in the code above it."""
|
unique index is to survive a bug in the code above it."""
|
||||||
with pytest.raises(sqlite3.IntegrityError):
|
with pytest.raises(sqlite3.IntegrityError):
|
||||||
db.execute(
|
db.execute(
|
||||||
"INSERT INTO members (gitea_login, role) VALUES ('usurpador', 'owner')"
|
"INSERT INTO members (gitea_login, role) VALUES ('usurpador', 'superadmin')"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_transfer_leaves_exactly_one_owner(app, db, owner_id, make_member):
|
def test_a_second_owner_is_impossible(db, owner_id):
|
||||||
from apps.board.members import transfer_ownership
|
with pytest.raises(sqlite3.IntegrityError):
|
||||||
admin_id = make_member("segunda", role="admin")
|
db.execute(
|
||||||
transfer_ownership(db, owner_id, admin_id)
|
"INSERT INTO members (gitea_login, role) VALUES ('usurpadora', 'owner')"
|
||||||
|
)
|
||||||
|
|
||||||
owners = db.execute("SELECT id FROM members WHERE role = 'owner'").fetchall()
|
|
||||||
assert [row["id"] for row in owners] == [admin_id]
|
@pytest.mark.parametrize("chair", ["superadmin", "owner"])
|
||||||
|
def test_transfer_leaves_exactly_one_holder(app, db, superadmin_id, make_member, chair):
|
||||||
|
"""Both chairs hand on the same way. The demotion comes first, or the unique
|
||||||
|
index refuses the promotion halfway through."""
|
||||||
|
from apps.board.members import transfer_ownership
|
||||||
|
holder = superadmin_id if chair == "superadmin" else make_member("presi", role="owner")
|
||||||
|
admin_id = make_member("segunda", role="admin")
|
||||||
|
|
||||||
|
transfer_ownership(db, holder, admin_id, chair)
|
||||||
|
|
||||||
|
holders = db.execute("SELECT id FROM members WHERE role = ?", (chair,)).fetchall()
|
||||||
|
assert [row["id"] for row in holders] == [admin_id]
|
||||||
assert db.execute("SELECT role FROM members WHERE id = ?",
|
assert db.execute("SELECT role FROM members WHERE id = ?",
|
||||||
(owner_id,)).fetchone()["role"] == "admin"
|
(holder,)).fetchone()["role"] == "admin"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_transfer_to_something_that_is_not_a_chair_is_refused(db, superadmin_id, make_member):
|
||||||
|
"""`chair` comes from the route and never from a request, and this is what
|
||||||
|
keeps that true if somebody ever wires it to one."""
|
||||||
|
from apps.board.members import transfer_ownership
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
transfer_ownership(db, superadmin_id, make_member("otra"), "admin")
|
||||||
|
|
||||||
|
|
||||||
# --- the routes ----------------------------------------------------------
|
# --- the routes ----------------------------------------------------------
|
||||||
@ -127,8 +168,8 @@ def test_admin_cannot_create_an_admin(client, post, make_member, sign_in):
|
|||||||
assert response.status_code == 403
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
def test_owner_can_create_an_admin(client, db, post, owner_id, sign_in):
|
def test_the_superadmin_can_create_an_admin(client, db, post, superadmin_id, sign_in):
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post("/comunidad/miembros/nuevo", {
|
post("/comunidad/miembros/nuevo", {
|
||||||
"login": "nueva", "display_name": "Nueva", "email": "n@example.com",
|
"login": "nueva", "display_name": "Nueva", "email": "n@example.com",
|
||||||
"role": "admin",
|
"role": "admin",
|
||||||
@ -142,15 +183,15 @@ def test_a_plain_user_cannot_reach_the_admin_screens(client, make_member, sign_i
|
|||||||
assert client.get("/comunidad/miembros/nuevo").status_code == 403
|
assert client.get("/comunidad/miembros/nuevo").status_code == 403
|
||||||
|
|
||||||
|
|
||||||
def test_the_owner_cannot_be_suspended(client, post, owner_id, make_member, sign_in):
|
def test_the_superadmin_cannot_be_suspended(client, post, superadmin_id, make_member, sign_in):
|
||||||
sign_in(make_member("admina", role="admin"))
|
sign_in(make_member("admina", role="admin"))
|
||||||
response = post(f"/comunidad/miembros/{owner_id}/estado", {"active": "0"})
|
response = post(f"/comunidad/miembros/{superadmin_id}/estado", {"active": "0"})
|
||||||
assert response.status_code == 403
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
def test_the_owner_cannot_suspend_themselves(client, post, owner_id, sign_in):
|
def test_the_superadmin_cannot_suspend_themselves(client, post, superadmin_id, sign_in):
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
response = post(f"/comunidad/miembros/{owner_id}/estado", {"active": "0"})
|
response = post(f"/comunidad/miembros/{superadmin_id}/estado", {"active": "0"})
|
||||||
assert response.status_code == 403
|
assert response.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
@ -165,11 +206,11 @@ def test_an_admin_cannot_demote_another_admin(client, post, make_member, sign_in
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_erasing_a_member_keeps_their_threads_readable(app, db, post, owner_id, make_member, sign_in):
|
def test_erasing_a_member_keeps_their_threads_readable(app, db, post, superadmin_id, make_member, sign_in):
|
||||||
author = make_member("saliente")
|
author = make_member("saliente")
|
||||||
db.execute("INSERT INTO threads (author_id, title, body_md) VALUES (?, 'Hola', 'Texto')",
|
db.execute("INSERT INTO threads (author_id, title, body_md) VALUES (?, 'Hola', 'Texto')",
|
||||||
(author,))
|
(author,))
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post(f"/comunidad/miembros/{author}/eliminar")
|
post(f"/comunidad/miembros/{author}/eliminar")
|
||||||
|
|
||||||
assert db.execute("SELECT 1 FROM members WHERE id = ?", (author,)).fetchone() is None
|
assert db.execute("SELECT 1 FROM members WHERE id = ?", (author,)).fetchone() is None
|
||||||
@ -180,36 +221,52 @@ def test_erasing_a_member_keeps_their_threads_readable(app, db, post, owner_id,
|
|||||||
assert row["display_name"] == "Miembro eliminado"
|
assert row["display_name"] == "Miembro eliminado"
|
||||||
|
|
||||||
|
|
||||||
def test_the_member_page_renders_for_each_role(client, db, owner_id, make_member, sign_in):
|
def test_the_member_page_renders_for_each_role(client, db, superadmin_id, owner_id,
|
||||||
"""Every role takes a different branch through member.html — the owner sees
|
make_member, sign_in):
|
||||||
transfer and erase, an admin sees suspend, a plain member sees neither — so
|
"""Every role takes a different branch through member.html — the
|
||||||
each one is rendered here rather than trusted.
|
superadministrator alone sees «Entregar la plataforma», both chairs see
|
||||||
|
«Eliminar», an admin sees «Suspender» and a plain member sees none of it —
|
||||||
|
so each one is rendered here rather than trusted.
|
||||||
|
|
||||||
These controls used to be on the cards in the directory and are on the
|
The page opened is always somebody else's: nobody manages themselves, the
|
||||||
person's page now, which is what this looks at. The owner's branch needs an
|
block is not drawn on your own page, and a test looking at it would pass for
|
||||||
admin to transfer to, so the page opened is the admin's.
|
the wrong reason.
|
||||||
"""
|
"""
|
||||||
admin_id = make_member("admina", role="admin")
|
admin_id = make_member("admina", role="admin")
|
||||||
|
cases = [
|
||||||
|
(superadmin_id, "admina", ["Entregar la plataforma", "Eliminar", "Suspender"]),
|
||||||
|
(owner_id, "admina", ["Eliminar", "Suspender"]),
|
||||||
|
(admin_id, "usuaria", ["Suspender"]),
|
||||||
|
(make_member("usuaria"), "admina", []),
|
||||||
|
]
|
||||||
|
forbidden = {"Entregar la plataforma", "Eliminar", "Suspender"}
|
||||||
|
|
||||||
for member_id, expected in ((owner_id, "Transferir titularidad"),
|
for member_id, who, expected in cases:
|
||||||
(admin_id, "Suspender"),
|
|
||||||
(make_member("usuaria"), None)):
|
|
||||||
sign_in(member_id)
|
sign_in(member_id)
|
||||||
# Never your own page: nobody manages themselves, so the block is not
|
|
||||||
# drawn there and the test would pass for the wrong reason.
|
|
||||||
who = "usuaria" if member_id == admin_id else "admina"
|
|
||||||
body = client.get(f"/comunidad/miembro/{who}").get_data(as_text=True)
|
body = client.get(f"/comunidad/miembro/{who}").get_data(as_text=True)
|
||||||
assert who.title() in body
|
assert who.title() in body
|
||||||
if expected:
|
for phrase in expected:
|
||||||
assert expected in body
|
assert phrase in body, (member_id, phrase)
|
||||||
else:
|
for phrase in forbidden - set(expected):
|
||||||
assert "Transferir titularidad" not in body
|
assert phrase not in body, (member_id, phrase)
|
||||||
assert "Suspender" not in body
|
|
||||||
|
|
||||||
|
def test_the_responsable_cannot_reach_an_admin_from_their_page(
|
||||||
|
client, owner_id, make_member, sign_in):
|
||||||
|
"""The association's chair runs the association. An admin account is the
|
||||||
|
platform's, so the whole management block is absent from their page."""
|
||||||
|
make_member("admina", role="admin")
|
||||||
|
sign_in(owner_id)
|
||||||
|
|
||||||
|
body = client.get("/comunidad/miembro/admina").get_data(as_text=True)
|
||||||
|
|
||||||
|
assert "Gestionar" in body # it is drawn — an admin is manageable…
|
||||||
|
assert "Administrador" not in body.split("Gestionar")[1] # …but not into or out of admin
|
||||||
|
|
||||||
|
|
||||||
def test_the_new_member_form_hides_the_role_choice_from_admins(
|
def test_the_new_member_form_hides_the_role_choice_from_admins(
|
||||||
client, owner_id, make_member, sign_in):
|
client, superadmin_id, make_member, sign_in):
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
assert "Administrador" in client.get("/comunidad/miembros/nuevo").get_data(as_text=True)
|
assert "Administrador" in client.get("/comunidad/miembros/nuevo").get_data(as_text=True)
|
||||||
|
|
||||||
sign_in(make_member("admina", role="admin"))
|
sign_in(make_member("admina", role="admin"))
|
||||||
@ -236,7 +293,7 @@ def test_the_export_is_only_your_own_writing(client, db, make_member, sign_in):
|
|||||||
|
|
||||||
# --- erasing somebody who has left traces --------------------------------
|
# --- erasing somebody who has left traces --------------------------------
|
||||||
|
|
||||||
def test_erasing_a_member_who_posted_a_picture(app, db, post, owner_id, make_member, sign_in):
|
def test_erasing_a_member_who_posted_a_picture(app, db, post, superadmin_id, make_member, sign_in):
|
||||||
"""This failed in production with a 500 the first time it was tried.
|
"""This failed in production with a 500 the first time it was tried.
|
||||||
|
|
||||||
`attachments.uploaded_by` is NOT NULL and does not cascade, so with a
|
`attachments.uploaded_by` is NOT NULL and does not cascade, so with a
|
||||||
@ -251,7 +308,7 @@ def test_erasing_a_member_who_posted_a_picture(app, db, post, owner_id, make_mem
|
|||||||
VALUES (1, 'foto-abc123abc123.jpg', 'foto.jpg', 'image/jpeg', 10, ?)""",
|
VALUES (1, 'foto-abc123abc123.jpg', 'foto.jpg', 'image/jpeg', 10, ?)""",
|
||||||
(author,),
|
(author,),
|
||||||
)
|
)
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
response = post(f"/comunidad/miembros/{author}/eliminar")
|
response = post(f"/comunidad/miembros/{author}/eliminar")
|
||||||
|
|
||||||
@ -297,11 +354,11 @@ def test_every_table_pointing_at_members_is_accounted_for(db):
|
|||||||
# --- onboarding, now that there is only one account to make --------------
|
# --- onboarding, now that there is only one account to make --------------
|
||||||
|
|
||||||
def test_a_new_member_has_no_password_until_they_choose_one(
|
def test_a_new_member_has_no_password_until_they_choose_one(
|
||||||
client, db, post, owner_id, sign_in, monkeypatch):
|
client, db, post, superadmin_id, sign_in, monkeypatch):
|
||||||
"""No password is generated and none is shown. Until the invitation is
|
"""No password is generated and none is shown. Until the invitation is
|
||||||
used, password_hash is NULL — and a NULL hash cannot be signed in with."""
|
used, password_hash is NULL — and a NULL hash cannot be signed in with."""
|
||||||
monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None)
|
monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None)
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
post("/comunidad/miembros/nuevo", {
|
post("/comunidad/miembros/nuevo", {
|
||||||
"login": "maria", "display_name": "María", "email": "m@example.com",
|
"login": "maria", "display_name": "María", "email": "m@example.com",
|
||||||
@ -314,10 +371,10 @@ def test_a_new_member_has_no_password_until_they_choose_one(
|
|||||||
assert row["password_hash"] is None
|
assert row["password_hash"] is None
|
||||||
|
|
||||||
|
|
||||||
def test_an_address_is_required(client, db, post, owner_id, sign_in):
|
def test_an_address_is_required(client, db, post, superadmin_id, sign_in):
|
||||||
"""It is the only way the invitation reaches anybody, so a member without
|
"""It is the only way the invitation reaches anybody, so a member without
|
||||||
one is a row that can never be used."""
|
one is a row that can never be used."""
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post("/comunidad/miembros/nuevo", {
|
post("/comunidad/miembros/nuevo", {
|
||||||
"login": "maria", "display_name": "María", "email": "", "role": "user",
|
"login": "maria", "display_name": "María", "email": "", "role": "user",
|
||||||
})
|
})
|
||||||
@ -325,12 +382,12 @@ def test_an_address_is_required(client, db, post, owner_id, sign_in):
|
|||||||
|
|
||||||
|
|
||||||
def test_a_duplicate_is_refused_before_anything_is_written(
|
def test_a_duplicate_is_refused_before_anything_is_written(
|
||||||
client, db, post, owner_id, make_member, sign_in, monkeypatch):
|
client, db, post, superadmin_id, make_member, sign_in, monkeypatch):
|
||||||
"""The error that started this: "ya están en uso" for somebody who was not
|
"""The error that started this: "ya están en uso" for somebody who was not
|
||||||
on the list. There is one list now, so the message and the screen agree."""
|
on the list. There is one list now, so the message and the screen agree."""
|
||||||
monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None)
|
monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None)
|
||||||
make_member("maria")
|
make_member("maria")
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
response = post("/comunidad/miembros/nuevo", {
|
response = post("/comunidad/miembros/nuevo", {
|
||||||
"login": "maria", "display_name": "Otra", "email": "otra@example.com",
|
"login": "maria", "display_name": "Otra", "email": "otra@example.com",
|
||||||
@ -344,11 +401,11 @@ def test_a_duplicate_is_refused_before_anything_is_written(
|
|||||||
|
|
||||||
|
|
||||||
def test_erasing_a_member_lets_the_name_be_used_again(
|
def test_erasing_a_member_lets_the_name_be_used_again(
|
||||||
client, db, post, owner_id, make_member, sign_in, monkeypatch):
|
client, db, post, superadmin_id, make_member, sign_in, monkeypatch):
|
||||||
"""Deleting used to leave an account behind on the other server, so the
|
"""Deleting used to leave an account behind on the other server, so the
|
||||||
name stayed taken somewhere invisible. With one store, gone means gone."""
|
name stayed taken somewhere invisible. With one store, gone means gone."""
|
||||||
monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None)
|
monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None)
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post(f"/comunidad/miembros/{make_member('salvador')}/eliminar")
|
post(f"/comunidad/miembros/{make_member('salvador')}/eliminar")
|
||||||
|
|
||||||
post("/comunidad/miembros/nuevo", {
|
post("/comunidad/miembros/nuevo", {
|
||||||
@ -477,3 +534,105 @@ def test_a_moderator_gets_no_controls_either(client, make_member, sign_in):
|
|||||||
assert client.post(f"/comunidad/miembros/{maria}/estado",
|
assert client.post(f"/comunidad/miembros/{maria}/estado",
|
||||||
data={"csrf_token": "token-for-tests", "active": "0"}
|
data={"csrf_token": "token-for-tests", "active": "0"}
|
||||||
).status_code == 403
|
).status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
# --- the two chairs, from the routes --------------------------------------
|
||||||
|
|
||||||
|
def test_an_admin_cannot_make_promote_or_erase_another_admin(
|
||||||
|
client, db, post, make_member, sign_in):
|
||||||
|
"""Four doors into the same power, checked at each one. A hidden button is a
|
||||||
|
courtesy; these are the rules."""
|
||||||
|
other = make_member("otra", role="admin")
|
||||||
|
sign_in(make_member("admina", role="admin"))
|
||||||
|
|
||||||
|
assert post("/comunidad/miembros/nuevo", {
|
||||||
|
"login": "tercera", "display_name": "Tercera",
|
||||||
|
"email": "t@example.com", "role": "admin"}).status_code == 403
|
||||||
|
assert post(f"/comunidad/miembros/{other}/rol", {"role": "user"}).status_code == 403
|
||||||
|
assert post(f"/comunidad/miembros/{other}/estado", {"active": "0"}).status_code == 403
|
||||||
|
assert post(f"/comunidad/miembros/{other}/eliminar").status_code == 403
|
||||||
|
assert db.execute("SELECT role, active FROM members WHERE id = ?",
|
||||||
|
(other,)).fetchone()["role"] == "admin"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_responsable_cannot_touch_an_admin_either(
|
||||||
|
client, db, post, owner_id, make_member, sign_in):
|
||||||
|
"""The chair this phase exists to make safe to hand over. A customer
|
||||||
|
organisation's president runs their association and does not administer the
|
||||||
|
platform that hosts it."""
|
||||||
|
admin_id = make_member("admina", role="admin")
|
||||||
|
sign_in(owner_id)
|
||||||
|
|
||||||
|
assert post("/comunidad/miembros/nuevo", {
|
||||||
|
"login": "nueva", "display_name": "Nueva",
|
||||||
|
"email": "n@example.com", "role": "admin"}).status_code == 403
|
||||||
|
assert post(f"/comunidad/miembros/{admin_id}/rol", {"role": "user"}).status_code == 403
|
||||||
|
assert post(f"/comunidad/miembros/{admin_id}/estado", {"active": "0"}).status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_nobody_reaches_the_superadmin_through_a_route(
|
||||||
|
client, post, superadmin_id, owner_id, make_member, sign_in):
|
||||||
|
for actor in (owner_id, make_member("admina", role="admin"), superadmin_id):
|
||||||
|
sign_in(actor)
|
||||||
|
assert post(f"/comunidad/miembros/{superadmin_id}/estado",
|
||||||
|
{"active": "0"}).status_code == 403, actor
|
||||||
|
assert post(f"/comunidad/miembros/{superadmin_id}/rol",
|
||||||
|
{"role": "user"}).status_code == 403, actor
|
||||||
|
assert post(f"/comunidad/miembros/{superadmin_id}/eliminar").status_code == 403, actor
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_superadmin_cannot_erase_the_responsable(client, post, superadmin_id,
|
||||||
|
owner_id, sign_in):
|
||||||
|
"""Deliberate, and the less obvious half of the separation: a platform
|
||||||
|
administrator quietly removing the president of the organisation they host
|
||||||
|
is exactly what two chairs are for."""
|
||||||
|
sign_in(superadmin_id)
|
||||||
|
assert post(f"/comunidad/miembros/{owner_id}/eliminar").status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_handing_the_platform_on_is_the_superadmins_alone(
|
||||||
|
client, db, post, superadmin_id, owner_id, make_member, sign_in):
|
||||||
|
admin_id = make_member("admina", role="admin")
|
||||||
|
|
||||||
|
for actor in (owner_id, admin_id):
|
||||||
|
sign_in(actor)
|
||||||
|
assert post(f"/comunidad/miembros/{admin_id}/transferir-plataforma"
|
||||||
|
).status_code == 403
|
||||||
|
|
||||||
|
sign_in(superadmin_id)
|
||||||
|
post(f"/comunidad/miembros/{admin_id}/transferir-plataforma")
|
||||||
|
|
||||||
|
assert db.execute("SELECT role FROM members WHERE id = ?",
|
||||||
|
(admin_id,)).fetchone()["role"] == "superadmin"
|
||||||
|
assert db.execute("SELECT role FROM members WHERE id = ?",
|
||||||
|
(superadmin_id,)).fetchone()["role"] == "admin"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_platform_only_goes_to_an_active_admin(client, db, post, superadmin_id,
|
||||||
|
make_member, sign_in):
|
||||||
|
sign_in(superadmin_id)
|
||||||
|
maria = make_member("maria")
|
||||||
|
suspended = make_member("dormida", role="admin", active=0)
|
||||||
|
|
||||||
|
post(f"/comunidad/miembros/{maria}/transferir-plataforma")
|
||||||
|
post(f"/comunidad/miembros/{suspended}/transferir-plataforma")
|
||||||
|
|
||||||
|
assert db.execute("SELECT role FROM members WHERE id = ?",
|
||||||
|
(superadmin_id,)).fetchone()["role"] == "superadmin"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_superadmin_can_fill_an_empty_responsable_chair(
|
||||||
|
client, db, post, superadmin_id, make_member, sign_in):
|
||||||
|
"""A fresh install has nobody in it — migration 7 promotes the owner and
|
||||||
|
leaves the chair open — so somebody has to be able to seat the first one."""
|
||||||
|
maria = make_member("maria")
|
||||||
|
sign_in(superadmin_id)
|
||||||
|
|
||||||
|
post(f"/comunidad/miembros/{maria}/transferir")
|
||||||
|
|
||||||
|
assert db.execute("SELECT role FROM members WHERE id = ?",
|
||||||
|
(maria,)).fetchone()["role"] == "owner"
|
||||||
|
# And the superadministrator is still the superadministrator: filling a
|
||||||
|
# chair you do not sit in costs you nothing.
|
||||||
|
assert db.execute("SELECT role FROM members WHERE id = ?",
|
||||||
|
(superadmin_id,)).fetchone()["role"] == "superadmin"
|
||||||
|
|||||||
@ -301,7 +301,7 @@ def test_an_empty_message_with_no_picture_is_refused(client, db, post, make_memb
|
|||||||
# --- erasure --------------------------------------------------------------
|
# --- erasure --------------------------------------------------------------
|
||||||
|
|
||||||
def test_erasing_a_member_takes_their_private_messages(
|
def test_erasing_a_member_takes_their_private_messages(
|
||||||
app, client, db, post, owner_id, make_member, sign_in):
|
app, client, db, post, superadmin_id, make_member, sign_in):
|
||||||
"""Unlike a thread, which survives its author as "Miembro eliminado". A
|
"""Unlike a thread, which survives its author as "Miembro eliminado". A
|
||||||
two-party exchange has no remainder to preserve, and keeping half of
|
two-party exchange has no remainder to preserve, and keeping half of
|
||||||
somebody's erased correspondence is what erasure exists to prevent."""
|
somebody's erased correspondence is what erasure exists to prevent."""
|
||||||
@ -311,7 +311,7 @@ def test_erasing_a_member_takes_their_private_messages(
|
|||||||
content_type="multipart/form-data")
|
content_type="multipart/form-data")
|
||||||
name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"]
|
name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"]
|
||||||
|
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post(f"/comunidad/miembros/{maria}/eliminar")
|
post(f"/comunidad/miembros/{maria}/eliminar")
|
||||||
|
|
||||||
for table in ("conversations", "conversation_members", "messages", "attachments"):
|
for table in ("conversations", "conversation_members", "messages", "attachments"):
|
||||||
@ -320,14 +320,14 @@ def test_erasing_a_member_takes_their_private_messages(
|
|||||||
|
|
||||||
|
|
||||||
def test_erasing_a_member_removes_blocks_either_way(
|
def test_erasing_a_member_removes_blocks_either_way(
|
||||||
client, db, post, owner_id, make_member, sign_in):
|
client, db, post, superadmin_id, make_member, sign_in):
|
||||||
maria, jose = make_member("maria"), make_member("jose")
|
maria, jose = make_member("maria"), make_member("jose")
|
||||||
sign_in(maria)
|
sign_in(maria)
|
||||||
post(f"/comunidad/privados/bloquear/{jose}")
|
post(f"/comunidad/privados/bloquear/{jose}")
|
||||||
sign_in(jose)
|
sign_in(jose)
|
||||||
post(f"/comunidad/privados/bloquear/{maria}")
|
post(f"/comunidad/privados/bloquear/{maria}")
|
||||||
|
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post(f"/comunidad/miembros/{maria}/eliminar")
|
post(f"/comunidad/miembros/{maria}/eliminar")
|
||||||
|
|
||||||
assert db.execute("SELECT COUNT(*) AS n FROM blocks").fetchone()["n"] == 0
|
assert db.execute("SELECT COUNT(*) AS n FROM blocks").fetchone()["n"] == 0
|
||||||
|
|||||||
@ -181,28 +181,52 @@ def test_a_moderator_is_accepted_afterwards(old_db):
|
|||||||
|
|
||||||
|
|
||||||
def test_every_member_column_survives_the_rebuild(old_db):
|
def test_every_member_column_survives_the_rebuild(old_db):
|
||||||
"""Thirteen columns copied by name. A typo in that list is a member losing
|
"""Thirteen columns copied by name, twice over now — steps 4 and 7 each
|
||||||
their email address, or their password, or their public page."""
|
rebuild this table. A typo in either list is a member losing their email
|
||||||
before = old_db.execute(
|
address, or their password, or their public page.
|
||||||
"SELECT id, gitea_login, display_name, email, role, active, created_by "
|
|
||||||
"FROM members ORDER BY id").fetchall()
|
`role` is compared separately because step 7 deliberately changes exactly
|
||||||
|
one of them: see the test below."""
|
||||||
|
columns = "id, gitea_login, display_name, email, active, created_by"
|
||||||
|
before = old_db.execute(f"SELECT {columns} FROM members ORDER BY id").fetchall()
|
||||||
|
|
||||||
migrations.apply(old_db)
|
migrations.apply(old_db)
|
||||||
|
|
||||||
after = old_db.execute(
|
after = old_db.execute(f"SELECT {columns} FROM members ORDER BY id").fetchall()
|
||||||
"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]
|
assert [tuple(row) for row in after] == [tuple(row) for row in before]
|
||||||
|
|
||||||
|
|
||||||
def test_the_one_owner_rule_survives_the_rebuild(old_db):
|
def test_the_owner_becomes_the_superadmin(old_db):
|
||||||
"""The partial unique index is not copied with the rows, so it has to be
|
"""Step 7's one intended change to the data. The person who could already do
|
||||||
recreated by hand. Without it the database silently stops being the thing
|
everything keeps being able to, nobody types anything, and the responsable
|
||||||
that guarantees one owner, and a bug in a handler becomes two owners."""
|
chair is left empty for the association to fill."""
|
||||||
|
was_owner = old_db.execute(
|
||||||
|
"SELECT gitea_login FROM members WHERE role = 'owner'").fetchone()["gitea_login"]
|
||||||
|
|
||||||
migrations.apply(old_db)
|
migrations.apply(old_db)
|
||||||
|
|
||||||
|
assert old_db.execute(
|
||||||
|
"SELECT role FROM members WHERE gitea_login = ?", (was_owner,)
|
||||||
|
).fetchone()["role"] == "superadmin"
|
||||||
|
assert old_db.execute("SELECT COUNT(*) FROM members WHERE role = 'owner'"
|
||||||
|
).fetchone()[0] == 0
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("chair", ["superadmin", "owner"])
|
||||||
|
def test_both_single_chair_rules_survive_the_rebuild(old_db, chair):
|
||||||
|
"""Neither partial unique index is copied with the rows, so both have to be
|
||||||
|
recreated by hand. Without them the database silently stops being the thing
|
||||||
|
that guarantees one of each, and a bug in a handler becomes two."""
|
||||||
|
migrations.apply(old_db)
|
||||||
|
# The superadmin chair is already filled by the promotion; the responsable
|
||||||
|
# chair is empty, so it takes one insert to fill before the rule can bite.
|
||||||
|
if chair == "owner":
|
||||||
|
old_db.execute("INSERT INTO members (gitea_login, display_name, role) "
|
||||||
|
"VALUES ('primera', 'Primera', 'owner')")
|
||||||
|
|
||||||
with pytest.raises(sqlite3.IntegrityError):
|
with pytest.raises(sqlite3.IntegrityError):
|
||||||
old_db.execute("INSERT INTO members (gitea_login, display_name, role) "
|
old_db.execute("INSERT INTO members (gitea_login, display_name, role) "
|
||||||
"VALUES ('otro', 'Otro', 'owner')")
|
f"VALUES ('otro', 'Otro', '{chair}')")
|
||||||
|
|
||||||
|
|
||||||
def test_nothing_pointing_at_a_member_is_left_dangling(old_db):
|
def test_nothing_pointing_at_a_member_is_left_dangling(old_db):
|
||||||
@ -266,10 +290,13 @@ def test_the_app_starts_against_a_database_from_before_all_this(tmp_path):
|
|||||||
old_sql = old_sql.replace(" password_hash TEXT,\n", "")
|
old_sql = old_sql.replace(" password_hash TEXT,\n", "")
|
||||||
# …and predates the moderator role, so step 4 has a CHECK to widen here too.
|
# …and predates the moderator role, so step 4 has a CHECK to widen here too.
|
||||||
old_sql = old_sql.replace(
|
old_sql = old_sql.replace(
|
||||||
" role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'moderator',\n"
|
" role TEXT NOT NULL CHECK (role IN ('superadmin', 'owner', 'admin', 'moderator',\n"
|
||||||
" 'user', 'tombstone')),",
|
" 'user', 'tombstone')),",
|
||||||
" role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')),")
|
" role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')),")
|
||||||
assert "CHECK (role IN ('owner', 'admin', 'user', 'tombstone'))" in old_sql
|
assert "CHECK (role IN ('owner', 'admin', 'user', 'tombstone'))" in old_sql
|
||||||
|
old_sql = old_sql.replace(
|
||||||
|
"CREATE UNIQUE INDEX IF NOT EXISTS members_one_superadmin\n"
|
||||||
|
" ON members(role) WHERE role = 'superadmin';\n\n", "")
|
||||||
old_sql += """
|
old_sql += """
|
||||||
CREATE TABLE gitea_tokens (
|
CREATE TABLE gitea_tokens (
|
||||||
member_id INTEGER PRIMARY KEY REFERENCES members(id) ON DELETE CASCADE,
|
member_id INTEGER PRIMARY KEY REFERENCES members(id) ON DELETE CASCADE,
|
||||||
@ -359,3 +386,57 @@ def test_step_six_drops_the_category_columns_and_keeps_the_rows(tmp_path):
|
|||||||
assert db.execute("PRAGMA user_version").fetchone()[0] == max(
|
assert db.execute("PRAGMA user_version").fetchone()[0] == max(
|
||||||
number for number, _, _ in migrations.STEPS)
|
number for number, _, _ in migrations.STEPS)
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_restart_does_not_demote_the_superadmin(tmp_path):
|
||||||
|
"""The one that would have shipped silently.
|
||||||
|
|
||||||
|
`_seed_superadmin` ends with `ON CONFLICT(gitea_login) DO UPDATE SET role =
|
||||||
|
…`. While owner was the top of the tree that line was right. Left as it was
|
||||||
|
after step 7, it would have matched BOARD_OWNER's login on every container
|
||||||
|
restart and set the role back to `owner` — a privilege *reduction* arriving
|
||||||
|
at no particular moment, caused by nothing anybody did, and leaving
|
||||||
|
`members_one_superadmin` free for somebody else to take the chair.
|
||||||
|
|
||||||
|
Nothing about a single start-up catches that; it takes a second one.
|
||||||
|
"""
|
||||||
|
from apps.board.app import create_app
|
||||||
|
from apps.board.db import connect
|
||||||
|
|
||||||
|
path = str(tmp_path / "board.db")
|
||||||
|
settings = {"SECRET_KEY": "x", "DB_PATH": path, "OWNER_LOGIN": "pablo",
|
||||||
|
"UPLOAD_DIR": str(tmp_path / "uploads"), "TESTING": True}
|
||||||
|
|
||||||
|
create_app(settings)
|
||||||
|
create_app(settings) # the restart
|
||||||
|
create_app(settings) # and another, because containers do that
|
||||||
|
|
||||||
|
db = connect(path)
|
||||||
|
rows = db.execute(
|
||||||
|
"SELECT gitea_login, role FROM members WHERE role IN ('superadmin', 'owner')"
|
||||||
|
).fetchall()
|
||||||
|
assert [(r["gitea_login"], r["role"]) for r in rows] == [("pablo", "superadmin")]
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_second_superadmin_is_not_seeded_over_the_first(tmp_path):
|
||||||
|
"""Changing BOARD_OWNER must not hand the platform to whoever can edit the
|
||||||
|
environment — a quieter escalation than it looks, since editing a compose
|
||||||
|
file draws far less attention than asking for access."""
|
||||||
|
from apps.board.app import create_app
|
||||||
|
from apps.board.db import connect
|
||||||
|
|
||||||
|
path = str(tmp_path / "board.db")
|
||||||
|
base = {"SECRET_KEY": "x", "DB_PATH": path,
|
||||||
|
"UPLOAD_DIR": str(tmp_path / "uploads"), "TESTING": True}
|
||||||
|
|
||||||
|
create_app({**base, "OWNER_LOGIN": "pablo"})
|
||||||
|
create_app({**base, "OWNER_LOGIN": "intruso"})
|
||||||
|
|
||||||
|
db = connect(path)
|
||||||
|
assert db.execute(
|
||||||
|
"SELECT gitea_login FROM members WHERE role = 'superadmin'"
|
||||||
|
).fetchone()["gitea_login"] == "pablo"
|
||||||
|
assert db.execute(
|
||||||
|
"SELECT COUNT(*) FROM members WHERE gitea_login = 'intruso'").fetchone()[0] == 0
|
||||||
|
db.close()
|
||||||
|
|||||||
@ -217,3 +217,40 @@ def test_signing_in_sets_the_hint_and_signing_out_clears_it(client, db, post, ma
|
|||||||
signed_out = post("/comunidad/logout")
|
signed_out = post("/comunidad/logout")
|
||||||
assert any("vl_sesion=;" in header or "vl_sesion=\"\"" in header
|
assert any("vl_sesion=;" in header or "vl_sesion=\"\"" in header
|
||||||
for header in signed_out.headers.get_all("Set-Cookie"))
|
for header in signed_out.headers.get_all("Set-Cookie"))
|
||||||
|
|
||||||
|
|
||||||
|
# --- the tier above admin -------------------------------------------------
|
||||||
|
|
||||||
|
def test_the_superadmin_sees_gestion(nav, superadmin_id):
|
||||||
|
"""The regression this file exists for, one tier higher.
|
||||||
|
|
||||||
|
`base.html` asked `g.member.role in ('owner', 'admin')`, which was right
|
||||||
|
until a role appeared above both — and then Gestión vanished from the
|
||||||
|
navigation of the one account that owns every screen on it. 622 tests
|
||||||
|
passed while it was broken, because every one of them signed in as an
|
||||||
|
admin or below.
|
||||||
|
"""
|
||||||
|
body = nav(superadmin_id)
|
||||||
|
assert "Gestión" in body
|
||||||
|
assert "/comunidad/gestion" in body
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("role", ["superadmin", "owner", "admin"])
|
||||||
|
def test_gestion_opens_for_every_role_that_can_see_it(role, client, db,
|
||||||
|
superadmin_id, make_member,
|
||||||
|
sign_in):
|
||||||
|
"""Seeing the link and reaching the page are two different checks, and a
|
||||||
|
role that passes one and fails the other is the worst of both."""
|
||||||
|
member_id = superadmin_id if role == "superadmin" else make_member("x", role=role)
|
||||||
|
sign_in(member_id)
|
||||||
|
assert client.get("/comunidad/gestion").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_public_strip_offers_gestion_to_the_superadmin(client, superadmin_id,
|
||||||
|
sign_in):
|
||||||
|
"""`sesion.json` draws the bar on vienalatina.com from its own list, so it
|
||||||
|
is a second place the same rule can be got wrong."""
|
||||||
|
sign_in(superadmin_id)
|
||||||
|
labels = [s["label"] for s in
|
||||||
|
client.get("/comunidad/sesion.json").get_json()["sections"]]
|
||||||
|
assert "Gestión" in labels
|
||||||
|
|||||||
@ -121,13 +121,13 @@ def test_the_bio_cannot_smuggle_html(client, published):
|
|||||||
|
|
||||||
@pytest.mark.parametrize("name", ["de", "pt-br", "categories", "admin",
|
@pytest.mark.parametrize("name", ["de", "pt-br", "categories", "admin",
|
||||||
"comunidad", "robots", "DE"])
|
"comunidad", "robots", "DE"])
|
||||||
def test_a_name_the_site_already_uses_is_refused(client, db, post, owner_id,
|
def test_a_name_the_site_already_uses_is_refused(client, db, post, superadmin_id,
|
||||||
sign_in, name, monkeypatch):
|
sign_in, name, monkeypatch):
|
||||||
"""Not because it would break the site — Caddy gives the static site every
|
"""Not because it would break the site — Caddy gives the static site every
|
||||||
collision — but because their page would never load and nobody would know
|
collision — but because their page would never load and nobody would know
|
||||||
why."""
|
why."""
|
||||||
monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None)
|
monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None)
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post("/comunidad/miembros/nuevo", {
|
post("/comunidad/miembros/nuevo", {
|
||||||
"login": name, "display_name": "X", "email": "x@example.com", "role": "user",
|
"login": name, "display_name": "X", "email": "x@example.com", "role": "user",
|
||||||
})
|
})
|
||||||
@ -187,7 +187,7 @@ def test_a_board_picture_cannot_be_served_as_a_profile_photo(
|
|||||||
|
|
||||||
|
|
||||||
def test_erasing_a_member_takes_the_photo_off_disk(
|
def test_erasing_a_member_takes_the_photo_off_disk(
|
||||||
app, client, db, post, owner_id, sign_in, published):
|
app, client, db, post, superadmin_id, sign_in, published):
|
||||||
member_id = published()
|
member_id = published()
|
||||||
sign_in(member_id)
|
sign_in(member_id)
|
||||||
post("/comunidad/mi-perfil", {"published": "on", "bio": "Hola",
|
post("/comunidad/mi-perfil", {"published": "on", "bio": "Hola",
|
||||||
@ -197,7 +197,7 @@ def test_erasing_a_member_takes_the_photo_off_disk(
|
|||||||
(member_id,)).fetchone()["photo_name"]
|
(member_id,)).fetchone()["photo_name"]
|
||||||
assert (Path(app.config["UPLOAD_DIR"]) / name).exists()
|
assert (Path(app.config["UPLOAD_DIR"]) / name).exists()
|
||||||
|
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post(f"/comunidad/miembros/{member_id}/eliminar")
|
post(f"/comunidad/miembros/{member_id}/eliminar")
|
||||||
|
|
||||||
assert not (Path(app.config["UPLOAD_DIR"]) / name).exists()
|
assert not (Path(app.config["UPLOAD_DIR"]) / name).exists()
|
||||||
@ -264,7 +264,7 @@ def test_their_page_links_out_to_the_public_one_when_there_is_one(
|
|||||||
assert 'href="/maria"' in client.get("/comunidad/miembro/maria").get_data(as_text=True)
|
assert 'href="/maria"' in client.get("/comunidad/miembro/maria").get_data(as_text=True)
|
||||||
|
|
||||||
|
|
||||||
def test_an_erased_members_name_is_not_a_link(client, post, owner_id,
|
def test_an_erased_members_name_is_not_a_link(client, post, superadmin_id,
|
||||||
make_member, sign_in):
|
make_member, sign_in):
|
||||||
"""The one name with no page behind it. An erased member's writing is
|
"""The one name with no page behind it. An erased member's writing is
|
||||||
reassigned to the tombstone, which is not a person and has nothing to
|
reassigned to the tombstone, which is not a person and has nothing to
|
||||||
@ -274,7 +274,7 @@ def test_an_erased_members_name_is_not_a_link(client, post, owner_id,
|
|||||||
sign_in(maria)
|
sign_in(maria)
|
||||||
post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"})
|
post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"})
|
||||||
|
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post(f"/comunidad/miembros/{maria}/eliminar")
|
post(f"/comunidad/miembros/{maria}/eliminar")
|
||||||
|
|
||||||
body = client.get("/comunidad/muro").get_data(as_text=True)
|
body = client.get("/comunidad/muro").get_data(as_text=True)
|
||||||
|
|||||||
@ -101,8 +101,8 @@ def test_the_count_and_my_own_mark_show_on_the_page(client, post, thread,
|
|||||||
|
|
||||||
|
|
||||||
def test_reacting_to_something_that_is_gone_is_a_404(db, post, thread,
|
def test_reacting_to_something_that_is_gone_is_a_404(db, post, thread,
|
||||||
owner_id, make_member, sign_in):
|
superadmin_id, make_member, sign_in):
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post(f"/comunidad/tema/{thread}/eliminar")
|
post(f"/comunidad/tema/{thread}/eliminar")
|
||||||
|
|
||||||
sign_in(make_member("maria"))
|
sign_in(make_member("maria"))
|
||||||
@ -138,13 +138,13 @@ def test_the_button_comes_back_to_the_comment_it_was_pressed_on(
|
|||||||
assert response.headers["Location"].endswith(f"/comunidad/tema/{thread}#c1")
|
assert response.headers["Location"].endswith(f"/comunidad/tema/{thread}#c1")
|
||||||
|
|
||||||
|
|
||||||
def test_erasing_a_member_takes_their_reactions(db, post, thread, owner_id,
|
def test_erasing_a_member_takes_their_reactions(db, post, thread, superadmin_id,
|
||||||
make_member, sign_in):
|
make_member, sign_in):
|
||||||
maria = make_member("maria")
|
maria = make_member("maria")
|
||||||
sign_in(maria)
|
sign_in(maria)
|
||||||
react(post, "thread", thread)
|
react(post, "thread", thread)
|
||||||
|
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post(f"/comunidad/miembros/{maria}/eliminar")
|
post(f"/comunidad/miembros/{maria}/eliminar")
|
||||||
|
|
||||||
assert db.execute("SELECT COUNT(*) AS n FROM reactions").fetchone()["n"] == 0
|
assert db.execute("SELECT COUNT(*) AS n FROM reactions").fetchone()["n"] == 0
|
||||||
|
|||||||
@ -364,7 +364,7 @@ def test_an_approved_one_cannot_be_edited_or_withdrawn(
|
|||||||
# --- erasure --------------------------------------------------------------
|
# --- erasure --------------------------------------------------------------
|
||||||
|
|
||||||
def test_erasing_the_author_takes_their_submissions_and_photos(
|
def test_erasing_the_author_takes_their_submissions_and_photos(
|
||||||
app, repo, db, post, owner_id, maria, sign_in):
|
app, repo, db, post, superadmin_id, maria, sign_in):
|
||||||
"""A submission is private writing, so it goes the way private messages do.
|
"""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
|
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."""
|
their name in a commit that is not ours to rewrite from here."""
|
||||||
@ -372,14 +372,14 @@ def test_erasing_the_author_takes_their_submissions_and_photos(
|
|||||||
propose(post, picture=(io.BytesIO(PNG), "feria.png"))
|
propose(post, picture=(io.BytesIO(PNG), "feria.png"))
|
||||||
stored = only_submission(db)["photo_name"]
|
stored = only_submission(db)["photo_name"]
|
||||||
|
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post(f"/comunidad/miembros/{maria}/eliminar")
|
post(f"/comunidad/miembros/{maria}/eliminar")
|
||||||
|
|
||||||
assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0
|
assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0
|
||||||
assert not (Path(app.config["UPLOAD_DIR"]) / stored).exists()
|
assert not (Path(app.config["UPLOAD_DIR"]) / stored).exists()
|
||||||
|
|
||||||
|
|
||||||
def test_erasing_a_reviewer_keeps_the_submission(db, post, owner_id, maria,
|
def test_erasing_a_reviewer_keeps_the_submission(db, post, superadmin_id, maria,
|
||||||
make_member, sign_in):
|
make_member, sign_in):
|
||||||
"""Who reviewed something is a fact about the submission, not personal data
|
"""Who reviewed something is a fact about the submission, not personal data
|
||||||
of the reviewer, so the name goes and the row stays."""
|
of the reviewer, so the name goes and the row stays."""
|
||||||
@ -390,7 +390,7 @@ def test_erasing_a_reviewer_keeps_the_submission(db, post, owner_id, maria,
|
|||||||
sign_in(reviewer)
|
sign_in(reviewer)
|
||||||
post(f"/comunidad/publicaciones/{submission_id}/rechazar", {"note": "Falta el dónde."})
|
post(f"/comunidad/publicaciones/{submission_id}/rechazar", {"note": "Falta el dónde."})
|
||||||
|
|
||||||
sign_in(owner_id)
|
sign_in(superadmin_id)
|
||||||
post(f"/comunidad/miembros/{reviewer}/eliminar")
|
post(f"/comunidad/miembros/{reviewer}/eliminar")
|
||||||
|
|
||||||
row = only_submission(db)
|
row = only_submission(db)
|
||||||
|
|||||||
260
apps/board/tests/test_tools.py
Normal file
260
apps/board/tests/test_tools.py
Normal file
@ -0,0 +1,260 @@
|
|||||||
|
"""The three screens the superadministrator gets, and the identity half.
|
||||||
|
|
||||||
|
Grouped in one file because they are one phase and share one question: who may
|
||||||
|
open this, and does it tell the truth about the running system.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from apps.board import activity, identity
|
||||||
|
|
||||||
|
SCREENS = {
|
||||||
|
"/comunidad/gestion/identidad": "superadmin",
|
||||||
|
"/comunidad/gestion/estado": "superadmin",
|
||||||
|
"/comunidad/gestion/registro": "superadmin",
|
||||||
|
"/comunidad/gestion/medios": "admin",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def boss(superadmin_id, sign_in):
|
||||||
|
sign_in(superadmin_id)
|
||||||
|
return superadmin_id
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("url", sorted(SCREENS))
|
||||||
|
def test_every_screen_opens_for_the_superadmin(client, boss, url, repo):
|
||||||
|
assert client.get(url).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("url,needs", sorted(SCREENS.items()))
|
||||||
|
def test_each_screen_refuses_the_roles_below_it(client, make_member, sign_in,
|
||||||
|
url, needs, repo):
|
||||||
|
"""Medios is open to admins — they are the people who upload, and the worst
|
||||||
|
an admin can do there is remove a picture from a post they could already
|
||||||
|
have edited. The other three are the platform's."""
|
||||||
|
# Everything above the rank passes too, which is what `is_at_least` means.
|
||||||
|
allowed = {"superadmin": set(), "admin": {"admin", "owner"}}[needs]
|
||||||
|
for role in ("user", "moderator", "admin", "owner"):
|
||||||
|
sign_in(make_member(f"persona-{role}", role=role))
|
||||||
|
expected = 200 if role in allowed else 403
|
||||||
|
assert client.get(url).status_code == expected, (url, role)
|
||||||
|
|
||||||
|
|
||||||
|
# --- identity -------------------------------------------------------------
|
||||||
|
|
||||||
|
def test_the_identity_round_trips_all_three_languages(client, db, post, boss, repo):
|
||||||
|
post("/comunidad/gestion/identidad", {
|
||||||
|
"name-es": "Viena Latina", "tagline-es": "La comunidad en Viena.",
|
||||||
|
"name-de": "Wien Latina", "tagline-de": "Die Community in Wien.",
|
||||||
|
"tagline-pt-br": "A comunidade em Viena.",
|
||||||
|
"social-instagram": "https://instagram.com/vienalatina",
|
||||||
|
"email": "hola@vienalatina.com", "city": "Wien",
|
||||||
|
"footer_text": "Asociación Viena Latina",
|
||||||
|
})
|
||||||
|
|
||||||
|
body = client.get("/comunidad/gestion/identidad").get_data(as_text=True)
|
||||||
|
for value in ("Wien Latina", "Die Community in Wien.",
|
||||||
|
"A comunidade em Viena.", "https://instagram.com/vienalatina",
|
||||||
|
"hola@vienalatina.com", "Asociación Viena Latina"):
|
||||||
|
assert value in body, value
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_untouched_language_is_not_written_at_all(client, db, post, boss, repo):
|
||||||
|
"""A file repeating config.yaml's own values back at it would make the
|
||||||
|
fallback meaningless and freeze today's defaults for good."""
|
||||||
|
post("/comunidad/gestion/identidad", {"tagline-es": "Sólo esto."})
|
||||||
|
|
||||||
|
names = json.loads(db.execute("SELECT names_json FROM site").fetchone()[0])
|
||||||
|
assert names == {"es": {"name": "", "tagline": "Sólo esto."}}
|
||||||
|
yaml = repo.files["data/site.yaml"].decode("utf-8")
|
||||||
|
assert "de:" not in yaml and "pt-br:" not in yaml
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_social_link_that_is_not_https_is_refused(client, db, post, boss, repo):
|
||||||
|
"""These render in the footer of every public page. `javascript:` in an href
|
||||||
|
is a script running on vienalatina.com."""
|
||||||
|
response = post("/comunidad/gestion/identidad",
|
||||||
|
{"social-instagram": "javascript:alert(1)"},
|
||||||
|
follow_redirects=True)
|
||||||
|
|
||||||
|
assert "tiene que empezar por https" in response.get_data(as_text=True)
|
||||||
|
assert db.execute("SELECT COUNT(*) AS n FROM site").fetchone()["n"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_tagline_is_flattened_to_one_line(client, db, post, boss, repo):
|
||||||
|
"""A newline inside og:description is a share card that renders raggedly in
|
||||||
|
some readers and truncated in others."""
|
||||||
|
post("/comunidad/gestion/identidad", {"tagline-es": "Una línea.\n\nY otra."})
|
||||||
|
|
||||||
|
names = json.loads(db.execute("SELECT names_json FROM site").fetchone()[0])
|
||||||
|
assert names["es"]["tagline"] == "Una línea. Y otra."
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_yaml_is_what_hugo_reads(client, post, boss, repo):
|
||||||
|
post("/comunidad/gestion/identidad", {
|
||||||
|
"name-es": "Viena Latina", "tagline-es": "La comunidad.",
|
||||||
|
"social-instagram": "https://instagram.com/vl",
|
||||||
|
"social-bluesky": "https://bsky.app/profile/vl",
|
||||||
|
"email": "hola@vienalatina.com", "city": "Wien",
|
||||||
|
})
|
||||||
|
|
||||||
|
yaml = repo.files["data/site.yaml"].decode("utf-8")
|
||||||
|
assert ' name: "Viena Latina"' in yaml
|
||||||
|
assert ' tagline: "La comunidad."' in yaml
|
||||||
|
# sameAs is a flat list of URLs: the names of the networks appear nowhere in
|
||||||
|
# the schema, only the addresses.
|
||||||
|
assert 'sameAs:\n - "https://instagram.com/vl"' in yaml
|
||||||
|
assert 'email: "hola@vienalatina.com"' in yaml
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_quote_in_a_name_cannot_break_the_file(client, post, boss, repo):
|
||||||
|
post("/comunidad/gestion/identidad", {"name-es": 'Viena "La" Latina\\'})
|
||||||
|
|
||||||
|
yaml = repo.files["data/site.yaml"].decode("utf-8")
|
||||||
|
assert r'name: "Viena \"La\" Latina\\"' in yaml
|
||||||
|
|
||||||
|
|
||||||
|
# --- the activity log -----------------------------------------------------
|
||||||
|
|
||||||
|
def test_the_acts_that_change_power_are_recorded(client, db, post, boss, make_member):
|
||||||
|
maria = make_member("maria")
|
||||||
|
post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"})
|
||||||
|
post(f"/comunidad/miembros/{maria}/estado", {"active": "0"})
|
||||||
|
|
||||||
|
rows = db.execute(
|
||||||
|
"SELECT action, object, detail FROM activity ORDER BY id").fetchall()
|
||||||
|
|
||||||
|
assert [(r["action"], r["object"]) for r in rows] == [
|
||||||
|
("role.changed", "Maria"), ("member.suspended", "Maria")]
|
||||||
|
assert "Miembro → Moderador" in rows[0]["detail"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_log_survives_the_person_who_wrote_it(client, db, post, boss, make_member):
|
||||||
|
"""The row stays and the name goes. That a role was changed is the
|
||||||
|
association's record; whose name was on it is the erased person's data."""
|
||||||
|
admin_id = make_member("admina", role="admin")
|
||||||
|
maria = make_member("maria")
|
||||||
|
sign_in_as = client.session_transaction
|
||||||
|
with sign_in_as() as session:
|
||||||
|
session["member_id"] = admin_id
|
||||||
|
session["csrf"] = "token-for-tests"
|
||||||
|
post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"})
|
||||||
|
|
||||||
|
with sign_in_as() as session:
|
||||||
|
session["member_id"] = boss
|
||||||
|
post(f"/comunidad/miembros/{admin_id}/eliminar")
|
||||||
|
|
||||||
|
rows = db.execute("SELECT actor_id, action FROM activity "
|
||||||
|
"WHERE action = 'role.changed'").fetchall()
|
||||||
|
assert len(rows) == 1
|
||||||
|
assert rows[0]["actor_id"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_broken_log_does_not_break_the_thing_it_records(app, db, boss,
|
||||||
|
make_member, monkeypatch):
|
||||||
|
"""An administrator who could not be appointed because the note about it
|
||||||
|
could not be saved is a worse outcome than a gap in the notes."""
|
||||||
|
with app.test_request_context():
|
||||||
|
monkeypatch.setattr(activity, "get_db",
|
||||||
|
lambda: (_ for _ in ()).throw(RuntimeError("no")))
|
||||||
|
activity.log("role.changed", "Maria") # must not raise
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_registro_reads_as_sentences(client, db, post, boss, make_member):
|
||||||
|
maria = make_member("maria")
|
||||||
|
post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"})
|
||||||
|
|
||||||
|
body = client.get("/comunidad/gestion/registro").get_data(as_text=True)
|
||||||
|
|
||||||
|
assert "cambió el rol de Maria" in body
|
||||||
|
|
||||||
|
|
||||||
|
# --- the media library ----------------------------------------------------
|
||||||
|
|
||||||
|
def test_an_orphan_is_named_as_one_and_a_used_picture_is_not(client, db, boss, repo):
|
||||||
|
repo.files["static/uploads/usada-aaaaaa.jpg"] = b"\xff\xd8\xff"
|
||||||
|
repo.files["static/uploads/huerfana-bbbbbb.jpg"] = b"\xff\xd8\xff"
|
||||||
|
db.execute("""INSERT INTO content_cache (path, sha, title, date, image)
|
||||||
|
VALUES ('content/post/x.es.md', 'a', 'Un artículo', '2026-01-01',
|
||||||
|
'/uploads/usada-aaaaaa.jpg')""")
|
||||||
|
|
||||||
|
body = client.get("/comunidad/gestion/medios").get_data(as_text=True)
|
||||||
|
|
||||||
|
assert "1 no la usa nadie" in body
|
||||||
|
assert "Un artículo" in body
|
||||||
|
# And the orphan is first, because it is the only row anybody has to act on.
|
||||||
|
assert body.index("huerfana-bbbbbb") < body.index("usada-aaaaaa")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_picture_in_use_cannot_be_deleted(client, db, post, boss, repo):
|
||||||
|
repo.files["static/uploads/usada-aaaaaa.jpg"] = b"\xff\xd8\xff"
|
||||||
|
db.execute("""INSERT INTO content_cache (path, sha, title, date, image)
|
||||||
|
VALUES ('content/post/x.es.md', 'a', 'Un artículo', '2026-01-01',
|
||||||
|
'/uploads/usada-aaaaaa.jpg')""")
|
||||||
|
|
||||||
|
response = post("/comunidad/gestion/medios/usada-aaaaaa.jpg/eliminar",
|
||||||
|
follow_redirects=True)
|
||||||
|
|
||||||
|
assert "está en uso" in response.get_data(as_text=True)
|
||||||
|
assert "static/uploads/usada-aaaaaa.jpg" in repo.files
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_orphan_is_deleted_and_logged(client, db, post, boss, repo):
|
||||||
|
repo.files["static/uploads/huerfana-bbbbbb.jpg"] = b"\xff\xd8\xff"
|
||||||
|
|
||||||
|
post("/comunidad/gestion/medios/huerfana-bbbbbb.jpg/eliminar",
|
||||||
|
{"sha": repo._sha(b"\xff\xd8\xff")})
|
||||||
|
|
||||||
|
assert "static/uploads/huerfana-bbbbbb.jpg" not in repo.files
|
||||||
|
assert db.execute("SELECT action, object FROM activity").fetchone()["object"] == \
|
||||||
|
"huerfana-bbbbbb.jpg"
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_editor_records_which_picture_a_post_uses(client, repo, db, post,
|
||||||
|
superadmin_id, sign_in):
|
||||||
|
"""Which is what makes "does anything use this?" a query rather than a
|
||||||
|
re-read of every post's frontmatter from the git server.
|
||||||
|
|
||||||
|
The cache is filled by the listing rather than by the write — it is keyed on
|
||||||
|
the sha the git server reports — so opening Contenido is the step that puts
|
||||||
|
the row there."""
|
||||||
|
sign_in(superadmin_id)
|
||||||
|
post("/comunidad/contenido/post/nuevo",
|
||||||
|
{"title": "Con foto", "body": "Texto.", "date": "2026-10-03",
|
||||||
|
"image": "/uploads/foto-abcdef.jpg"})
|
||||||
|
client.get("/comunidad/contenido/post")
|
||||||
|
|
||||||
|
row = db.execute("SELECT image FROM content_cache").fetchone()
|
||||||
|
assert row["image"] == "/uploads/foto-abcdef.jpg"
|
||||||
|
|
||||||
|
|
||||||
|
# --- the status screen ----------------------------------------------------
|
||||||
|
|
||||||
|
def test_the_status_screen_says_when_the_token_cannot_write(client, boss, monkeypatch):
|
||||||
|
""""Present" was never the problem. A token with the wrong scope is
|
||||||
|
non-empty, looks fine, and cannot write a single file — which is exactly the
|
||||||
|
configuration that broke publishing for three phases."""
|
||||||
|
from apps.board import gitea, status
|
||||||
|
monkeypatch.setattr(status.gitea, "list_directory",
|
||||||
|
lambda *a, **k: (_ for _ in ()).throw(
|
||||||
|
gitea.GiteaError("403: sin permiso de repositorio")))
|
||||||
|
|
||||||
|
body = client.get("/comunidad/gestion/estado").get_data(as_text=True)
|
||||||
|
|
||||||
|
assert "no puede leer el repositorio" in body
|
||||||
|
assert "sin permiso de repositorio" in body
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_status_screen_counts_what_is_there(client, db, boss, make_member, repo):
|
||||||
|
make_member("maria")
|
||||||
|
make_member("luisa", role="moderator")
|
||||||
|
|
||||||
|
body = client.get("/comunidad/gestion/estado").get_data(as_text=True)
|
||||||
|
|
||||||
|
assert "3 miembros" in body # the superadministrator and the two
|
||||||
|
assert "2 con algún cargo" in body # superadministrator + moderator
|
||||||
@ -521,43 +521,75 @@ has been archiving air" are otherwise the same empty line.
|
|||||||
|
|
||||||
### 11.6 Who can do what
|
### 11.6 Who can do what
|
||||||
|
|
||||||
| | Responsable | Administrador | Moderador | Miembro |
|
Five roles, and **two of them are single chairs held by the database** rather
|
||||||
|---|---|---|---|---|
|
than by the application: a partial unique index each, so a bug in a handler
|
||||||
| Wall: post, comment, edit own | ✓ | ✓ | ✓ | ✓ |
|
cannot produce a second of either.
|
||||||
| Private messages, own profile | ✓ | ✓ | ✓ | ✓ |
|
|
||||||
| Propose a public post | ✓ | ✓ | ✓ | ✓ |
|
| | Superadministrador | Responsable | Administrador | Moderador | Miembro |
|
||||||
| Publish a public post directly | ✓ | ✓ | ✓ | — |
|
|---|---|---|---|---|---|
|
||||||
| Approve or return a proposal | ✓ | ✓ | ✓ | — |
|
| Wall: post, comment, edit own | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||||
| Edit and delete published posts | ✓ | ✓ | ✓ | — |
|
| Private messages, own profile | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||||
| Static pages of the site | ✓ | ✓ | — | — |
|
| Propose a public post | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||||
| Delete any wall post | ✓ | ✓ | — | — |
|
| Publish a public post directly | ✓ | ✓ | ✓ | ✓ | — |
|
||||||
| Edit someone else's post | — | — | — | — |
|
| Approve or return a proposal | ✓ | ✓ | ✓ | ✓ | — |
|
||||||
| Pin and close threads | ✓ | ✓ | — | — |
|
| Edit and delete published posts | ✓ | ✓ | ✓ | ✓ | — |
|
||||||
| Create members and moderators | ✓ | ✓ | — | — |
|
| Static pages of the site | ✓ | ✓ | ✓ | — | — |
|
||||||
| Change a role (below admin) | ✓ | ✓ | — | — |
|
| Delete any wall post, pin and close | ✓ | ✓ | ✓ | — | — |
|
||||||
| Create admins, promote to admin | ✓ | — | — | — |
|
| Edit someone else's post | — | — | — | — | — |
|
||||||
| Suspend a member or moderator | ✓ | ✓ | — | — |
|
| Create members and moderators | ✓ | ✓ | ✓ | — | — |
|
||||||
| Suspend an admin | ✓ | — | — | — |
|
| Change a role below admin | ✓ | ✓ | ✓ | — | — |
|
||||||
| Transfer ownership, erase a member | ✓ | — | — | — |
|
| Suspend a member or moderator | ✓ | ✓ | ✓ | — | — |
|
||||||
|
| Erase a member | ✓ | ✓ | — | — | — |
|
||||||
|
| Name the responsable | ✓ | ✓ | — | — | — |
|
||||||
|
| **Create, promote, suspend an admin** | ✓ | — | — | — | — |
|
||||||
|
| **Marca: the look and the identity** | ✓ | — | — | — | — |
|
||||||
|
| **Estado del sistema, Registro** | ✓ | — | — | — | — |
|
||||||
|
| **Hand the platform on** | ✓ | — | — | — | — |
|
||||||
|
|
||||||
|
**The two chairs do different jobs, and that is the point.** The
|
||||||
|
*superadministrador* runs the **platform**: admin accounts, the look, the
|
||||||
|
identity, the system tools. The *responsable* runs the **association**: members,
|
||||||
|
moderators, invitations, erasure. Installed for a second organisation, the first
|
||||||
|
is whoever maintains the box and the second is their president — which is what
|
||||||
|
makes the responsable chair safe to hand to a customer, and why an admin account
|
||||||
|
is not theirs to grant.
|
||||||
|
|
||||||
|
**Neither chair can be touched by anybody, including themselves.** The
|
||||||
|
superadministrator because there is nothing above them; the responsable because
|
||||||
|
the chair belongs to the association, and a platform administrator quietly
|
||||||
|
removing the president of the organisation they host is exactly the move this
|
||||||
|
separation exists to prevent. Each steps down by handing their own chair on, and
|
||||||
|
whoever gives one up becomes an administrator — there is no role above the one
|
||||||
|
they just gave away.
|
||||||
|
|
||||||
**A moderator has no power over people.** They decide what the public reads and
|
**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
|
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
|
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.
|
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
|
Both rules live in one place each — `may_create` and `may_manage` in
|
||||||
in one place (`may_create` in `apps/board/members.py`) and the role form on
|
`apps/board/members.py` — and the role picker on a member's page is built from
|
||||||
*Miembros* checks it twice: once for reaching the person, once for the role being
|
`assignable_roles(actor)`, the same predicate, so it can never offer a role the
|
||||||
given.
|
handler will refuse. "This role or anything above it" is `is_at_least` in
|
||||||
|
`apps/board/security.py`, over one ordered `LADDER`: it replaced seven literal
|
||||||
|
tuples scattered through the app, each of which had silently excluded the
|
||||||
|
superadministrator the moment a tier appeared above owner.
|
||||||
|
|
||||||
Nobody edits anyone else's words, administrators included. Taking a post down is
|
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
|
visible to the person who wrote it; rewriting it is not, and an admin who could
|
||||||
do that could leave a sentence attributed to a member who never wrote it.
|
do that could leave a sentence attributed to a member who never wrote it.
|
||||||
|
|
||||||
There is exactly one owner, and the database enforces it with a unique index
|
**On upgrade**, migration 7 promotes the existing owner — Pablo — to
|
||||||
rather than trusting the application to remember. The owner cannot be suspended
|
superadministrator and leaves the responsable chair empty. Nothing is erased and
|
||||||
or demoted by anyone, themselves included — to step down, transfer ownership to
|
nobody has to type anything: a superadministrator passes every check an owner
|
||||||
an admin.
|
passed. The chair is filled from *Miembros* → somebody's page → **Nombrar
|
||||||
|
responsable** whenever there is somebody to put in it.
|
||||||
|
|
||||||
|
`BOARD_OWNER` keeps its name and now seeds a superadministrator. It refuses to
|
||||||
|
change an existing one, so editing the environment cannot hand anybody the
|
||||||
|
platform — and the `ON CONFLICT` clause that writes the role is pinned to
|
||||||
|
`superadmin` for a reason worth knowing: left saying `owner`, it would have
|
||||||
|
demoted the superadministrator on every container restart.
|
||||||
|
|
||||||
### 11.7 Personal data
|
### 11.7 Personal data
|
||||||
|
|
||||||
@ -1013,7 +1045,7 @@ Choosing a picture shows a thumbnail with its name and size before anything is
|
|||||||
uploaded. That is the one reason `blob:` is in the `img-src` policy — a handle to
|
uploaded. That is the one reason `blob:` is in the `img-src` policy — a handle to
|
||||||
bytes already in the page, which reaches no network.
|
bytes already in the page, which reaches no network.
|
||||||
|
|
||||||
### 11.18 Marca: the admin owns the look
|
### 11.18 Marca: the superadministrator owns the look
|
||||||
|
|
||||||
*Gestión* → **Marca**, admins only. Colours, a logo and a favicon for both
|
*Gestión* → **Marca**, admins only. Colours, a logo and a favicon for both
|
||||||
halves of the site, with an *Avanzado* fold holding every token as a text field
|
halves of the site, with an *Avanzado* fold holding every token as a text field
|
||||||
@ -1067,6 +1099,21 @@ block is where they see them, restyled by `board.js` setting the custom
|
|||||||
properties on that one element (a DOM write, not an inline `style` attribute,
|
properties on that one element (a DOM write, not an inline `style` attribute,
|
||||||
which is what makes it work under a policy with no `'unsafe-inline'`).
|
which is what makes it work under a policy with no `'unsafe-inline'`).
|
||||||
|
|
||||||
|
**A typeface and the corners.** Four system-font stacks — nothing is downloaded
|
||||||
|
from anywhere, which is deliberate and a GDPR matter: a stylesheet that pulls a
|
||||||
|
font from fonts.gstatic.com tells Google the IP address of everyone who reads
|
||||||
|
the site. A fifth option takes an uploaded `.woff2`, self-hosted, sniffed by its
|
||||||
|
`wOF2` signature and capped at 400 KB; it is named ahead of the old stack in the
|
||||||
|
`font-family`, so a font that fails to load leaves a readable site rather than a
|
||||||
|
browser default. The screen carries a fold-out warning about missing accented
|
||||||
|
glyphs, file size, synthesised bold — and about **licensing**, which is the part
|
||||||
|
with a real cost: a font is software, a desktop licence is not a webfont
|
||||||
|
licence, and that liability follows the platform to every organisation it is
|
||||||
|
installed for. SIL OFL and Apache-2.0 are the safe ones.
|
||||||
|
|
||||||
|
Roundness is one setting driving all four `--radius-*` tokens, because a site
|
||||||
|
whose cards are round and whose buttons are square looks like two sites.
|
||||||
|
|
||||||
**No SVG and no ICO.** The logo takes PNG, JPG or WebP and the favicon PNG only,
|
**No SVG and no ICO.** The logo takes PNG, JPG or WebP and the favicon PNG only,
|
||||||
both identified from their bytes by the same sniffer the wall uses. An SVG is XML
|
both identified from their bytes by the same sniffer the wall uses. An SVG is XML
|
||||||
that can carry script and would be served from our own origin; ICO would be one
|
that can carry script and would be served from our own origin; ICO would be one
|
||||||
@ -1079,6 +1126,37 @@ needs nothing — it walks `content/` only, and `data/` and `static/` are outsid
|
|||||||
it. A site with no `data/brand.yaml` builds byte-for-byte the HTML it built
|
it. A site with no `data/brand.yaml` builds byte-for-byte the HTML it built
|
||||||
before any of this existed, which is asserted by building both ways.
|
before any of this existed, which is asserted by building both ways.
|
||||||
|
|
||||||
|
### 11.18b Identidad — what the site is called and where to find it
|
||||||
|
|
||||||
|
*Gestión* → **Identidad**, superadministrator only. The name and the one-line
|
||||||
|
tagline **in the three languages**, the association's accounts elsewhere, a
|
||||||
|
public email, a city and street, a default share picture and the footer line.
|
||||||
|
|
||||||
|
All of it used to be `config.yaml`, which meant it could only be changed by
|
||||||
|
somebody with the repository — the thing this phase exists to end. Same
|
||||||
|
architecture as Marca: SQLite first for the members area, then a commit of
|
||||||
|
`data/site.yaml`, so a git outage never blocks a change that does not need git.
|
||||||
|
|
||||||
|
**Hugo cannot have `config.yaml` overridden by a data file.** The name and
|
||||||
|
tagline are therefore read through `partials/site-name.html` and
|
||||||
|
`site-tagline.html`, which prefer `site.Data.site` and fall back to the config —
|
||||||
|
and every template that shows either calls one of them, so the two cannot drift.
|
||||||
|
A site with no `data/site.yaml` builds byte-for-byte what it built before, which
|
||||||
|
is asserted by building both ways.
|
||||||
|
|
||||||
|
**Only what was actually set is written.** A file repeating the config's own
|
||||||
|
values back at it would make the fallback meaningless and freeze today's
|
||||||
|
defaults for good, so the form shows them as placeholders rather than as values
|
||||||
|
— a prefilled form saves the fallback the first time anybody presses the button.
|
||||||
|
|
||||||
|
The contact fields are not decoration: they become `ContactPoint` and
|
||||||
|
`PostalAddress` in the `Organization` schema, which is what puts an association
|
||||||
|
in a *local* search result rather than only a web one. The social links become
|
||||||
|
`sameAs`, which is how a search or answer engine knows an Instagram account and
|
||||||
|
this site are the same body. Both are checked on the way in — a link must be
|
||||||
|
`https://`, because these render in the footer of every public page and
|
||||||
|
`javascript:` in an `href` is a script running on vienalatina.com.
|
||||||
|
|
||||||
### 11.19 The chrome on a phone
|
### 11.19 The chrome on a phone
|
||||||
|
|
||||||
**The public menu opens from a ☰ below 768px**, and above it is the horizontal
|
**The public menu opens from a ☰ below 768px**, and above it is the horizontal
|
||||||
@ -1115,6 +1193,43 @@ In the members area the navigation **wraps** on a phone rather than scrolling:
|
|||||||
six sections over two lines shows all six, where a swipe strip would have left
|
six sections over two lines shows all six, where a swipe strip would have left
|
||||||
Calendario and Gestión off the right edge with nothing to say they were there.
|
Calendario and Gestión off the right edge with nothing to say they were there.
|
||||||
|
|
||||||
|
### 11.20 The three admin tools
|
||||||
|
|
||||||
|
**Estado del sistema** (superadministrator). WordPress's Site Health, and it
|
||||||
|
earns its place for a specific reason: every outage in this project has been a
|
||||||
|
configuration fact invisible until somebody hit it. It asks the running system
|
||||||
|
rather than a file — the content token is **exercised** against the repository
|
||||||
|
rather than checked for emptiness, which is the single most valuable line on the
|
||||||
|
page, because "present" was never the problem; the mail host is connected to;
|
||||||
|
the newest backup is named with its age and size; free disk is reported; and
|
||||||
|
every setting `.env.example` documents that the container does not have is
|
||||||
|
listed with what stops working without it. **It changes nothing**, deliberately:
|
||||||
|
a diagnostic screen that can also act is one somebody uses to act without
|
||||||
|
reading.
|
||||||
|
|
||||||
|
**Registro de actividad** (superadministrator). Who changed a role, approved or
|
||||||
|
returned a proposal, touched the look or the identity, suspended or erased
|
||||||
|
somebody. Deliberately not a general event store — no page views, no successful
|
||||||
|
sign-ins; a log that records everything is a log nobody reads. `activity.log()`
|
||||||
|
never raises: an administrator who could not be appointed because the note about
|
||||||
|
it could not be saved is a worse outcome than a gap in the notes. On erasure the
|
||||||
|
actor is **cleared and not cascaded** — that a role was changed is the
|
||||||
|
association's record, whose name was on it is the erased person's data.
|
||||||
|
|
||||||
|
**Biblioteca de medios** (administrators and above). Every picture the public
|
||||||
|
site carries, with the posts that use each. **Orphans are the point**: a picture
|
||||||
|
is committed when a post is written, and deleting the post leaves it in the
|
||||||
|
repository, deployed, referenced by nothing, for good — there has never been a
|
||||||
|
way to see one. They sort to the top and are the only rows with a delete button;
|
||||||
|
a picture in use is refused by the handler and not merely hidden, because a
|
||||||
|
broken image on a published page is worse than an orphan nobody sees. It reads
|
||||||
|
`content_cache.image`, which is what makes "does anything use this?" a query
|
||||||
|
rather than a re-read of every post's frontmatter on every page view.
|
||||||
|
|
||||||
|
Open to administrators, unlike the other two, because they are the people who
|
||||||
|
upload — and the worst an administrator can do here is remove a picture from a
|
||||||
|
post they could already have edited.
|
||||||
|
|
||||||
## 12. Make Gitea look like the site
|
## 12. Make Gitea look like the site
|
||||||
|
|
||||||
Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its
|
Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its
|
||||||
|
|||||||
@ -4041,3 +4041,14 @@ a.notif-card__message:hover {
|
|||||||
.agenda__day--busy { display: block; }
|
.agenda__day--busy { display: block; }
|
||||||
.agenda__number { display: inline-block; margin-right: 8px; }
|
.agenda__number { display: inline-block; margin-right: 8px; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The association's accounts elsewhere, in the footer. Set in
|
||||||
|
Gestión → Identidad; absent entirely on a site that has set none. */
|
||||||
|
.site-foot__social {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 14px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
}
|
||||||
|
|||||||
@ -3,7 +3,7 @@
|
|||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>{{ if not .IsHome }}{{ .Title }} — {{ end }}{{ .Site.Title }}</title>
|
<title>{{ if not .IsHome }}{{ .Title }} — {{ end }}{{ partial "site-name.html" . }}</title>
|
||||||
{{ partial "seo-head.html" . }}
|
{{ partial "seo-head.html" . }}
|
||||||
{{ $css := resources.Get "css/main.css" | minify | fingerprint }}
|
{{ $css := resources.Get "css/main.css" | minify | fingerprint }}
|
||||||
<link rel="stylesheet" href="{{ $css.RelPermalink }}" integrity="{{ $css.Data.Integrity }}">
|
<link rel="stylesheet" href="{{ $css.RelPermalink }}" integrity="{{ $css.Data.Integrity }}">
|
||||||
|
|||||||
@ -19,7 +19,17 @@
|
|||||||
{{ $tokens := "" }}
|
{{ $tokens := "" }}
|
||||||
{{ range $name, $value := .tokens }}{{ $tokens = printf "%s--%s:%s;" $tokens $name $value }}{{ end }}
|
{{ range $name, $value := .tokens }}{{ $tokens = printf "%s--%s:%s;" $tokens $name $value }}{{ end }}
|
||||||
{{ $sheet := "" }}
|
{{ $sheet := "" }}
|
||||||
{{ with $tokens }}{{ $sheet = printf ":root{%s}" . }}{{ end }}
|
{{/* The uploaded typeface first, so the @font-face is declared before anything
|
||||||
|
asks for the family. `font-display: swap` deliberately: the alternative
|
||||||
|
shows nothing until the file arrives, and a blank article on a slow phone
|
||||||
|
is worse than one that changes typeface a moment after it appears. */}}
|
||||||
|
{{ with .font }}
|
||||||
|
{{ $sheet = printf "@font-face{font-family:\"VLPropia\";src:url(%s) format('woff2');font-weight:100 900;font-display:swap}" . }}
|
||||||
|
{{ end }}
|
||||||
|
{{ with $tokens }}{{ $sheet = printf "%s:root{%s}" $sheet . }}{{ end }}
|
||||||
|
{{/* On `body`, because that is where main.css sets the stack and a custom
|
||||||
|
property would need every rule to opt in. */}}
|
||||||
|
{{ with .font_stack }}{{ $sheet = printf "%sbody{font-family:%s}" $sheet . }}{{ end }}
|
||||||
{{ with $.Site.Data.brand.custom_css }}{{ $sheet = printf "%s\n%s" $sheet . }}{{ end }}
|
{{ with $.Site.Data.brand.custom_css }}{{ $sheet = printf "%s\n%s" $sheet . }}{{ end }}
|
||||||
{{ with $sheet }}
|
{{ with $sheet }}
|
||||||
{{ $brand := resources.FromString "css/brand.css" . | minify | fingerprint }}
|
{{ $brand := resources.FromString "css/brand.css" . | minify | fingerprint }}
|
||||||
|
|||||||
@ -8,5 +8,21 @@
|
|||||||
{{ end }}
|
{{ end }}
|
||||||
</nav>
|
</nav>
|
||||||
{{ end }}
|
{{ end }}
|
||||||
<p>{{ .Site.Title }} © {{ now.Format "2006" }}</p>
|
{{/* The association's accounts elsewhere. Read through a variable for the
|
||||||
|
same reason as the name — a field lookup on nil fails the build on a
|
||||||
|
site that has not set any. `rel="me"` is what lets Mastodon verify a
|
||||||
|
link back, and costs nothing on the others. */}}
|
||||||
|
{{ $social := dict }}
|
||||||
|
{{ with site.Data.site }}{{ with .social }}{{ $social = . }}{{ end }}{{ end }}
|
||||||
|
{{ with $social }}
|
||||||
|
<nav class="site-foot__social" aria-label="Redes">
|
||||||
|
{{ range $name, $url := . }}
|
||||||
|
<a href="{{ $url }}" rel="me nofollow noopener">{{ $name | title }}</a>
|
||||||
|
{{ end }}
|
||||||
|
</nav>
|
||||||
|
{{ end }}
|
||||||
|
|
||||||
|
{{ $footer := "" }}
|
||||||
|
{{ with site.Data.site }}{{ $footer = .footer_text }}{{ end }}
|
||||||
|
<p>{{ with $footer }}{{ . }}{{ else }}{{ partial "site-name.html" $ }} © {{ now.Format "2006" }}{{ end }}</p>
|
||||||
</footer>
|
</footer>
|
||||||
|
|||||||
@ -15,9 +15,10 @@
|
|||||||
{{ $logo := "" }}{{ $stamp := "0" }}
|
{{ $logo := "" }}{{ $stamp := "0" }}
|
||||||
{{ with site.Data.brand }}{{ $logo = .logo }}{{ $stamp = .stamp }}{{ end }}
|
{{ with site.Data.brand }}{{ $logo = .logo }}{{ $stamp = .stamp }}{{ end }}
|
||||||
{{ with $logo }}
|
{{ with $logo }}
|
||||||
<img class="site-bar__logo" src="{{ . }}?v={{ $stamp }}" alt="{{ site.Title }}">
|
<img class="site-bar__logo" src="{{ . }}?v={{ $stamp }}"
|
||||||
|
alt="{{ partial "site-name.html" $ }}">
|
||||||
{{ else }}
|
{{ else }}
|
||||||
<span class="site-bar__brand-text">{{ .Site.Title }}</span>
|
<span class="site-bar__brand-text">{{ partial "site-name.html" . }}</span>
|
||||||
{{ end }}
|
{{ end }}
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
|||||||
@ -4,7 +4,7 @@
|
|||||||
{{ $localeMap := .Site.Params.localeMap }}
|
{{ $localeMap := .Site.Params.localeMap }}
|
||||||
{{ $locale := index $localeMap .Language.Lang | default "es_ES" }}
|
{{ $locale := index $localeMap .Language.Lang | default "es_ES" }}
|
||||||
{{ $desc := "" }}
|
{{ $desc := "" }}
|
||||||
{{ if .IsPage }}{{ $desc = .Description | default (.Summary | plainify | truncate 200) }}{{ else }}{{ $desc = .Site.Params.description }}{{ end }}
|
{{ if .IsPage }}{{ $desc = .Description | default (.Summary | plainify | truncate 200) }}{{ else }}{{ $desc = partial "site-tagline.html" . }}{{ end }}
|
||||||
{{/* One line, always. A summary pulled out of the body arrives with the line
|
{{/* One line, always. A summary pulled out of the body arrives with the line
|
||||||
breaks the prose had, and a newline inside og:description is a card that
|
breaks the prose had, and a newline inside og:description is a card that
|
||||||
renders raggedly in some readers and truncated in others. */}}
|
renders raggedly in some readers and truncated in others. */}}
|
||||||
@ -20,9 +20,13 @@
|
|||||||
|
|
||||||
Absolute, because WhatsApp, Signal, Mastodon and Bluesky all fetch it from
|
Absolute, because WhatsApp, Signal, Mastodon and Bluesky all fetch it from
|
||||||
outside and a relative path means nothing to them. */}}
|
outside and a relative path means nothing to them. */}}
|
||||||
{{ $brandLogo := "" }}
|
{{ $brandLogo := "" }}{{ $chosen := "" }}
|
||||||
{{ with site.Data.brand }}{{ $brandLogo = .logo }}{{ end }}
|
{{ with site.Data.brand }}{{ $brandLogo = .logo }}{{ end }}
|
||||||
{{ $fallback := or $brandLogo .Site.Params.defaultImage }}
|
{{ with site.Data.site }}{{ $chosen = .share_image }}{{ end }}
|
||||||
|
{{/* The picture chosen in Identidad wins over the logo, which wins over the
|
||||||
|
one in config.yaml: most sites want their logo and the field exists for the
|
||||||
|
ones that want something else. */}}
|
||||||
|
{{ $fallback := or $chosen (or $brandLogo .Site.Params.defaultImage) }}
|
||||||
{{ $image := "" }}
|
{{ $image := "" }}
|
||||||
{{ with .Params.image }}{{ $image = . | absURL }}
|
{{ with .Params.image }}{{ $image = . | absURL }}
|
||||||
{{ else }}{{ with $fallback }}{{ $image = . | absURL }}{{ end }}{{ end }}
|
{{ else }}{{ with $fallback }}{{ $image = . | absURL }}{{ end }}{{ end }}
|
||||||
@ -42,7 +46,7 @@
|
|||||||
{{ if and .IsPage (eq .Section "post") }}
|
{{ if and .IsPage (eq .Section "post") }}
|
||||||
{{/* ---- Article ---- */}}
|
{{/* ---- Article ---- */}}
|
||||||
<meta property="og:type" content="article">
|
<meta property="og:type" content="article">
|
||||||
<meta property="og:site_name" content="{{ .Site.Title }}">
|
<meta property="og:site_name" content="{{ partial "site-name.html" . }}">
|
||||||
<meta property="og:title" content="{{ .Title }}">
|
<meta property="og:title" content="{{ .Title }}">
|
||||||
<meta property="og:description" content="{{ $desc }}">
|
<meta property="og:description" content="{{ $desc }}">
|
||||||
<meta property="og:url" content="{{ .Permalink }}">
|
<meta property="og:url" content="{{ .Permalink }}">
|
||||||
@ -124,8 +128,8 @@
|
|||||||
{{ else if .IsHome }}
|
{{ else if .IsHome }}
|
||||||
{{/* ---- Home ---- */}}
|
{{/* ---- Home ---- */}}
|
||||||
<meta property="og:type" content="website">
|
<meta property="og:type" content="website">
|
||||||
<meta property="og:site_name" content="{{ .Site.Title }}">
|
<meta property="og:site_name" content="{{ partial "site-name.html" . }}">
|
||||||
<meta property="og:title" content="{{ .Site.Title }}">
|
<meta property="og:title" content="{{ partial "site-name.html" . }}">
|
||||||
<meta property="og:description" content="{{ $desc }}">
|
<meta property="og:description" content="{{ $desc }}">
|
||||||
<meta property="og:url" content="{{ .Permalink }}">
|
<meta property="og:url" content="{{ .Permalink }}">
|
||||||
<meta property="og:locale" content="{{ $locale }}">
|
<meta property="og:locale" content="{{ $locale }}">
|
||||||
@ -138,14 +142,33 @@
|
|||||||
<meta name="twitter:image" content="{{ . }}">
|
<meta name="twitter:image" content="{{ . }}">
|
||||||
{{ end }}
|
{{ end }}
|
||||||
|
|
||||||
|
{{/* The organisation, as a search or answer engine reads it. Everything
|
||||||
|
overridable lives in Gestión → Identidad; `areaServed` stays here because a
|
||||||
|
city is a fact about this association and not a setting. */}}
|
||||||
{{ $org := dict
|
{{ $org := dict
|
||||||
"@context" "https://schema.org"
|
"@context" "https://schema.org"
|
||||||
"@type" "Organization"
|
"@type" "Organization"
|
||||||
"name" .Site.Title
|
"name" (partial "site-name.html" .)
|
||||||
"url" .Site.Home.Permalink
|
"url" .Site.Home.Permalink
|
||||||
"description" .Site.Params.description
|
"description" (partial "site-tagline.html" .)
|
||||||
"areaServed" (dict "@type" "City" "name" "Wien" "addressCountry" "AT")
|
"areaServed" (dict "@type" "City" "name" "Wien" "addressCountry" "AT")
|
||||||
}}
|
}}
|
||||||
|
{{ with site.Data.site }}
|
||||||
|
{{/* sameAs is how an engine knows an Instagram account and this site are one
|
||||||
|
body — the single highest-value field here for being found at all. */}}
|
||||||
|
{{ with .sameAs }}{{ $org = merge $org (dict "sameAs" .) }}{{ end }}
|
||||||
|
{{ with .email }}
|
||||||
|
{{ $org = merge $org (dict "contactPoint" (dict
|
||||||
|
"@type" "ContactPoint" "contactType" "general" "email" .)) }}
|
||||||
|
{{ end }}
|
||||||
|
{{ if or .city .street }}
|
||||||
|
{{ $address := dict "@type" "PostalAddress" "addressCountry" "AT" }}
|
||||||
|
{{ with .city }}{{ $address = merge $address (dict "addressLocality" .) }}{{ end }}
|
||||||
|
{{ with .street }}{{ $address = merge $address (dict "streetAddress" .) }}{{ end }}
|
||||||
|
{{ with .phone }}{{ $org = merge $org (dict "telephone" .) }}{{ end }}
|
||||||
|
{{ $org = merge $org (dict "address" $address) }}
|
||||||
|
{{ end }}
|
||||||
|
{{ end }}
|
||||||
{{/* The same fallback as the share card: the admin's logo, then the configured
|
{{/* The same fallback as the share card: the admin's logo, then the configured
|
||||||
default. This is the field a search engine uses to put a mark beside the
|
default. This is the field a search engine uses to put a mark beside the
|
||||||
organisation's name, so it should be the logo somebody actually uploaded. */}}
|
organisation's name, so it should be the logo somebody actually uploaded. */}}
|
||||||
@ -184,7 +207,7 @@
|
|||||||
document about the organisation rather than an article, hence WebPage
|
document about the organisation rather than an article, hence WebPage
|
||||||
rather than BlogPosting, and no author: a page is the site speaking. */}}
|
rather than BlogPosting, and no author: a page is the site speaking. */}}
|
||||||
<meta property="og:type" content="website">
|
<meta property="og:type" content="website">
|
||||||
<meta property="og:site_name" content="{{ .Site.Title }}">
|
<meta property="og:site_name" content="{{ partial "site-name.html" . }}">
|
||||||
<meta property="og:title" content="{{ .Title }}">
|
<meta property="og:title" content="{{ .Title }}">
|
||||||
<meta property="og:description" content="{{ $desc }}">
|
<meta property="og:description" content="{{ $desc }}">
|
||||||
<meta property="og:url" content="{{ .Permalink }}">
|
<meta property="og:url" content="{{ .Permalink }}">
|
||||||
|
|||||||
20
themes/vienalatina/layouts/partials/site-name.html
Normal file
20
themes/vienalatina/layouts/partials/site-name.html
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
{{- /* The site's name, from Gestión → Identidad when it has been set there and
|
||||||
|
from config.yaml when it has not.
|
||||||
|
|
||||||
|
Hugo cannot have `config.yaml` overridden by a data file, so this partial
|
||||||
|
is the override: every template that shows the name calls it, and the two
|
||||||
|
sources cannot drift. A site with no data/site.yaml renders exactly what it
|
||||||
|
rendered before any of this existed.
|
||||||
|
|
||||||
|
Read through a variable rather than as site.Data.site.languages.<lang>.name,
|
||||||
|
because on a site with no data file that chain is a field lookup on nil and
|
||||||
|
fails the build — which is the state every install starts in. */ -}}
|
||||||
|
{{- $name := site.Title -}}
|
||||||
|
{{- with site.Data.site -}}
|
||||||
|
{{- with .languages -}}
|
||||||
|
{{- with index . $.Site.Language.Lang -}}
|
||||||
|
{{- with .name }}{{ $name = . }}{{ end -}}
|
||||||
|
{{- end -}}
|
||||||
|
{{- end -}}
|
||||||
|
{{- end -}}
|
||||||
|
{{- $name -}}
|
||||||
12
themes/vienalatina/layouts/partials/site-tagline.html
Normal file
12
themes/vienalatina/layouts/partials/site-tagline.html
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
{{- /* The one-line description of the site, from Gestión → Identidad or from
|
||||||
|
config.yaml. See site-name.html for why it is a partial and why it reads
|
||||||
|
through a variable. */ -}}
|
||||||
|
{{- $tagline := site.Params.description -}}
|
||||||
|
{{- with site.Data.site -}}
|
||||||
|
{{- with .languages -}}
|
||||||
|
{{- with index . $.Site.Language.Lang -}}
|
||||||
|
{{- with .tagline }}{{ $tagline = . }}{{ end -}}
|
||||||
|
{{- end -}}
|
||||||
|
{{- end -}}
|
||||||
|
{{- end -}}
|
||||||
|
{{- $tagline -}}
|
||||||
Loading…
Reference in New Issue
Block a user