Compare commits

..

11 commits

Author SHA1 Message Date
84eef9ec4f ✨ (user): Recuerda el estado de usuarios y roles
Los listados de usuarios y roles se montan con `remember_query()` y
dejan de arrastrar el estado en los enlaces. La renovación de la sesión
"Recuérdame" ya no se pierde cuando la respuesta fija otra cookie.
2026-11-11 18:51:43 +01:00
030ac92e2f 💄 (bootsier): Muestra el acceso en una tarjeta 2026-11-11 18:40:03 +01:00
a276a5f797 ✨ (form): Añade texto de ayuda a Checkbox
Documenta el criterio de uso de las cookies en PageTop y por qué no
requieren la aceptación del usuario.
2026-11-11 18:36:04 +01:00
e4a88b2150 ✨ (web): Recuerda el estado de los listados
Añade `web::remember_query()`, que guarda en una cookie por listado los
filtros, el orden y la página, y los restaura con un 303 al volver al
listado sin parámetros. "Limpiar" de `ListFilter` añade `?reset` para
olvidarlos.
2026-11-11 07:46:27 +01:00
d8493291e4 ✨ (base) Añade ListView y ListFilter para listados
- ListView: botones, mensajes, tabla y paginador en orden fijo;
  anuncia el número de resultados a los lectores de pantalla.
- ListFilter: filtros en fila con "Filtrar" y "Limpiar", envío
  automático opcional y marcas de cambios sin aplicar.
- pagetop-htmx: hx_pager::boost() y hx_filter::boost(); cancelan
  las peticiones solapadas y atenúan el listado mientras carga,
  con estilos sólo en las páginas con listado.
- Usuarios y roles migrados al nuevo patrón.
2026-11-10 22:49:40 +01:00
0f71eba7ab 📝 Acorta la descripción de AdminFrame 2026-11-10 22:02:50 +01:00
7e7720bd49 💄 (bootsier): Centra verticalmente celdas de tablas 2026-11-10 22:02:25 +01:00
bdc94be92a 💄 (user): Unifica botoneras y enlaces de vuelta
- "Guardar" y "Cancelar" en la misma fila en todos los formularios.
- "Volver" sólo en fichas de sólo lectura.
- Búsqueda de usuarios con `form::input::Field` y botones de alta en
  estilo principal.
2026-11-09 23:04:59 +01:00
698b917fb1 ➖ Sustituye parking_lot por std::sync
PageTop ya no lo necesita como dependencia directa: `std::sync` cubre
los bloqueos del contexto, los temas y las trazas. No se detecta pérdida
de rendimiento en ningún caso.

Usa `unwrap()` en los bloqueos, también en las extensiones, porque sus
secciones exclusivas no pueden provocar panic. Sólo pagetop-cron ignora
el envenenamiento, porque calcula fechas con el bloqueo tomado.
2026-11-09 07:22:18 +01:00
a6d15ab211 ♻️ Exige la petición en las variantes de ErrorPage
Sustituye `Option<HttpRequest>` por `HttpRequest` en todas las
variantes. Ningún uso construía un ErrorPage sin petición y, sin ella,
la página de error pierde el idioma negociado y el usuario actual.
2026-11-08 14:24:30 +01:00
947aef2f91 🔥 Simplifica startup_banner a booleano 2026-11-08 13:51:35 +01:00
92 changed files with 2588 additions and 1350 deletions

1
Cargo.lock generated
View file

@ -2174,7 +2174,6 @@ dependencies = [
"pagetop-macros",
"pagetop-minimal",
"pagetop-statics",
"parking_lot",
"serde",
"serde_json",
"serde_qs",

View file

@ -46,7 +46,6 @@ itoa = "1.0"
lettre = { version = "0.11", default-features = false }
mime_guess = "2.0"
minify-js = "0.6"
parking_lot = "0.12"
pastey = "0.2"
path-slash = "0.2"
proc-macro2 = "1.0"
@ -131,7 +130,6 @@ fluent-templates.workspace = true
getter-methods.workspace = true
indexmap.workspace = true
itoa.workspace = true
parking_lot.workspace = true
pagetop-macros.workspace = true
pagetop-minimal.workspace = true
pagetop-statics.workspace = true

114
assets/js/list-filter.js Normal file
View file

@ -0,0 +1,114 @@
// Señala en los filtros de listado (`ListFilter`) que se aplican con botón los campos cuyo valor ya
// no coincide con el del filtro aplicado, para que el usuario sepa que el listado todavía no
// corresponde a lo que muestra el formulario. Sólo pone y quita clases (`list-filter-changed` en el
// contenedor de cada campo, `list-filter-pending` en el formulario) y el texto del aviso para
// lectores de pantalla; el aspecto lo da cada tema. Sin dependencias.
//
// Actúa sólo en los formularios con el aviso `.list-filter-status`, que `ListFilter` no pinta
// cuando los filtros se envían solos.
(function () {
"use strict";
var FIELDS =
'input:not([type="hidden"]):not([type="submit"])' +
':not([type="button"]):not([type="reset"]), select, textarea';
// Opción que estaba elegida al aplicar el filtro. Un desplegable simple sin ninguna opción
// marcada en el HTML muestra la primera.
function wasSelected(select, option, index) {
if (option.defaultSelected) {
return true;
}
if (select.multiple) {
return false;
}
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].defaultSelected) {
return false;
}
}
return index === 0;
}
// Indica si el campo tiene un valor distinto del que tenía al aplicar el filtro.
function isChanged(field) {
if (field.type === "checkbox" || field.type === "radio") {
return field.checked !== field.defaultChecked;
}
if (field.tagName === "SELECT") {
for (var i = 0; i < field.options.length; i++) {
if (field.options[i].selected !== wasSelected(field, field.options[i], i)) {
return true;
}
}
return false;
}
return field.value !== field.defaultValue;
}
// Toma los valores actuales como los del filtro aplicado. Hace falta cuando sólo se actualiza
// el listado y el formulario no se vuelve a pintar.
function commit(field) {
if (field.type === "checkbox" || field.type === "radio") {
field.defaultChecked = field.checked;
} else if (field.tagName === "SELECT") {
for (var i = 0; i < field.options.length; i++) {
field.options[i].defaultSelected = field.options[i].selected;
}
} else {
field.defaultValue = field.value;
}
}
function refresh(form) {
var changed = [];
form.querySelectorAll(FIELDS).forEach(function (field) {
var container = field.closest(".form-field") || field;
if (changed.indexOf(container) === -1 && isChanged(field)) {
changed.push(container);
}
});
form.querySelectorAll(".list-filter-changed").forEach(function (container) {
if (changed.indexOf(container) === -1) {
container.classList.remove("list-filter-changed");
}
});
changed.forEach(function (container) {
container.classList.add("list-filter-changed");
});
var pending = changed.length > 0;
form.classList.toggle("list-filter-pending", pending);
// Sólo se cambia el texto al empezar o terminar los cambios pendientes, para que el lector
// de pantalla lo anuncie una vez y no con cada pulsación.
var status = form.querySelector(".list-filter-status");
var text = pending ? status.getAttribute("data-pending") || "" : "";
if (status.textContent !== text) {
status.textContent = text;
}
}
function filterOf(element) {
var form = element instanceof Element ? element.closest("form.list-filter") : null;
return form && form.querySelector(".list-filter-status") ? form : null;
}
function onChange(event) {
var form = filterOf(event.target);
if (form) {
refresh(form);
}
}
document.addEventListener("input", onChange);
document.addEventListener("change", onChange);
document.addEventListener("submit", function (event) {
var form = filterOf(event.target);
if (form) {
form.querySelectorAll(FIELDS).forEach(commit);
refresh(form);
}
});
})();

52
assets/js/list-view.js Normal file
View file

@ -0,0 +1,52 @@
// Anuncia a los lectores de pantalla el resumen de un listado (`ListView`, atributo
// `data-summary`, p. ej. "23 resultados") cuando se actualiza sin recargar la página, al filtrar,
// ordenar o cambiar de página. Un lector de pantalla no suele anunciar una zona `aria-live` que se
// inserta de golpe, así que el aviso usa una única zona creada al cargar la página, y el listado
// nuevo sólo le pasa su texto. Al cargar la página no anuncia nada. Sin dependencias: vale para
// HTMX o para cualquier otra forma de actualizar sólo una parte de la página.
(function () {
"use strict";
var SELECTOR = ".list-view[data-summary]";
var REGION_ID = "list-view-status";
// La zona se busca por su identificador cada vez: si se restaura una página del historial
// sustituyendo el contenido del `<body>` (como hace HTMX al volver atrás), la zona creada al
// cargar desaparece y queda la copia restaurada.
function region() {
var element = document.getElementById(REGION_ID);
if (!element) {
element = document.createElement("div");
element.id = REGION_ID;
element.className = "visually-hidden";
element.setAttribute("role", "status");
document.body.appendChild(element);
}
return element;
}
region();
function announce(text) {
var element = region();
// Se vacía primero para que se anuncie también un texto igual al anterior.
element.textContent = "";
setTimeout(function () {
element.textContent = text;
}, 50);
}
new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
mutation.addedNodes.forEach(function (node) {
if (!(node instanceof Element)) {
return;
}
var list = node.matches(SELECTOR) ? node : node.querySelector(SELECTOR);
if (list) {
announce(list.getAttribute("data-summary"));
}
});
});
}).observe(document.body, { childList: true, subtree: true });
})();

View file

@ -25,6 +25,8 @@
@use "basic/dropdown";
@use "basic/form";
@use "basic/image";
@use "basic/list-filter";
@use "basic/list-view";
@use "basic/messages";
@use "basic/nav";
@use "basic/navbar";

View file

@ -9,7 +9,9 @@
}
.form-text {
font-size: 0.9375rem;
font-size: 0.875rem;
font-style: italic;
line-height: 1.3;
color: var(--val-color--text--muted);
}
@ -33,23 +35,37 @@ fieldset > legend {
}
.form-check {
display: flex;
display: grid;
grid-template-columns: auto 1fr;
align-items: center;
gap: 0.5rem;
gap: 0.25rem 0.5rem;
min-height: 1.5rem;
margin-bottom: 0.25rem;
}
// A single checkbox has no label above it to give it room, as the other fields do.
.form-field.form-check:not(.form-check-inline) {
margin-top: 1em;
}
.form-check-inline {
display: inline-flex;
display: inline-grid;
margin-right: 1rem;
}
.form-check-reverse {
flex-direction: row-reverse;
justify-content: flex-start;
grid-template-columns: 1fr auto;
text-align: right;
}
.form-check-reverse > .form-check-input {
grid-column: 2;
grid-row: 1;
}
// Help text goes below the label, aligned with it.
.form-check > .form-text {
grid-column: 2;
}
.form-check-reverse > .form-text {
grid-column: 1;
}
.form-check-input {
flex-shrink: 0;
cursor: pointer;
}
.form-check-label {

View file

@ -0,0 +1,59 @@
// List filters (ListFilter): fields and button on one row, wrapping when there is no room.
.list-filter {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 0.5rem 1rem;
margin-bottom: 1rem;
}
.list-filter > .form-field {
margin-bottom: 0;
}
// Marks of changed filters not applied yet (filters with a button), set by `list-filter.js`. Only
// colors and opacity change, never sizes: the dot always takes its room, hidden, so nothing moves
// when it shows up. A vivid orange, set apart from the primary color of the button, darkened just
// enough to keep a 3:1 contrast against the background. Every changed field gets the dot by its
// label, once per field (on the title of a group); text fields and dropdowns also show a gray
// background.
.list-filter {
--list-filter-mark: color-mix(in srgb, #fd7e14 85%, black);
}
.list-filter .form-field > .form-label::after,
.list-filter .form-field.form-check > .form-check-label::after {
content: "\25CF" / "";
margin-left: 0.25em;
color: var(--list-filter-mark);
opacity: 0;
}
.list-filter .list-filter-changed > .form-label::after,
.list-filter .list-filter-changed.form-check > .form-check-label::after {
opacity: 1;
}
.list-filter .list-filter-changed .form-control,
.list-filter .list-filter-changed .form-select {
background-color: color-mix(in srgb, var(--val-color--bg--muted) 60%, #fff);
}
// Native checkboxes only take a color when checked; a switch is drawn by the theme.
.list-filter .list-filter-changed .form-check-input {
accent-color: var(--list-filter-mark);
}
.list-filter .list-filter-changed.form-switch .form-check-input:checked {
background-color: var(--list-filter-mark);
}
.list-filter-pending > button[type="submit"] {
background-color: var(--val-color--primary);
border-color: var(--val-color--primary);
}
.list-filter-pending > button[type="submit"]:hover {
background-color: color-mix(in srgb, var(--val-color--primary) 85%, black);
border-color: color-mix(in srgb, var(--val-color--primary) 85%, black);
}

View file

@ -0,0 +1,8 @@
// List view (ListView): action buttons above the table, then messages, table and pager.
.list-view {
margin: 1.5rem 0;
}
.list-view-actions {
margin-bottom: 1rem;
}

View file

@ -30,10 +30,6 @@
margin-top: 1.5rem;
}
.user-admin-table-wrapper {
margin: 1.5rem 0;
}
.user-form-error {
padding: 0.625rem 0.875rem;
margin-bottom: 1rem;

View file

@ -23,6 +23,12 @@ fn main() -> std::io::Result<()> {
"static/js/basic.dialog.min.js",
)?;
// JS: minifica el aviso del resumen de `ListView` a los lectores de pantalla.
minify_js("assets/js/list-view.js", "static/js/list-view.min.js")?;
// JS: minifica las marcas de cambios sin aplicar de `ListFilter`, independientes del tema.
minify_js("assets/js/list-filter.js", "static/js/list-filter.min.js")?;
// JS: minifica la integración de `Dropdown` con `accessible-menu` del tema Basic.
minify_js(
"assets/js/basic.dropdown.init.js",

View file

@ -80,8 +80,8 @@ admin_path = "/admin" # Ruta raíz del panel de administración
# "/", sin "/" final; cada tramo sólo admite letras y dígitos
# ASCII, "-", "_", "." y "~" (sin ser "." ni ".."). Una no
# válida impide arrancar.
startup_banner = "Slant" # Banner ASCII al arrancar: "Off", "Slant", "Small", "Speed"
# o "Starwars".
startup_banner = true # Muestra al arrancar un banner ASCII con el nombre de la
# aplicación (true) o no (false).
[dev]
pagetop_static_dir = "" # Directorio static/ de PageTop para servir sus archivos

View file

@ -13,7 +13,7 @@ use crate::settings::{self, SettingFieldType, SettingsSchema};
fn config_form_page(
request: &HttpRequest,
) -> Result<(&'static AdminPage, &'static SettingsSchema), ErrorPage> {
let not_found = || ErrorPage::NotFound(Some(request.clone()));
let not_found = || ErrorPage::NotFound(request.clone());
let path = strip_admin_path(request.path()).ok_or_else(not_found)?;
let page = AdminRegistry::global().page(path).ok_or_else(not_found)?;
let schema = config_forms().get(path).ok_or_else(not_found)?;

View file

@ -133,6 +133,68 @@ fieldset > legend {
opacity: 1;
}
// List filters (ListFilter): fields and button on one row, wrapping when there is no room.
.list-filter {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: ($spacer * .5) $spacer;
margin-bottom: $spacer;
> .form-field {
margin-bottom: 0;
}
}
// Marks of changed filters not applied yet (filters with a button), set by `list-filter.js`. Only
// colors and opacity change, never sizes: the dot always takes its room, hidden, so nothing moves
// when it shows up. A vivid orange, set apart from the primary color of the button, darkened just
// enough to keep a 3:1 contrast against the background. Every changed field gets the dot by its
// label, once per field (on the title of a group); text fields and dropdowns also show a gray
// background. Floating labels are left out: Bootstrap draws their background with `::after`.
.list-filter {
--list-filter-mark: #{mix(#000, $orange, 15%)};
}
.list-filter .form-field:not(.form-floating) > .form-label::after,
.list-filter .form-field.form-check > .form-check-label::after {
content: "\25CF" / "";
margin-left: .25em;
color: var(--list-filter-mark);
opacity: 0;
}
.list-filter .list-filter-changed {
&:not(.form-floating) > .form-label::after,
&.form-check > .form-check-label::after {
opacity: 1;
}
.form-control,
.form-select,
.form-check-input {
background-color: var(--bs-secondary-bg);
}
.form-check-input:checked {
background-color: var(--list-filter-mark);
border-color: var(--list-filter-mark);
}
}
.list-filter-pending > .btn-secondary[type="submit"] {
@extend .btn-primary;
}
// List view (ListView): action buttons above the table.
.list-view {
margin-block: $spacer * 1.5;
}
.list-view-actions {
margin-bottom: $spacer;
}
// Pager component.
// `.pagination`, `.page-item`, `.page-link`, `.active` and `.disabled` already come styled by
// Bootstrap, since Pager reuses that same markup (the ellipsis is a disabled `.page-link` span,
@ -296,3 +358,41 @@ fieldset > legend {
border-bottom-color: var(--bs-primary);
font-weight: 600;
}
// Login page (pagetop-user `LoginForm`): the form inside a centered card, as in Bootstrap's sign-in
// example. The submit button takes the full width of the card.
.user-login-page {
display: flex;
align-items: center;
justify-content: center;
min-height: 70vh;
padding: $spacer * 2 $spacer;
background-color: var(--bs-tertiary-bg);
}
.user-login-card {
width: 100%;
max-width: 24rem;
padding: $spacer * 2;
background-color: var(--bs-body-bg);
border: var(--bs-border-width) solid var(--bs-border-color-translucent);
border-radius: var(--bs-border-radius-lg);
box-shadow: var(--bs-box-shadow);
}
.user-login-card .btn[type="submit"] {
width: 100%;
margin-top: $spacer * .5;
}
.user-register-link,
.user-reset-link {
margin: $spacer 0 0;
text-align: center;
}
// Form errors of pagetop-user, with the palette of Bootstrap's own alerts.
.user-form-error {
@extend .alert;
@extend .alert-danger;
}

View file

@ -9,3 +9,8 @@ $navbar-brand-font-size: 1.75rem;
$font-family-sans-serif: "Source Sans 3", system-ui, -apple-system, "Segoe UI", Roboto,
"Helvetica Neue", "Noto Sans", "Liberation Sans", Arial, sans-serif, "Apple Color Emoji",
"Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
// Table cells centered vertically, as in the Basic theme: with Bootstrap's default (top), a cell
// holding a button is taller and the text of the other cells sticks to the top of the row. Header
// cells keep Bootstrap's bottom alignment.
$table-cell-vertical-align: middle;

View file

@ -411,7 +411,7 @@ async fn trigger_post(request: HttpRequest) -> Response {
.filter(|(scheme, _)| scheme.eq_ignore_ascii_case("Bearer"))
.map(|(_, token)| token.trim_start());
if !token.is_some_and(scheduler::token_matches) {
return ErrorPage::NotFound(Some(request)).into_response();
return ErrorPage::NotFound(request).into_response();
}
// Siempre `200 OK`, aunque falle algún trabajo: un reintento del programa externo podría
// llegar a otra instancia y repetir también los que terminaron bien. Sólo se indica el tipo de
@ -433,5 +433,5 @@ async fn trigger_post(request: HttpRequest) -> Response {
}
async fn not_found(request: HttpRequest) -> ErrorPage {
ErrorPage::NotFound(Some(request))
ErrorPage::NotFound(request)
}

View file

@ -282,8 +282,9 @@ impl Entry {
}
}
// Un `panic!` sólo puede ocurrir fuera de la sección protegida (se ejecutan en otra tarea),
// así que el estado sigue siendo coherente aunque el `Mutex` quede envenenado.
// Los trabajos se ejecutan en otra tarea, fuera de la sección protegida. Dentro sólo podría
// fallar el cálculo de fechas de `take_due()`, que no deja el estado incoherente, así que un
// `Mutex` envenenado no debe detener el trabajo.
fn state(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}

View file

@ -47,7 +47,9 @@ impl Extension for MyApp {
```
A partir de ese momento, todas las páginas de la aplicación incluirán automáticamente el script de
HTMX 2. Puedes usar los atributos `hx-*` directamente en tus componentes o el código HTML generado:
HTMX 2, y las que tengan algún listado (`ListView`), unos pocos estilos que lo atenúan mientras
se actualiza. Puedes usar los atributos `hx-*` directamente en tus componentes o el código HTML
generado:
```rust
use pagetop::prelude::*;

View file

@ -0,0 +1,51 @@
//! Soporte HTMX al componente [`ListFilter`].
//!
//! [`ListFilter`] es un formulario GET que funciona sin JavaScript: al aplicarlo, el navegador pide
//! de nuevo la página con los filtros aplicados. [`boost()`] hace que sólo se actualice el listado,
//! tanto al pulsar su botón como, con [`ListFilter::with_auto_submit()`], al cambiar un campo.
use pagetop::prelude::*;
use crate::hx;
/// Hace que, al aplicar `filter`, se actualice sólo el elemento `target` (un selector CSS, p. ej.
/// `"#user-list"`), sin recargar la página.
///
/// Añade al formulario `hx::BOOST` (envía sus campos a su propia ruta), `hx::TARGET`, `hx::SWAP`
/// (reemplaza el elemento entero y sube al principio) y `hx::PUSH_URL`, para que la dirección del
/// navegador refleje los filtros aplicados. No cambia cuándo se aplican: al pulsar el botón o, con
/// [`ListFilter::with_auto_submit()`], al cambiar un campo. Sin JavaScript, el filtro recarga la
/// página como cualquier formulario.
///
/// Para que las peticiones no se pisen, una nueva petición contra `target` (desde los filtros, el
/// paginador o una cabecera) cancela la que estuviera en curso (`hx::SYNC`). Y mientras llega la
/// respuesta, `target` recibe la clase `htmx-request` (`hx::INDICATOR`), con la que la extensión
/// atenúa el listado ([`ListView`]).
///
/// La ruta del filtro debe responder a las peticiones HTMX con el elemento `target` ya filtrado,
/// normalmente el [`ListView`] del listado.
///
/// ```rust,no_run
/// use pagetop::prelude::*;
/// use pagetop_htmx::prelude::*;
///
/// let filter = hx_filter::boost(
/// ListFilter::new()
/// .with_filter_action("/admin/users")
/// .with_field(form::input::Field::search().with_name("q")),
/// "#user-list",
/// );
/// ```
pub fn boost(filter: ListFilter, target: impl Into<CowStr>) -> ListFilter {
let target: CowStr = target.into();
filter
.with_prop(PropsOp::set(hx::BOOST, "true"))
.with_prop(PropsOp::set(
hx::SYNC,
util::join!(target.as_ref(), ":replace"),
))
.with_prop(PropsOp::set(hx::INDICATOR, target.clone()))
.with_prop(PropsOp::set(hx::TARGET, target))
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP))
.with_prop(PropsOp::set(hx::PUSH_URL, "true"))
}

View file

@ -8,25 +8,53 @@
//! Para una navegación sin recarga basta con añadir `hx::BOOST` (más `hx::TARGET` y `hx::SWAP`) al
//! propio `<nav>`. HTMX convierte automáticamente en peticiones AJAX los enlaces de todas las
//! páginas, reutilizando el `href` que cada uno ya tiene resuelto, sin que [`Pager`] tenga que
//! generar ningún atributo `hx-*` por sí misma.
//!
//! ```rust,no_run
//! use pagetop::prelude::*;
//! use pagetop_htmx::prelude::*;
//!
//! let pager = Pager::new()
//! .with_base_path("/admin/users")
//! .with_extra_query("sort", "username")
//! .with_current_page(2)
//! .with_items_per_page(20)
//! .with_total_items(97)
//! .with_prop(PropsOp::set(hx::BOOST, "true"))
//! .with_prop(PropsOp::set(hx::TARGET, "#user-table-wrapper"))
//! .with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP))
//! .with_prop(PropsOp::set(hx::PUSH_URL, "true"));
//! ```
//! generar ningún atributo `hx-*` por sí misma. [`boost()`] los añade todos de una vez.
//!
//! [`Pager`]: pagetop::base::component::Pager
//! [`Props`]: pagetop::html::Props
//! [`PropsOp::set()`]: pagetop::html::PropsOp::set
//! [`with_prop()`]: pagetop::base::component::Pager::with_prop
use pagetop::prelude::*;
use crate::hx;
/// Hace que los enlaces de `pager` reemplacen sólo el elemento `target` (un selector CSS, p. ej.
/// `"#user-list"`), sin recargar la página.
///
/// Añade al `<nav>` del paginador `hx::BOOST`, `hx::TARGET`, `hx::SWAP` (reemplaza el elemento
/// entero y sube al principio) y `hx::PUSH_URL`, para que la dirección del navegador refleje la
/// página mostrada. Sin JavaScript, los enlaces siguen funcionando como peticiones normales.
///
/// Para que las peticiones no se pisen, una nueva petición contra `target` (desde los filtros, el
/// paginador o una cabecera) cancela la que estuviera en curso (`hx::SYNC`). Y mientras llega la
/// respuesta, `target` recibe la clase `htmx-request` (`hx::INDICATOR`), con la que la extensión
/// atenúa el listado ([`ListView`]).
///
/// ```rust,no_run
/// use pagetop::prelude::*;
/// use pagetop_htmx::prelude::*;
///
/// let pager = hx_pager::boost(
/// Pager::new()
/// .with_base_path("/admin/users")
/// .with_extra_query("sort", "username")
/// .with_current_page(2)
/// .with_items_per_page(20)
/// .with_total_items(97),
/// "#user-list",
/// );
/// ```
pub fn boost(pager: Pager, target: impl Into<CowStr>) -> Pager {
let target: CowStr = target.into();
pager
.with_prop(PropsOp::set(hx::BOOST, "true"))
.with_prop(PropsOp::set(
hx::SYNC,
util::join!(target.as_ref(), ":replace"),
))
.with_prop(PropsOp::set(hx::INDICATOR, target.clone()))
.with_prop(PropsOp::set(hx::TARGET, target))
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP))
.with_prop(PropsOp::set(hx::PUSH_URL, "true"))
}

View file

@ -23,9 +23,14 @@ use crate::hx;
///
/// [`Table`] y `SortLink` no requieren HTMX. Cada extensión que quiera aplicar una navegación sin
/// recarga debe añadir sus propios atributos `hx-*` usando [`SortLink::with_prop()`]. Como esos
/// cuatro atributos son siempre los mismos para cualquier cabecera ordenable (`hx-get` igual al
/// `href`, `hx-swap="outerHTML scroll:top"` y `hx-push-url="true"`, y sólo `hx-target` cambia según
/// la tabla), [`sort_link()`] evita reescribirlos en cada columna de cada listado.
/// atributos son siempre los mismos para cualquier cabecera ordenable (`hx-get` igual al `href`,
/// `hx-swap="outerHTML scroll:top"` y `hx-push-url="true"`, y sólo `hx-target` cambia según la
/// tabla), [`sort_link()`] evita reescribirlos en cada columna de cada listado.
///
/// Para que las peticiones no se pisen, una nueva petición contra `target` (desde los filtros, el
/// paginador o una cabecera) cancela la que estuviera en curso (`hx::SYNC`). Y mientras llega la
/// respuesta, `target` recibe la clase `htmx-request` (`hx::INDICATOR`), con la que la extensión
/// atenúa el listado ([`ListView`]).
///
/// El enlace resultante funciona igual con o sin HTMX: `href` es siempre la URL real del nuevo
/// estado de orden, así que navega correctamente aunque HTMX no esté disponible en el cliente.
@ -80,9 +85,12 @@ pub fn sort_link(
// `RoutePath` en `SortLink::new()` (vía `href.as_str()`) y como `CowStr` en `PropsOp::set()`.
let href = href.into().to_string();
let target = target.as_ref().to_owned();
let sync = util::join!(target.as_str(), ":replace");
table::SortLink::new(href.as_ref())
.with_dir(dir)
.with_prop(PropsOp::set(hx::GET, href))
.with_prop(PropsOp::set(hx::SYNC, sync))
.with_prop(PropsOp::set(hx::INDICATOR, target.clone()))
.with_prop(PropsOp::set(hx::TARGET, target))
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP))
.with_prop(PropsOp::set(hx::PUSH_URL, "true"))

View file

@ -48,7 +48,9 @@ impl Extension for MyApp {
```
A partir de ese momento, todas las páginas de la aplicación incluirán automáticamente el script de
HTMX 2. Puedes usar los atributos `hx-*` directamente en tus componentes o el código HTML generado:
HTMX 2, y las que tengan algún listado ([`ListView`]), unos pocos estilos que lo atenúan mientras
se actualiza. Puedes usar los atributos `hx-*` directamente en tus componentes o el código HTML
generado:
```rust
use pagetop::prelude::*;
@ -92,6 +94,7 @@ use pagetop::prelude::*;
include_locales!(LOCALES_HTMX);
pub mod hx;
pub mod hx_filter;
pub mod hx_pager;
pub mod hx_table;
pub mod request;
@ -100,6 +103,7 @@ pub mod response;
/// Prelude de `pagetop-htmx`.
pub mod prelude {
pub use crate::hx;
pub use crate::hx_filter;
pub use crate::hx_pager;
pub use crate::hx_table;
pub use crate::request::HtmxRequestExt;
@ -110,8 +114,9 @@ pub mod prelude {
///
/// Poner esta extensión en [`dependencies()`](pagetop::core::extension::Extension::dependencies)
/// hace que todas las páginas de la aplicación incluyan automáticamente el script de HTMX mediante
/// un atributo [`defer`](pagetop::html::JavaScript::defer). No es necesaria ninguna configuración
/// adicional.
/// un atributo [`defer`](pagetop::html::JavaScript::defer), y las que tienen algún listado
/// ([`ListView`]), los estilos con los que se atenúa mientras se actualiza. No es necesaria ninguna
/// configuración adicional.
///
/// # Ejemplo
///
@ -144,7 +149,10 @@ impl Extension for Htmx {
}
fn actions(&self) -> Vec<ActionBox> {
actions![action::page::BeforeRenderBody::new(add_htmx_script)]
actions![
action::page::BeforeRenderBody::new(add_htmx_script),
action::component::BeforeRender::<ListView>::new(add_list_loading_styles),
]
}
fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
@ -156,3 +164,19 @@ impl Extension for Htmx {
fn add_htmx_script(page: &mut Page) {
page.alter_assets(JavaScript::defer("/htmx/js/htmx.min.js").with_version("2.0.10"));
}
// Mientras los helpers de listado (filtros, paginador, cabeceras ordenables) esperan una respuesta,
// HTMX pone la clase `htmx-request` en el listado: se atenúa para que se vea que está cargando. El
// retardo evita el parpadeo cuando la respuesta es rápida. Sólo en las páginas con algún listado.
fn add_list_loading_styles(_list: &mut ListView, cx: &mut Context) {
cx.alter_assets(AssetsOp::add_responsive_styles(
None,
"list-view",
[("transition", "opacity 0.2s ease-in-out 0.15s")],
));
cx.alter_assets(AssetsOp::add_responsive_styles(
None,
"list-view htmx-request",
[("opacity", "0.5")],
));
}

View file

@ -10,7 +10,9 @@ impl Extension for TestApp {
}
fn configure_router(&self, routes: Routes) -> Routes {
routes.public_route("/page", web::get(render_page))
routes
.public_route("/page", web::get(render_page))
.public_route("/list", web::get(render_list))
}
}
@ -21,6 +23,13 @@ async fn render_page(request: HttpRequest) -> Result<Markup, ErrorPage> {
.await
}
async fn render_list(request: HttpRequest) -> Result<Markup, ErrorPage> {
Page::new(request)
.with_child(ListView::new().with_table(Table::new().with_column(Lc::n("Name"))))
.render()
.await
}
// All tests in this file share the same root extension (`TestApp`), since `EXTENSIONS` is a global
// `OnceLock` initialized only once per test binary (see `core/extension/all.rs`).
@ -60,3 +69,22 @@ async fn rendered_pages_automatically_include_the_pinned_htmx_script_tag() {
assert!(body.contains("defer"));
assert!(body.contains("<p>hello</p>"));
}
// **< List loading styles >************************************************************************
#[pagetop::test]
async fn pages_with_a_list_embed_the_list_loading_styles_and_others_do_not() {
let app = web::test::init_router(Application::prepare(&TestApp).await.test());
let req = web::test::TestRequest::get().uri("/list").to_request();
let body = web::test::read_body_text(web::test::send_request(&app, req).await).await;
// HTMX sets `htmx-request` on the element named by `hx-indicator`: the list.
assert!(
body.contains(".list-view.htmx-request{opacity:0.5}"),
"{body}"
);
let req = web::test::TestRequest::get().uri("/page").to_request();
let body = web::test::read_body_text(web::test::send_request(&app, req).await).await;
assert!(!body.contains("htmx-request"), "{body}");
}

View file

@ -0,0 +1,100 @@
use pagetop::prelude::*;
use pagetop_htmx::prelude::*;
// Forces an effective language different from the default negotiated one (en-US, with no `?lang` in
// the request), so that `Context::route()` decides to propagate `?lang=...` in local routes.
fn cx_with_lang(lang: &str) -> Context {
Context::default().with_langid(&Locale::resolve(lang))
}
// **< hx_pager::boost() >**************************************************************************
#[pagetop::test]
async fn boost_targets_the_list_from_the_pager_nav() {
let mut pager = hx_pager::boost(
Pager::new()
.with_base_path("/items")
.with_current_page(1)
.with_items_per_page(10)
.with_total_items(50),
"#item-list",
);
let html = pager.render(&mut Context::default()).await.into_string();
assert!(html.contains(r#"hx-boost="true""#), "{html}");
assert!(html.contains(r##"hx-target="#item-list""##), "{html}");
assert!(html.contains(r#"hx-swap="outerHTML scroll:top""#), "{html}");
assert!(html.contains(r#"hx-push-url="true""#), "{html}");
}
// **< hx_filter::boost() >*************************************************************************
#[pagetop::test]
async fn boost_sends_the_filter_form_to_the_list() {
let mut filter = hx_filter::boost(
ListFilter::new()
.with_filter_action("/items")
.with_field(form::input::Field::search().with_name("q")),
"#item-list",
);
let html = filter.render(&mut Context::default()).await.into_string();
// `hx-boost` on the form sends its fields to its own `action`, so no `hx-get` is needed.
assert!(html.contains(r#"hx-boost="true""#), "{html}");
assert!(!html.contains("hx-get"), "{html}");
// When it applies is up to the filter (button or auto submit), not to HTMX.
assert!(!html.contains("hx-trigger"), "{html}");
assert!(html.contains(r##"hx-target="#item-list""##), "{html}");
assert!(html.contains(r#"hx-push-url="true""#), "{html}");
}
#[pagetop::test]
async fn boosted_filter_keeps_the_language_in_a_hidden_field() {
// A boosted GET form drops the query of its `action`, the same as the browser does.
let mut filter = hx_filter::boost(
ListFilter::new()
.with_filter_action("/items")
.with_field(form::input::Field::search().with_name("q")),
"#item-list",
);
let html = filter
.render(&mut cx_with_lang("es-ES"))
.await
.into_string();
assert!(html.contains(r#"name="lang""#), "{html}");
assert!(html.contains(r#"value="es-ES""#), "{html}");
}
// **< Overlapping requests and loading indicator >*************************************************
#[pagetop::test]
async fn list_helpers_cancel_overlapping_requests_and_mark_the_list_while_loading() {
let mut pager = hx_pager::boost(
Pager::new()
.with_base_path("/items")
.with_current_page(1)
.with_items_per_page(10)
.with_total_items(50),
"#item-list",
);
let mut filter = hx_filter::boost(ListFilter::new().with_filter_action("/items"), "#item-list");
let mut table = Table::new().with_column(
table::Column::new(Lc::n("Name")).with_sort(hx_table::sort_link(
"/items",
"#item-list",
None,
)),
);
let mut cx = Context::default();
for html in [
pager.render(&mut cx).await.into_string(),
filter.render(&mut cx).await.into_string(),
table.render(&mut cx).await.into_string(),
] {
// Every request against the list cancels the one in progress, wherever it comes from.
assert!(html.contains(r##"hx-sync="#item-list:replace""##), "{html}");
assert!(html.contains(r##"hx-indicator="#item-list""##), "{html}");
}
}

View file

@ -15,7 +15,7 @@ async fn render_column(column: table::Column) -> String {
// **< sort_link() - htmx attributes >**************************************************************
#[pagetop::test]
async fn sort_link_sets_the_four_fixed_htmx_attributes() {
async fn sort_link_sets_the_fixed_htmx_attributes() {
let column = table::Column::new(Lc::n("User")).with_sort(hx_table::sort_link(
"/admin/users",
"#user-table",

View file

@ -36,7 +36,7 @@ use pagetop::prelude::*;
use crate::Email;
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::sync::Mutex;
static OUTBOX: Mutex<Vec<SentEmail>> = Mutex::new(Vec::new());
@ -99,13 +99,13 @@ fn unescape(value: &str) -> String {
/// Recoge todos los correos guardados, en el orden en que se enviaron.
pub fn take() -> Vec<SentEmail> {
std::mem::take(&mut *lock())
std::mem::take(&mut *OUTBOX.lock().unwrap())
}
/// Recoge los correos entregados a la dirección dada, en el orden en que se enviaron, y deja los
/// demás.
pub fn take_to(address: &str) -> Vec<SentEmail> {
let mut outbox = lock();
let mut outbox = OUTBOX.lock().unwrap();
let (taken, kept) = outbox
.drain(..)
.partition(|sent: &SentEmail| sent.is_delivered_to(address));
@ -114,18 +114,13 @@ pub fn take_to(address: &str) -> Vec<SentEmail> {
}
pub(crate) fn push(email: Email, envelope_to: Vec<String>, raw: Vec<u8>) {
lock().push(SentEmail {
OUTBOX.lock().unwrap().push(SentEmail {
email,
envelope_to,
raw: String::from_utf8_lossy(&raw).into_owned(),
});
}
// Una prueba que falla con el bloqueo tomado no debe impedir que las demás sigan usándolo.
fn lock() -> MutexGuard<'static, Vec<SentEmail>> {
OUTBOX.lock().unwrap_or_else(PoisonError::into_inner)
}
// Correos completos de la cola de envío pendientes de entregar con este transporte, por su
// identificador en la cola. La cola sólo guarda el mensaje compuesto, y las pruebas necesitan el
// correo completo para consultarlo con `SentEmail::email()`.
@ -134,15 +129,12 @@ static QUEUED: Mutex<Vec<(i32, Email)>> = Mutex::new(Vec::new());
#[cfg(feature = "queue")]
pub(crate) fn hold(id: i32, email: Email) {
QUEUED
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push((id, email));
QUEUED.lock().unwrap().push((id, email));
}
#[cfg(feature = "queue")]
pub(crate) fn release(id: i32) -> Option<Email> {
let mut queued = QUEUED.lock().unwrap_or_else(PoisonError::into_inner);
let mut queued = QUEUED.lock().unwrap();
let index = queued.iter().position(|(queued_id, _)| *queued_id == id)?;
Some(queued.swap_remove(index).1)
}

View file

@ -159,7 +159,7 @@ pub(crate) async fn preview_get(
) -> Result<Markup, ErrorPage> {
let previews = MailPreviews::collect();
let Some(preview) = previews.previews.iter().find(|p| p.key == key) else {
return Err(ErrorPage::NotFound(Some(request)));
return Err(ErrorPage::NotFound(request));
};
let cx = Context::new(request.clone());
let email = transport::prepare_preview((preview.build)(&cx));

View file

@ -159,6 +159,25 @@ frenar a quien prueba unas pocas contraseñas habituales en muchas cuentas sin l
ninguna. Detrás de un *proxy* inverso, los límites por IP requieren configurar
`server.client_ip_header`.
## Cookies
Al iniciar sesión se crea la *cookie* de sesión (`cookie_name` de `[user.session]`, `pagetop` por
defecto). Es propia, `HttpOnly` y con un identificador aleatorio que la aplicación guarda en la base
de datos. Se borra al cerrar sesión.
Sin marcar "Recuérdame", el navegador la borra al cerrarse, y la sesión deja de valer tras
`idle_secs` sin uso. Es una *cookie* de autenticación para un servicio que el propio usuario pide,
así que en España y en la Unión Europea no requiere su aceptación: las normas y guías en que se basa
están en la sección *Cookies* del módulo `web` de PageTop.
Con "Recuérdame", la sesión se conserva aunque se cierre el navegador, hasta `remember_idle_secs`
sin uso (14 días por defecto). El dictamen 04/2012 del Grupo de Trabajo del Artículo 29 (WP194) no
exime estas *cookies* de inicio de sesión persistente, pero considera suficiente que sea el usuario
quien la pida marcando expresamente la casilla, siempre que sepa que se usa una *cookie*. Por eso el
formulario de acceso lo indica en el texto de ayuda de la casilla, que además desaconseja marcarla
en un equipo compartido. La aplicación sólo tiene que declararla también en su política de
*cookies*.
## Créditos
Este *crate* guarda las contraseñas con el algoritmo Argon2 mediante

View file

@ -22,6 +22,11 @@ max_ip_requests = 3
max_ip_failed_logins = 3
max_email_changes = 2
# Sesiones con "Recuérdame" renovadas en cada petición, para probar que la renovación convive con
# otras cookies de la respuesta.
[user.session]
write_interval_secs = 0
# Costes mínimos de Argon2id: las pruebas cifran muchas contraseñas.
[user.password]
argon2_m_cost = 64

View file

@ -24,11 +24,11 @@ pub use user_name::UserName;
use pagetop::prelude::*;
use crate::LOCALES_USER;
use crate::account::UserStatus;
use crate::component::admin::status_key;
use crate::config::{user_language_applies, user_timezone_applies};
use crate::entity::user;
use crate::{LOCALES_USER, PROFILE_PATH};
// Texto libre de varias líneas como contenido seguro: cada salto de línea se convierte en `<br>`,
// sin depender del CSS del tema. Se usa para mostrar el "Sobre mí" del usuario.
@ -87,6 +87,27 @@ pub(crate) fn error_banner(error: Option<Lc>) -> Html {
})
}
// Enlace para salir de un formulario sin guardar.
pub(crate) fn cancel_link(route: impl Into<Route>) -> Button {
Button::anchor(Lc::t("btn-cancel", &LOCALES_USER), route).with_style(button::Style::Link)
}
// Botonera de un formulario: el botón de envío y, en la misma fila, el enlace para salir sin
// guardar.
pub(crate) fn form_actions(submit: Lc, cancel: impl Into<Route>) -> Flex {
Flex::new()
.with_wrap(flex::Behavior::Wrap)
.with_align(align::Items::Center)
.with_gap(align::Gap::Both(UnitValue::RelRem(0.5)))
.with_child(Button::submit(submit).with_style(button::Style::Solid(Intent::Primary)))
.with_child(cancel_link(cancel))
}
// Botonera de los formularios del perfil propio, que al cancelar vuelven al perfil.
pub(crate) fn profile_form_actions(submit: Lc, cx: &Context) -> Flex {
form_actions(submit, cx.route(PROFILE_PATH))
}
// Bloque de sólo lectura con los datos de perfil de un usuario, para «Mi cuenta» y para la ficha de
// administración.
pub(crate) async fn user_details(user: &user::Model, cx: &mut Context) -> Block {

View file

@ -12,7 +12,7 @@ mod user_table;
pub(crate) use admin_password_form::AdminPasswordForm;
pub(crate) use role_form::{RoleForm, RoleFormMode};
pub(crate) use role_permissions_form::RolePermissionsForm;
pub(crate) use role_table::RoleTable;
pub(crate) use role_table::{RoleTable, delete_dialog};
pub(crate) use user_form::{UserForm, UserFormMode};
pub(crate) use user_table::{UserTable, status_key};

View file

@ -5,14 +5,12 @@ use pagetop::prelude::*;
use crate::LOCALES_USER;
use crate::user_path;
use crate::component::{PasswordConfirm, error_banner};
use crate::component::{PasswordConfirm, error_banner, form_actions};
#[derive(AutoDefault, Clone, Debug, Getters)]
pub(crate) struct AdminPasswordForm {
user_id: i32,
error: Option<Lc>,
/// Listado de origen al que volver tras guardar (orden, búsqueda, página).
waypoint: Waypoint,
}
#[async_trait]
@ -23,7 +21,7 @@ impl Component for AdminPasswordForm {
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let action = user_path(self.user_id(), "password");
let action = self.waypoint().append_to(cx.route(action));
let action = cx.route(action);
let mut form = Form::new()
.with_id("user-admin-password-form")
@ -34,10 +32,10 @@ impl Component for AdminPasswordForm {
PasswordConfirm::new()
.with_password_label(Lc::t("field-new-password", &LOCALES_USER)),
)
.with_child(
Button::submit(Lc::t("btn-save", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
);
.with_child(form_actions(
Lc::t("btn-save", &LOCALES_USER),
cx.route(user_path(self.user_id(), "edit")),
));
Ok(form.render(cx).await)
}
@ -56,9 +54,4 @@ impl AdminPasswordForm {
self.error = error.into();
self
}
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into();
self
}
}

View file

@ -6,7 +6,7 @@ use crate::ADMIN_ROLES_PATH;
use crate::LOCALES_USER;
use crate::role_path;
use crate::component::error_banner;
use crate::component::{error_banner, form_actions};
use crate::service::role_admin::{ROLE_LABEL_MAX_CHARS, ROLE_MACHINE_NAME_MAX_CHARS};
#[derive(AutoDefault, Clone, Copy, Debug, PartialEq)]
@ -21,8 +21,6 @@ pub(crate) struct RoleForm {
mode: RoleFormMode,
error: Option<Lc>,
role_id: Option<i32>,
/// Listado de origen al que volver tras guardar (orden).
waypoint: Waypoint,
machine_name: String,
label: String,
description: String,
@ -40,7 +38,7 @@ impl Component for RoleForm {
RoleFormMode::New => util::join!(ADMIN_ROLES_PATH.as_str(), "/new"),
RoleFormMode::Edit => role_path(self.role_id().copied().unwrap_or_default(), "edit"),
};
let action = self.waypoint().append_to(cx.route(action));
let action = cx.route(action);
let machine_name_field = match self.mode() {
RoleFormMode::New => form::input::Field::text()
@ -86,10 +84,10 @@ impl Component for RoleForm {
.with_inputmode(Some(form::input::Mode::Numeric)),
);
form = form.with_child(
Button::submit(Lc::t("btn-save", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
);
form = form.with_child(form_actions(
Lc::t("btn-save", &LOCALES_USER),
cx.route(ADMIN_ROLES_PATH.as_str()),
));
Ok(form.render(cx).await)
}
@ -114,11 +112,6 @@ impl RoleForm {
self
}
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into();
self
}
pub(crate) fn with_machine_name(mut self, machine_name: impl Into<String>) -> Self {
self.machine_name = machine_name.into();
self

View file

@ -4,7 +4,9 @@
use pagetop::prelude::*;
use crate::ADMIN_ROLES_PATH;
use crate::LOCALES_USER;
use crate::component::form_actions;
use crate::role_path;
use crate::component::admin::PermissionGroups;
@ -15,8 +17,6 @@ pub(crate) struct RolePermissionsForm {
role_id: i32,
error: Option<Lc>,
groups: PermissionGroups,
/// Listado de origen al que volver tras guardar (orden).
waypoint: Waypoint,
}
#[async_trait]
@ -27,7 +27,7 @@ impl Component for RolePermissionsForm {
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let action = role_path(self.role_id(), "permissions");
let action = self.waypoint().append_to(cx.route(action));
let action = cx.route(action);
let mut form = Form::new()
.with_id("role-permissions-form")
@ -52,10 +52,10 @@ impl Component for RolePermissionsForm {
form = form.with_child(fieldset);
}
form = form.with_child(
Button::submit(Lc::t("btn-save", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
);
form = form.with_child(form_actions(
Lc::t("btn-save", &LOCALES_USER),
cx.route(ADMIN_ROLES_PATH.as_str()),
));
Ok(form.render(cx).await)
}
@ -79,9 +79,4 @@ impl RolePermissionsForm {
self.groups = groups;
self
}
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into();
self
}
}

View file

@ -1,8 +1,8 @@
//! Tabla de roles: cabeceras ordenables y filas con acciones.
//! Listado de roles: cabeceras ordenables y filas con acciones, en un `ListView`.
use pagetop::prelude::*;
use pagetop_htmx::hx;
use pagetop_htmx::hx_table::sort_link;
use pagetop_htmx::{hx, hx_pager};
use crate::ADMIN_ROLES_PATH;
use crate::LOCALES_USER;
@ -12,7 +12,6 @@ use crate::service::role_admin::{RoleListItem, RoleSortField};
#[derive(AutoDefault, Clone, Debug, Getters)]
pub(crate) struct RoleTable {
props: Props,
items: Vec<RoleListItem>,
sort: RoleSortField,
dir: SortDir,
@ -29,15 +28,6 @@ impl Component for RoleTable {
Self::default()
}
fn id(&self) -> Option<String> {
self.props.get_id()
}
fn setup(&mut self, _cx: &mut Context) {
self.alter_prop(PropsOp::set_id("role-table-wrapper"));
self.alter_prop(PropsOp::prepend_classes("user-admin-table-wrapper"));
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let pager = Pager::new()
.with_base_path(ADMIN_ROLES_PATH.as_str())
@ -45,13 +35,7 @@ impl Component for RoleTable {
.with_extra_query("dir", *self.dir())
.with_current_page(self.page())
.with_items_per_page(self.per_page())
.with_total_items(self.total())
.with_prop(PropsOp::set(hx::BOOST, "true"))
.with_prop(PropsOp::set(hx::TARGET, "#role-table-wrapper"))
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP))
.with_prop(PropsOp::set(hx::PUSH_URL, "true"))
.render(cx)
.await;
.with_total_items(self.total());
let mut table = Table::new()
.with_prop(PropsOp::add_classes("user-admin-table"))
@ -62,23 +46,6 @@ impl Component for RoleTable {
.with_column(Lc::t("col-actions", &LOCALES_USER))
.with_empty(Lc::t("empty-roles-list", &LOCALES_USER));
let confirm_dialog = Dialog::new()
.with_id("confirm-delete-role")
.with_child(Html::with(|cx| {
html! { p { (Lc::t("confirm-delete-role", &LOCALES_USER).using(cx)) } }
}))
.with_footer(
Button::plain(Lc::t("btn-cancel", &LOCALES_USER))
.with_prop(PropsOp::set("data-dialog-dismiss", "modal")),
)
.with_footer(Html::with(
|_cx| html! { span id="role-delete-confirm-action" {} },
))
.render(cx)
.await;
let waypoint = Waypoint::from(self.list_href(cx));
for role in self.items() {
let system_badge = if role.locked {
Some(
@ -102,7 +69,7 @@ impl Component for RoleTable {
table.alter_row(
table::Row::new()
.with_cell(role.machine_name.as_str())
.with_cell(label_cell(role, &waypoint))
.with_cell(label_cell(role))
.with_cell(Html::with(move |_cx| {
html! {
@if let Some(badge) = &system_badge { (badge) }
@ -111,37 +78,50 @@ impl Component for RoleTable {
}))
.with_cell(role.user_count.to_string())
.with_cell(
actions_cell(role, &waypoint, *self.sort(), *self.dir(), self.page(), cx)
.await,
actions_cell(role, *self.sort(), *self.dir(), self.page(), cx).await,
),
);
}
let new_href = waypoint.append_to(cx.route(util::join!(ADMIN_ROLES_PATH.as_str(), "/new")));
let new_href = cx.route(util::join!(ADMIN_ROLES_PATH.as_str(), "/new"));
Ok(html! {
div (self.props().unpack(cx)) {
(Button::anchor(Lc::t("btn-create-role", &LOCALES_USER), new_href).render(cx).await)
@if let Some(message) = self.message() {
div class="user-form-error" role="alert" { (message.clone().using(cx)) }
if let Some(message) = self.message() {
cx.push_message(MessageLevel::Error, message.clone());
}
(table.render(cx).await)
(pager)
(confirm_dialog)
}
})
let mut list = ListView::new()
.with_id("role-table-wrapper")
.with_action(
Button::anchor(Lc::t("btn-create-role", &LOCALES_USER), new_href)
.with_style(button::Style::Solid(Intent::Primary)),
)
.with_table(table)
.with_pager(hx_pager::boost(pager, "#role-table-wrapper"));
Ok(list.render(cx).await)
}
}
// Diálogo de confirmación de borrado, compartido por todas las filas: el botón de borrar de cada
// una lo abre y carga en él su botón de confirmación (ver `delete_confirm_get` en los *handlers* de
// roles). Va en la página, fuera del listado, para que HTMX no lo reemplace al actualizarlo.
pub(crate) fn delete_dialog() -> Dialog {
Dialog::new()
.with_id("confirm-delete-role")
.with_child(Html::with(|cx| {
html! { p { (Lc::t("confirm-delete-role", &LOCALES_USER).using(cx)) } }
}))
.with_footer(
Button::plain(Lc::t("btn-cancel", &LOCALES_USER))
.with_prop(PropsOp::set("data-dialog-dismiss", "modal")),
)
.with_footer(Html::with(
|_cx| html! { span id="role-delete-confirm-action" {} },
))
}
#[builder_impl]
impl RoleTable {
// **< RoleTable BUILDER >**********************************************************************
pub(crate) fn with_prop(mut self, op: impl Into<PropsOp>) -> Self {
self.props.alter_prop(op);
self
}
pub(crate) fn with_items(mut self, items: Vec<RoleListItem>) -> Self {
self.items = items;
self
@ -177,17 +157,6 @@ impl RoleTable {
self
}
// URL del listado con el estado actual (orden, página): es el valor que viaja como `waypoint`
// en los enlaces de ver/editar/permisos, para poder volver exactamente a este mismo estado. Se
// construye con `cx.route()` para que preserve el parámetro `lang` cuando corresponda.
fn list_href(&self, cx: &Context) -> String {
cx.route(ADMIN_ROLES_PATH.as_str())
.alter_param("sort", self.sort().as_str())
.alter_param("dir", *self.dir())
.alter_param("page", self.page().to_string())
.to_string()
}
// Construye la cabecera ordenable de una columna: el enlace ya funciona sin HTMX (navega con
// una petición normal); `pagetop_htmx::hx_table::sort_link()` añade aparte los atributos `hx-*`
// para que la tabla se actualice sin recargar la página cuando la extensión esté disponible.
@ -216,12 +185,11 @@ impl RoleTable {
// Construye la celda de etiqueta: enlaza a la pantalla de sólo lectura con todos los permisos del
// rol. Devuelve un componente `Html` para que el marcado se genere cuando `Table` renderice la
// celda, no al construir la fila.
fn label_cell(role: &RoleListItem, waypoint: &Waypoint) -> Html {
fn label_cell(role: &RoleListItem) -> Html {
let label = crate::role_label(role.id, &role.label);
let id = role.id;
let waypoint = waypoint.clone();
Html::with(move |cx| {
let view_href = waypoint.append_to(cx.route(role_path(id, "view")));
let view_href = cx.route(role_path(id, "view"));
html! {
a href=(view_href) { (label.using(cx)) }
}
@ -233,7 +201,6 @@ fn label_cell(role: &RoleListItem, waypoint: &Waypoint) -> Html {
// que el marcado se genere cuando `Table` renderice la celda, no al construir la fila.
async fn actions_cell(
role: &RoleListItem,
waypoint: &Waypoint,
sort: RoleSortField,
dir: SortDir,
page: u64,
@ -241,7 +208,6 @@ async fn actions_cell(
) -> Html {
let id = role.id;
let locked = role.locked;
let waypoint = waypoint.clone();
let can_manage_permissions = cx
.request()
@ -252,7 +218,7 @@ async fn actions_cell(
// (ver `pagetop-bootsier::theme::bs::button`), incluida la traducción de `data-dialog-*` que
// usa el botón de borrado.
let permissions_button = if can_manage_permissions {
let permissions_href = waypoint.append_to(cx.route(role_path(id, "permissions")));
let permissions_href = cx.route(role_path(id, "permissions"));
Some(
Button::anchor(
Lc::t("btn-manage-permissions", &LOCALES_USER),
@ -270,7 +236,7 @@ async fn actions_cell(
let (edit_button, delete_button) = if locked {
(None, None)
} else {
let edit_href = waypoint.append_to(cx.route(role_path(id, "edit")));
let edit_href = cx.route(role_path(id, "edit"));
let edit_button = Button::anchor(Lc::t("btn-edit", &LOCALES_USER), edit_href)
.with_style(button::Style::Solid(Intent::Primary))
.with_size(button::Size::Small)

View file

@ -7,7 +7,7 @@ use crate::config::{SETTINGS, user_language_applies, user_timezone_applies};
use crate::user_path;
use crate::{ADMIN_USERS_PATH, PROFILE_EDIT_PATH};
use crate::component::{PasswordConfirm, error_banner};
use crate::component::{PasswordConfirm, error_banner, form_actions, profile_form_actions};
use crate::identity::{EMAIL_MAX_CHARS, USERNAME_MIN_CHARS, username_help, username_max_chars};
use crate::service::user_admin::{ABOUT_MAX_CHARS, DISPLAY_NAME_MAX_CHARS};
@ -27,8 +27,6 @@ pub(crate) struct UserForm {
mode: UserFormMode,
error: Option<Lc>,
user_id: Option<i32>,
/// Listado de origen al que volver tras guardar (orden, búsqueda, página).
waypoint: Waypoint,
username: String,
email: String,
display_name: String,
@ -63,7 +61,7 @@ impl Component for UserForm {
// El propio usuario cambia su email en otra pantalla, que pide su contraseña y confirma la
// nueva dirección antes de aplicarla.
let email_readonly = *self.mode() == UserFormMode::Profile;
let action = self.waypoint().append_to(cx.route(action));
let action = cx.route(action);
let mut form = Form::new()
.with_id(USER_ADMIN_FORM_ID)
@ -159,14 +157,18 @@ impl Component for UserForm {
);
}
// En modo `Edit`, "Guardar" se renderiza fuera del formulario, junto al resto de acciones
// de la pantalla (ver `USER_ADMIN_FORM_ID`); en los demás modos no hay ninguna botonera con
// la que agruparlo, así que se queda aquí, dentro del propio `<form>`.
if *self.mode() != UserFormMode::Edit {
form = form.with_child(
Button::submit(Lc::t("btn-save", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
);
// En modo `Edit`, "Guardar" y "Cancelar" se renderizan fuera del formulario, junto al resto
// de acciones de la pantalla (ver `USER_ADMIN_FORM_ID`).
let save = Lc::t("btn-save", &LOCALES_USER);
match self.mode() {
UserFormMode::Edit => {}
UserFormMode::Profile => {
form = form.with_child(profile_form_actions(save, cx));
}
UserFormMode::New => {
let cancel = cx.route(ADMIN_USERS_PATH.as_str());
form = form.with_child(form_actions(save, cancel));
}
}
Ok(form.render(cx).await)
@ -192,11 +194,6 @@ impl UserForm {
self
}
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into();
self
}
pub(crate) fn with_username(mut self, username: impl Into<String>) -> Self {
self.username = username.into();
self

View file

@ -1,7 +1,7 @@
//! Tabla de usuarios: cabeceras ordenables, filas y paginación embebida.
//! Listado de usuarios: cabeceras ordenables, filas y paginación, en un `ListView`.
use pagetop::prelude::*;
use pagetop_htmx::hx;
use pagetop_htmx::hx_pager;
use pagetop_htmx::hx_table::sort_link;
use crate::ADMIN_USERS_PATH;
@ -12,7 +12,6 @@ use crate::user_path;
#[derive(AutoDefault, Clone, Debug, Getters)]
pub(crate) struct UserTable {
props: Props,
items: Vec<UserListItem>,
sort: UserSortField,
dir: SortDir,
@ -28,15 +27,6 @@ impl Component for UserTable {
Self::default()
}
fn id(&self) -> Option<String> {
self.props.get_id()
}
fn setup(&mut self, _cx: &mut Context) {
self.alter_prop(PropsOp::set_id("user-table-wrapper"));
self.alter_prop(PropsOp::prepend_classes("user-admin-table-wrapper"));
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let pager = Pager::new()
.with_base_path(ADMIN_USERS_PATH.as_str())
@ -45,13 +35,7 @@ impl Component for UserTable {
.with_extra_query("dir", *self.dir())
.with_current_page(self.page())
.with_items_per_page(self.per_page())
.with_total_items(self.total())
.with_prop(PropsOp::set(hx::BOOST, "true"))
.with_prop(PropsOp::set(hx::TARGET, "#user-table-wrapper"))
.with_prop(PropsOp::set(hx::SWAP, hx::swap::OUTER_HTML_SCROLL_TOP))
.with_prop(PropsOp::set(hx::PUSH_URL, "true"))
.render(cx)
.await;
.with_total_items(self.total());
let mut table = Table::new()
.with_prop(PropsOp::add_classes("user-admin-table"))
@ -63,7 +47,6 @@ impl Component for UserTable {
.with_column(Lc::t("col-actions", &LOCALES_USER))
.with_empty(Lc::t("empty-users-list", &LOCALES_USER));
let waypoint = Waypoint::from(self.list_href(cx));
let viewer_is_admin = cx
.request()
.and_then(|r| r.extension::<Account>())
@ -74,24 +57,26 @@ impl Component for UserTable {
table.alter_row(
table::Row::new()
.with_cell(username_cell(user, &waypoint))
.with_cell(username_cell(user))
.with_cell(user.email.as_str())
.with_cell(user.display_name.as_deref().unwrap_or("-"))
.with_cell(roles_cell(user, cx).await)
.with_cell(Lc::t(status_key(status), &LOCALES_USER))
.with_cell(actions_cell(user, &waypoint, viewer_is_admin, cx).await),
.with_cell(actions_cell(user, viewer_is_admin, cx).await),
);
}
let new_href = waypoint.append_to(cx.route(util::join!(ADMIN_USERS_PATH.as_str(), "/new")));
let new_href = cx.route(util::join!(ADMIN_USERS_PATH.as_str(), "/new"));
Ok(html! {
div (self.props().unpack(cx)) {
(Button::anchor(Lc::t("btn-create-user", &LOCALES_USER), new_href).render(cx).await)
(table.render(cx).await)
(pager)
}
})
let mut list = ListView::new()
.with_id("user-table-wrapper")
.with_action(
Button::anchor(Lc::t("btn-create-user", &LOCALES_USER), new_href)
.with_style(button::Style::Solid(Intent::Primary)),
)
.with_table(table)
.with_pager(hx_pager::boost(pager, "#user-table-wrapper"));
Ok(list.render(cx).await)
}
}
@ -99,11 +84,6 @@ impl Component for UserTable {
impl UserTable {
// **< UserTable BUILDER >**********************************************************************
pub(crate) fn with_prop(mut self, op: impl Into<PropsOp>) -> Self {
self.props.alter_prop(op);
self
}
pub(crate) fn with_items(mut self, items: Vec<UserListItem>) -> Self {
self.items = items;
self
@ -139,21 +119,6 @@ impl UserTable {
self
}
// URL del listado con el estado actual (búsqueda, orden, página): es el valor que viaja como
// `waypoint` en los enlaces de ver/editar, para poder volver exactamente a este mismo estado.
// Se construye con `cx.route()` para que preserve el parámetro `lang` cuando corresponda.
fn list_href(&self, cx: &Context) -> String {
let mut route = cx.route(ADMIN_USERS_PATH.as_str());
if let Some(q) = self.query().filter(|q| !q.is_empty()) {
route.alter_param("q", q);
}
route
.alter_param("sort", self.sort().as_str())
.alter_param("dir", *self.dir())
.alter_param("page", self.page().to_string())
.to_string()
}
// Construye la cabecera ordenable de una columna: el enlace ya funciona sin HTMX (navega con
// una petición normal); `pagetop_htmx::hx_table::sort_link()` añade aparte los atributos `hx-*`
// para que la tabla se actualice sin recargar la página cuando la extensión esté disponible.
@ -186,12 +151,11 @@ impl UserTable {
// Construye la celda de usuario: el nombre enlaza a la pantalla de sólo lectura con todos sus
// datos y roles. Devuelve un componente `Html` para que el marcado se genere cuando `Table`
// renderice la celda, no al construir la fila.
fn username_cell(user: &UserListItem, waypoint: &Waypoint) -> Html {
fn username_cell(user: &UserListItem) -> Html {
let username = user.username.clone();
let id = user.id;
let waypoint = waypoint.clone();
Html::with(move |cx| {
let view_href = waypoint.append_to(cx.route(user_path(id, "view")));
let view_href = cx.route(user_path(id, "view"));
html! {
a href=(view_href) { (username.as_str()) }
}
@ -202,16 +166,11 @@ fn username_cell(user: &UserListItem, waypoint: &Waypoint) -> Html {
// si quien mira no lo es (no puede gestionarla, ver `handlers::admin::users::require_manageable`).
// Devuelve un componente `Html` para que el marcado se genere cuando `Table` renderice la celda, no
// al construir la fila.
async fn actions_cell(
user: &UserListItem,
waypoint: &Waypoint,
viewer_is_admin: bool,
cx: &mut Context,
) -> Html {
async fn actions_cell(user: &UserListItem, viewer_is_admin: bool, cx: &mut Context) -> Html {
if user.is_admin && !viewer_is_admin {
return Html::default();
}
let edit_href = waypoint.append_to(cx.route(user_path(user.id, "edit")));
let edit_href = cx.route(user_path(user.id, "edit"));
// El botón se renderiza aquí, no dentro del `Html::with()` de abajo: necesita pasar por su
// propio ciclo de renderizado (`.render().await`) para que el tema activo lo estilice igual

View file

@ -4,7 +4,7 @@ use pagetop::prelude::*;
use crate::{EMAIL_PATH, LOCALES_USER};
use crate::component::error_banner;
use crate::component::{error_banner, profile_form_actions};
use crate::identity::EMAIL_MAX_CHARS;
/// Pide la nueva dirección y la contraseña actual. Si ya hay un cambio pendiente de confirmar, lo
@ -56,10 +56,10 @@ impl Component for ChangeEmailForm {
.with_autocomplete(Some(form::Autocomplete::current_password()))
.with_required(true),
)
.with_child(
Button::submit(Lc::t("btn-change-email", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
);
.with_child(profile_form_actions(
Lc::t("btn-change-email", &LOCALES_USER),
cx,
));
Ok(form.render(cx).await)
}

View file

@ -4,7 +4,7 @@ use pagetop::prelude::*;
use crate::{LOCALES_USER, PROFILE_PASSWORD_PATH};
use crate::component::{PasswordConfirm, error_banner};
use crate::component::{PasswordConfirm, error_banner, profile_form_actions};
/// Pide la contraseña actual además de la nueva y su confirmación, a diferencia del
/// restablecimiento por un administrador.
@ -36,10 +36,10 @@ impl Component for ChangePasswordForm {
PasswordConfirm::new()
.with_password_label(Lc::t("field-new-password", &LOCALES_USER)),
)
.with_child(
Button::submit(Lc::t("btn-set-password", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
);
.with_child(profile_form_actions(
Lc::t("btn-set-password", &LOCALES_USER),
cx,
));
Ok(form.render(cx).await)
}

View file

@ -59,9 +59,13 @@ impl Component for LoginForm {
.with_child(
form::Checkbox::check()
.with_name("remember")
.with_label(Lc::t("field-remember-me", &LOCALES_USER)),
.with_label(Lc::t("field-remember-me", &LOCALES_USER))
.with_help_text(Lc::t("help-remember-me", &LOCALES_USER)),
)
.with_child(
Button::submit(Lc::t("btn-login", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
)
.with_child(Button::submit(Lc::t("btn-login", &LOCALES_USER)))
.with_child(links(SETTINGS.allow_registration));
if strict {

View file

@ -27,7 +27,10 @@ impl Component for PasswordResetConfirmForm {
PasswordConfirm::new()
.with_password_label(Lc::t("field-new-password", &LOCALES_USER)),
)
.with_child(Button::submit(Lc::t("btn-set-password", &LOCALES_USER)));
.with_child(
Button::submit(Lc::t("btn-set-password", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
);
Ok(form.render(cx).await)
}

View file

@ -30,7 +30,10 @@ impl Component for PasswordResetForm {
.with_autofocus(true)
.with_required(true),
)
.with_child(Button::submit(Lc::t("btn-send-reset-link", &LOCALES_USER)))
.with_child(
Button::submit(Lc::t("btn-send-reset-link", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
)
.with_child(back_to_login());
Ok(form.render(cx).await)

View file

@ -49,7 +49,10 @@ impl Component for RegisterForm {
.with_required(true),
)
.with_child(PasswordConfirm::new())
.with_child(Button::submit(Lc::t("btn-register", &LOCALES_USER)));
.with_child(
Button::submit(Lc::t("btn-register", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
);
Ok(form.render(cx).await)
}

View file

@ -41,7 +41,7 @@ pub struct Model {
/// Último intento fallido, para saber si el siguiente cae dentro de la misma ventana.
pub failed_login_at: Option<DateTimeUtc>,
pub locked_until: Option<DateTimeUtc>,
/// Acceso irrestricto al sistema, sin pasar por roles ni permisos.
/// Acceso total al sistema, sin pasar por roles ni permisos.
pub is_admin: bool,
pub created_at: DateTimeUtc,
pub updated_at: DateTimeUtc,

View file

@ -96,11 +96,11 @@ pub(crate) async fn profile_get(request: HttpRequest) -> Response {
let user = match user_admin::find_user(id).await {
Ok(user) => user,
Err(_) => return ErrorPage::NotFound(Some(request)).into_response(),
Err(_) => return ErrorPage::NotFound(request).into_response(),
};
let roles = match user_admin::user_roles(id).await {
Ok(roles) => roles,
Err(_) => return ErrorPage::InternalError(Some(request)).into_response(),
Err(_) => return ErrorPage::InternalError(request).into_response(),
};
let can_edit = has_permission(&request, &UserPermission::EditOwnProfile);
let can_change_password = has_permission(&request, &UserPermission::ChangeOwnPassword);
@ -213,12 +213,12 @@ pub(crate) async fn public_profile_get(
return Ok(deny_access(request));
}
let Ok(user) = user_admin::find_user(id).await else {
return Err(ErrorPage::NotFound(Some(request)));
return Err(ErrorPage::NotFound(request));
};
if UserStatus::from_i16(user.status) != UserStatus::Active
&& !has_permission(&request, &UserPermission::AdminUsers)
{
return Err(ErrorPage::NotFound(Some(request)));
return Err(ErrorPage::NotFound(request));
}
let title = match util::non_blank(user.display_name.as_deref().unwrap_or_default()) {
@ -278,7 +278,7 @@ pub(crate) async fn profile_edit_get(request: HttpRequest) -> Result<Response, E
return Ok(login_redirect(request, PROFILE_EDIT_PATH));
};
let Ok(user) = user_admin::find_user(id).await else {
return Err(ErrorPage::NotFound(Some(request)));
return Err(ErrorPage::NotFound(request));
};
let form = UserForm::new()
@ -310,7 +310,7 @@ pub(crate) struct ProfileFormData {
/// POST /user/edit - Guarda los datos del perfil propio. El nombre de usuario sólo cambia con
/// `user:change_own_username`; el email, desde [`email_get()`]; roles, estado y acceso
/// irrestricto no se tocan nunca desde aquí.
/// total no se tocan nunca desde aquí.
pub(crate) async fn profile_edit_post(
request: HttpRequest,
web::Form(form): web::Form<ProfileFormData>,
@ -319,7 +319,7 @@ pub(crate) async fn profile_edit_post(
return Ok(login_redirect(request, PROFILE_EDIT_PATH));
};
let Ok(user) = user_admin::find_user(id).await else {
return Err(ErrorPage::NotFound(Some(request)));
return Err(ErrorPage::NotFound(request));
};
// Sin permiso se conserva el nombre actual, aunque la petición se haya manipulado a mano.
@ -432,7 +432,7 @@ pub(crate) async fn email_get(request: HttpRequest) -> Result<Response, ErrorPag
return Ok(login_redirect(request, EMAIL_PATH));
};
let Ok(user) = user_admin::find_user(id).await else {
return Err(ErrorPage::NotFound(Some(request)));
return Err(ErrorPage::NotFound(request));
};
let title = Lc::t("title-profile-email", &LOCALES_USER);
let form = ChangeEmailForm::new().with_pending_email(user.pending_email);
@ -508,7 +508,7 @@ pub(crate) async fn email_confirm_get(
.await
.unwrap_or(false)
{
return Err(ErrorPage::NotFound(Some(request)));
return Err(ErrorPage::NotFound(request));
}
Ok(no_referrer(
confirm_page(
@ -541,27 +541,21 @@ pub(crate) async fn email_confirm_post(
message_page(request, title, Lc::t("error-email-taken", &LOCALES_USER)).await,
)
}
Err(_) => ErrorPage::NotFound(Some(request)).into_response(),
Err(_) => ErrorPage::NotFound(request).into_response(),
}
}
// **< render_profile_page >************************************************************************
// Página del perfil propio con un formulario y un botón para volver al perfil sin guardar.
// Página del perfil propio con un formulario.
async fn render_profile_page(
request: HttpRequest,
title: Lc,
form: impl Component + 'static,
) -> Response {
let page = Page::new(request);
let cancel = Button::anchor(Lc::t("btn-cancel", &LOCALES_USER), page.route(PROFILE_PATH));
page.with_title(title.clone())
.with_child(
Block::new()
.with_title(title)
.with_child(form)
.with_child(cancel),
)
Page::new(request)
.with_title(title.clone())
.with_child(Block::new().with_title(title).with_child(form))
.render()
.await
.into_response()

View file

@ -59,14 +59,7 @@ pub(crate) fn map_auth_error(err: &AuthError) -> Lc {
}
}
// Enlace de vuelta al listado, usado en las pantallas de alta/edición/asignación.
pub(crate) fn back_link(href: impl Into<RoutePath>) -> Html {
let href = href.into();
Html::with(move |cx| {
html! {
p class="user-admin-back-link" {
a href=(href.clone()) { (Lc::t("link-back-to-list", &LOCALES_USER).using(cx)) }
}
}
})
// Enlace para salir de una ficha de sólo lectura. Los formularios tienen `form_actions()`.
pub(crate) fn back_link(route: impl Into<Route>) -> Button {
Button::anchor(Lc::t("link-back", &LOCALES_USER), route).with_style(button::Style::Link)
}

View file

@ -8,7 +8,7 @@ use pagetop_htmx::prelude::*;
use crate::ADMIN_ROLES_PATH;
use crate::LOCALES_USER;
use crate::component::admin::{
PermissionGroups, RoleForm, RoleFormMode, RolePermissionsForm, RoleTable,
PermissionGroups, RoleForm, RoleFormMode, RolePermissionsForm, RoleTable, delete_dialog,
};
use crate::config::SETTINGS;
use crate::entity::role;
@ -43,7 +43,7 @@ pub(crate) async fn list_get(
let result = match role_admin::list_roles_page(&params).await {
Ok(result) => result,
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
Err(_) => return Err(ErrorPage::InternalError(request)),
};
let mut table = RoleTable::new()
@ -62,6 +62,7 @@ pub(crate) async fn list_get(
Ok(Page::admin(request)
.with_title(title)
.with_child(table)
.with_child(delete_dialog())
.render()
.await
.into_response())
@ -71,21 +72,12 @@ pub(crate) async fn list_get(
// **< new_get / new_post >*************************************************************************
/// GET /admin/user/roles/new - Formulario de alta de rol.
pub(crate) async fn new_get(
request: HttpRequest,
web::Query(waypoint): web::Query<Waypoint>,
) -> Result<Response, ErrorPage> {
pub(crate) async fn new_get(request: HttpRequest) -> Result<Response, ErrorPage> {
let page = Page::admin(request);
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
let title = Lc::t("title-admin-role-new", &LOCALES_USER);
Ok(page
.with_title(title)
.with_child(
RoleForm::new()
.with_mode(RoleFormMode::New)
.with_waypoint(waypoint),
)
.with_child(back_link(back_href))
.with_child(RoleForm::new().with_mode(RoleFormMode::New))
.render()
.await
.into_response())
@ -104,7 +96,6 @@ pub(crate) struct NewRoleFormData {
/// POST /admin/user/roles/new - Crea un rol.
pub(crate) async fn new_post(
request: HttpRequest,
web::Query(waypoint): web::Query<Waypoint>,
web::Form(form): web::Form<NewRoleFormData>,
) -> Result<Response, ErrorPage> {
let weight: i32 = form.weight.trim().parse().unwrap_or(0);
@ -120,25 +111,22 @@ pub(crate) async fn new_post(
match result {
Ok(_) => {
let cx = Context::admin(request);
let target = waypoint.or(cx.route(ADMIN_ROLES_PATH.as_str()));
let target = cx.route(ADMIN_ROLES_PATH.as_str());
Ok(Redirect::see_other(target).into_response())
}
Err(err) => {
let page = Page::admin(request);
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
let form_component = RoleForm::new()
.with_mode(RoleFormMode::New)
.with_machine_name(form.machine_name)
.with_label(form.label)
.with_description(form.description)
.with_weight(weight)
.with_error(map_auth_error(&err))
.with_waypoint(waypoint);
.with_error(map_auth_error(&err));
let title = Lc::t("title-admin-role-new", &LOCALES_USER);
Ok(page
.with_title(title)
.with_child(form_component)
.with_child(back_link(back_href))
.render()
.await
.into_response())
@ -152,18 +140,16 @@ pub(crate) async fn new_post(
pub(crate) async fn edit_get(
request: HttpRequest,
web::Path(id): web::Path<i32>,
web::Query(waypoint): web::Query<Waypoint>,
) -> Result<Response, ErrorPage> {
let role = match role_admin::find_role(id).await {
Ok(role) => role,
Err(_) => return Err(ErrorPage::NotFound(Some(request))),
Err(_) => return Err(ErrorPage::NotFound(request)),
};
if role.locked {
return Err(ErrorPage::AccessDenied(Some(request)));
return Err(ErrorPage::AccessDenied(request));
}
let page = Page::admin(request);
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
let title = Lc::t("title-admin-role-edit", &LOCALES_USER);
Ok(page
@ -175,10 +161,8 @@ pub(crate) async fn edit_get(
.with_machine_name(role.machine_name)
.with_label(role.label)
.with_description(role.description.unwrap_or_default())
.with_weight(role.weight)
.with_waypoint(waypoint),
.with_weight(role.weight),
)
.with_child(back_link(back_href))
.render()
.await
.into_response())
@ -197,7 +181,6 @@ pub(crate) struct EditRoleFormData {
pub(crate) async fn edit_post(
request: HttpRequest,
web::Path(id): web::Path<i32>,
web::Query(waypoint): web::Query<Waypoint>,
web::Form(form): web::Form<EditRoleFormData>,
) -> Result<Response, ErrorPage> {
let weight: i32 = form.weight.trim().parse().unwrap_or(0);
@ -215,7 +198,7 @@ pub(crate) async fn edit_post(
match result {
Ok(()) => {
let cx = Context::admin(request);
let target = waypoint.or(cx.route(ADMIN_ROLES_PATH.as_str()));
let target = cx.route(ADMIN_ROLES_PATH.as_str());
Ok(Redirect::see_other(target).into_response())
}
Err(err) => {
@ -224,7 +207,6 @@ pub(crate) async fn edit_post(
.map(|role| role.machine_name)
.unwrap_or_default();
let page = Page::admin(request);
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
let form_component = RoleForm::new()
.with_mode(RoleFormMode::Edit)
.with_role_id(Some(id))
@ -232,13 +214,11 @@ pub(crate) async fn edit_post(
.with_label(form.label)
.with_description(form.description)
.with_weight(weight)
.with_error(map_auth_error(&err))
.with_waypoint(waypoint);
.with_error(map_auth_error(&err));
let title = Lc::t("title-admin-role-edit", &LOCALES_USER);
Ok(page
.with_title(title)
.with_child(form_component)
.with_child(back_link(back_href))
.render()
.await
.into_response())
@ -253,20 +233,19 @@ pub(crate) async fn edit_post(
pub(crate) async fn view_get(
request: HttpRequest,
web::Path(id): web::Path<i32>,
web::Query(waypoint): web::Query<Waypoint>,
) -> Result<Response, ErrorPage> {
let role = match role_admin::find_role(id).await {
Ok(role) => role,
Err(_) => return Err(ErrorPage::NotFound(Some(request))),
Err(_) => return Err(ErrorPage::NotFound(request)),
};
let selected = match role_admin::role_permission_keys(id).await {
Ok(keys) => keys,
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
Err(_) => return Err(ErrorPage::InternalError(request)),
};
let mut page = Page::admin(request);
let groups = build_permission_groups(&selected, page.context());
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
let back_href = page.route(ADMIN_ROLES_PATH.as_str());
let details_block = role_view_details(&role, page.context_mut()).await;
let title = Lc::t("title-admin-role-view", &LOCALES_USER);
@ -388,9 +367,9 @@ pub(crate) async fn delete_post(
let mut cx = Context::admin(request);
Ok(HtmxResponse::new(table.render(&mut cx).await).into_response())
} else {
let cx = Context::new(request);
match result {
Ok(()) => {
let cx = Context::new(request);
let target = cx
.route(ADMIN_ROLES_PATH.as_str())
.alter_param(
@ -402,7 +381,7 @@ pub(crate) async fn delete_post(
.to_string();
Ok(Redirect::see_other(target).into_response())
}
Err(_) => Err(ErrorPage::BadRequest(cx.request().cloned())),
Err(_) => Err(ErrorPage::BadRequest(request)),
}
}
}
@ -411,7 +390,7 @@ pub(crate) async fn delete_post(
/// GET /admin/user/roles/{id}/delete/confirm - Botón de confirmación de borrado para esta fila,
/// insertado vía htmx en el diálogo de confirmación compartido por toda la tabla (ver
/// `RoleTable`), con la URL de borrado de este rol ya incrustada.
/// `delete_dialog()`), con la URL de borrado de este rol ya incrustada.
///
/// Propaga `sort`/`dir`/`page` (recibidos como query string desde la propia fila) hacia la URL de
/// borrado, para que `delete_post` pueda volver a mostrar la misma página tras el borrado, en vez
@ -467,21 +446,19 @@ fn build_permission_groups(selected: &[String], cx: &Context) -> PermissionGroup
pub(crate) async fn permissions_get(
request: HttpRequest,
web::Path(id): web::Path<i32>,
web::Query(waypoint): web::Query<Waypoint>,
) -> Result<Response, ErrorPage> {
require_permission(&request, &UserPermission::AdminPermissions)?;
if role_admin::find_role(id).await.is_err() {
return Err(ErrorPage::NotFound(Some(request)));
return Err(ErrorPage::NotFound(request));
}
let selected = match role_admin::role_permission_keys(id).await {
Ok(keys) => keys,
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
Err(_) => return Err(ErrorPage::InternalError(request)),
};
let page = Page::admin(request);
let groups = build_permission_groups(&selected, page.context());
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
let title = Lc::t("title-admin-role-permissions", &LOCALES_USER);
Ok(page
@ -489,10 +466,8 @@ pub(crate) async fn permissions_get(
.with_child(
RolePermissionsForm::new()
.with_role_id(id)
.with_groups(groups)
.with_waypoint(waypoint),
.with_groups(groups),
)
.with_child(back_link(back_href))
.render()
.await
.into_response())
@ -511,36 +486,32 @@ pub(crate) struct RolePermissionsFormData {
pub(crate) async fn permissions_post(
request: HttpRequest,
web::Path(id): web::Path<i32>,
web::Query(waypoint): web::Query<Waypoint>,
raw: web::RawForm,
) -> Result<Response, ErrorPage> {
require_permission(&request, &UserPermission::AdminPermissions)?;
let Ok(form) = serde_qs::from_bytes::<RolePermissionsFormData>(&raw.0) else {
return Err(ErrorPage::BadRequest(Some(request)));
return Err(ErrorPage::BadRequest(request));
};
match role_admin::set_role_permissions(id, &form.permission_keys).await {
Ok(()) => {
let cx = Context::admin(request);
let target = waypoint.or(cx.route(ADMIN_ROLES_PATH.as_str()));
let target = cx.route(ADMIN_ROLES_PATH.as_str());
Ok(Redirect::see_other(target).into_response())
}
Err(err) => {
let page = Page::admin(request);
let groups = build_permission_groups(&form.permission_keys, page.context());
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
let form_component = RolePermissionsForm::new()
.with_role_id(id)
.with_groups(groups)
.with_error(map_auth_error(&err))
.with_waypoint(waypoint);
.with_error(map_auth_error(&err));
let title = Lc::t("title-admin-role-permissions", &LOCALES_USER);
Ok(page
.with_title(title)
.with_child(form_component)
.with_child(back_link(back_href))
.render()
.await
.into_response())

View file

@ -11,7 +11,7 @@ use crate::account::{Account, UserStatus};
use crate::component::admin::{
AdminPasswordForm, USER_ADMIN_FORM_ID, UserForm, UserFormMode, UserTable,
};
use crate::component::user_details;
use crate::component::{cancel_link, user_details};
use crate::config::SETTINGS;
use crate::entity::{role, user};
use crate::error::AuthError;
@ -53,7 +53,7 @@ pub(crate) async fn list_get(
let result = match user_admin::list_users(&params).await {
Ok(result) => result,
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
Err(_) => return Err(ErrorPage::InternalError(request)),
};
let mut table = UserTable::new()
@ -72,7 +72,7 @@ pub(crate) async fn list_get(
let title = Lc::t("title-admin-users", &LOCALES_USER);
Ok(Page::admin(request)
.with_title(title)
.with_child(search_bar(query.q))
.with_child(search_filter(query.q))
.with_child(table)
.render()
.await
@ -80,27 +80,21 @@ pub(crate) async fn list_get(
}
}
// **< search_bar >*********************************************************************************
// **< search_filter >******************************************************************************
fn search_bar(current_query: Option<String>) -> Html {
let value = current_query.unwrap_or_default();
Html::with(move |cx| {
html! {
div class="user-admin-search" {
input
type="search"
id="user-admin-search-input"
name="q"
value=(value.as_str())
placeholder=[Lc::t("field-search-users", &LOCALES_USER).lookup(cx)]
hx-get=(cx.route(ADMIN_USERS_PATH.as_str()).to_string())
hx-trigger="keyup changed delay:400ms, search"
hx-target="#user-table-wrapper"
hx-swap=(hx::swap::OUTER_HTML_SCROLL_TOP)
hx-push-url="true";
}
}
})
fn search_filter(current_query: Option<String>) -> ListFilter {
hx_filter::boost(
ListFilter::new()
.with_filter_action(ADMIN_USERS_PATH.as_str())
.with_field(
form::input::Field::search()
.with_id("user-admin-search")
.with_name("q")
.with_value(current_query.unwrap_or_default())
.with_placeholder(Lc::t("field-search-users", &LOCALES_USER)),
),
"#user-table-wrapper",
)
}
// **< available_roles >****************************************************************************
@ -131,14 +125,14 @@ fn parse_role_ids(role_ids: &[String]) -> Vec<i32> {
// Carga el usuario y comprueba que quien hace la petición puede gestionarlo. La cuenta de un
// administrador sólo la gestiona otro administrador: si no, quien administra usuarios podría
// apoderarse de ella (p. ej. restableciendo su contraseña) y obtener acceso irrestricto, que sólo
// apoderarse de ella (p. ej. restableciendo su contraseña) y obtener acceso total, que sólo
// un administrador puede conceder.
async fn require_manageable(request: &HttpRequest, id: i32) -> Result<user::Model, ErrorPage> {
let Ok(user) = user_admin::find_user(id).await else {
return Err(ErrorPage::NotFound(Some(request.clone())));
return Err(ErrorPage::NotFound(request.clone()));
};
if user.is_admin && !request.extension::<Account>().is_some_and(|a| a.is_admin()) {
return Err(ErrorPage::AccessDenied(Some(request.clone())));
return Err(ErrorPage::AccessDenied(request.clone()));
}
Ok(user)
}
@ -146,19 +140,15 @@ async fn require_manageable(request: &HttpRequest, id: i32) -> Result<user::Mode
// **< new_get / new_post >*************************************************************************
/// GET /admin/user/users/new - Formulario de alta de usuario.
pub(crate) async fn new_get(
request: HttpRequest,
web::Query(waypoint): web::Query<Waypoint>,
) -> Result<Response, ErrorPage> {
pub(crate) async fn new_get(request: HttpRequest) -> Result<Response, ErrorPage> {
let roles = match available_roles(&[]).await {
Ok(roles) => roles,
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
Err(_) => return Err(ErrorPage::InternalError(request)),
};
// El campo "administrador" sólo se ofrece si quien da de alta ya es administrador: no es un
// permiso del catálogo (igual que conceder/revocar en la edición, ver `set_user_admin`).
let allow_admin_field = request.extension::<Account>().is_some_and(|a| a.is_admin());
let page = Page::admin(request);
let back_href = waypoint.or(page.route(ADMIN_USERS_PATH.as_str()));
let title = Lc::t("title-admin-user-new", &LOCALES_USER);
Ok(page
.with_title(title)
@ -166,10 +156,8 @@ pub(crate) async fn new_get(
UserForm::new()
.with_mode(UserFormMode::New)
.with_roles(roles)
.with_allow_admin_field(allow_admin_field)
.with_waypoint(waypoint),
.with_allow_admin_field(allow_admin_field),
)
.with_child(back_link(back_href))
.render()
.await
.into_response())
@ -201,11 +189,10 @@ pub(crate) struct NewUserFormData {
/// deserializa claves repetidas como `role_ids=2&role_ids=3` en un `Vec<T>`).
pub(crate) async fn new_post(
request: HttpRequest,
web::Query(waypoint): web::Query<Waypoint>,
raw: web::RawForm,
) -> Result<Response, ErrorPage> {
let Ok(form) = serde_qs::from_bytes::<NewUserFormData>(&raw.0) else {
return Err(ErrorPage::BadRequest(Some(request)));
return Err(ErrorPage::BadRequest(request));
};
let allow_admin_field = request.extension::<Account>().is_some_and(|a| a.is_admin());
// Nunca fiarse sólo de que el campo esté presente en el formulario: sólo se concede si quien
@ -230,13 +217,12 @@ pub(crate) async fn new_post(
match result {
Ok(_) => {
let cx = Context::admin(request);
let target = waypoint.or(cx.route(ADMIN_USERS_PATH.as_str()));
let target = cx.route(ADMIN_USERS_PATH.as_str());
Ok(Redirect::see_other(target).into_response())
}
Err(err) => {
let roles = available_roles(&role_ids).await.unwrap_or_default();
let page = Page::admin(request);
let back_href = waypoint.or(page.route(ADMIN_USERS_PATH.as_str()));
let form_component = UserForm::new()
.with_mode(UserFormMode::New)
.with_username(form.username)
@ -248,13 +234,11 @@ pub(crate) async fn new_post(
.with_roles(roles)
.with_allow_admin_field(allow_admin_field)
.with_is_admin(is_admin)
.with_error(map_auth_error(&err))
.with_waypoint(waypoint);
.with_error(map_auth_error(&err));
let title = Lc::t("title-admin-user-new", &LOCALES_USER);
Ok(page
.with_title(title)
.with_child(form_component)
.with_child(back_link(back_href))
.render()
.await
.into_response())
@ -265,23 +249,18 @@ pub(crate) async fn new_post(
// **< edit_get / edit_post >***********************************************************************
// Pantalla de edición con el formulario relleno con los datos guardados del usuario.
async fn render_user_edit(
request: HttpRequest,
id: i32,
error: Option<Lc>,
waypoint: Waypoint,
) -> Response {
async fn render_user_edit(request: HttpRequest, id: i32, error: Option<Lc>) -> Response {
let user = match user_admin::find_user(id).await {
Ok(user) => user,
Err(_) => return ErrorPage::NotFound(Some(request)).into_response(),
Err(_) => return ErrorPage::NotFound(request).into_response(),
};
let current = match user_admin::user_role_ids(id).await {
Ok(ids) => ids,
Err(_) => return ErrorPage::InternalError(Some(request)).into_response(),
Err(_) => return ErrorPage::InternalError(request).into_response(),
};
let roles = match available_roles(&current).await {
Ok(roles) => roles,
Err(_) => return ErrorPage::InternalError(Some(request)).into_response(),
Err(_) => return ErrorPage::InternalError(request).into_response(),
};
let status = UserStatus::from_i16(user.status);
let is_admin = user.is_admin;
@ -295,7 +274,7 @@ async fn render_user_edit(
.with_theme(user.theme.unwrap_or_default())
.with_roles(roles)
.with_error(error);
render_edit_page(request, id, status, is_admin, form, waypoint).await
render_edit_page(request, id, status, is_admin, form).await
}
// Pantalla de edición del usuario `id` con `form` ya relleno, sea con los datos guardados o con los
@ -307,7 +286,6 @@ async fn render_edit_page(
status: UserStatus,
is_admin: bool,
form: UserForm,
waypoint: Waypoint,
) -> Response {
// El botón de conceder/revocar sólo se muestra si quien lo ve ya es administrador y no está
// viendo su propio perfil: no es un permiso del catálogo, y nadie puede automodificarse el flag
@ -318,7 +296,6 @@ async fn render_edit_page(
// Bloquear y activar exige además `user:block_accounts` (ver `status_post`).
let can_change_status = has_permission(&request, &UserPermission::BlockAccounts);
let mut page = Page::admin(request);
let back_href = waypoint.or(page.route(ADMIN_USERS_PATH.as_str()));
let title = Lc::t("title-admin-user-edit", &LOCALES_USER);
let actions = edit_actions(
id,
@ -326,43 +303,32 @@ async fn render_edit_page(
is_admin,
can_toggle_admin,
can_change_status,
&waypoint,
page.context_mut(),
);
page.with_title(title)
.with_child(
form.with_mode(UserFormMode::Edit)
.with_user_id(Some(id))
.with_waypoint(waypoint.clone()),
)
.with_child(form.with_mode(UserFormMode::Edit).with_user_id(Some(id)))
.with_child(actions)
.with_child(back_link(back_href))
.render()
.await
.into_response()
}
// Enlace a la pantalla de restablecer contraseña y botones de bloqueo/activación (sólo si
// `can_change_status`) y de concesión/revocación de acceso irrestricto (sólo si
// `can_toggle_admin`). El listado
// de origen (`waypoint`) se arrastra a todas ellas para que, al volver aquí, esta misma pantalla
// siga sabiendo devolver al listado en el estado en que se dejó.
// Botonera de la edición: "Guardar", "Cancelar", el enlace a la pantalla de restablecer contraseña
// y los botones de bloqueo/activación (sólo si `can_change_status`) y de concesión/revocación de
// acceso total (sólo si `can_toggle_admin`).
//
// "Guardar" (envía el `<form>` de `UserForm` vía el atributo `form`, ver `USER_ADMIN_FORM_ID`) y
// "Restablecer contraseña" son botones sueltos; bloqueo/activación y concesión/revocación de admin
// (este último sólo si `can_toggle_admin`) van cada uno en su propio `Form`, con un campo `Hidden`
// para el nuevo valor, para conservar el envío nativo sin JavaScript, mejorado con
// `hx-post`/`hx-confirm`. Todos son hijos directos del mismo `Container` con Flex, que los alinea
// en fila con espaciado uniforme sin que ninguno tenga que ser forzosamente un `Button` suelto (ver
// PAGETOP.md, "Preferir componentes a `html!` en bruto").
// "Guardar" (envía el `<form>` de `UserForm` vía el atributo `form`, ver `USER_ADMIN_FORM_ID`),
// "Cancelar" y "Restablecer contraseña" son botones sueltos; bloqueo/activación y
// concesión/revocación de admin van cada uno en su propio `Form`, con un campo `Hidden` para el
// nuevo valor, para conservar el envío nativo sin JavaScript, mejorado con `hx-post`/`hx-confirm`.
// Todos son hijos directos del mismo `Flex`, que los alinea en fila con espaciado uniforme.
fn edit_actions(
user_id: i32,
status: UserStatus,
target_is_admin: bool,
can_toggle_admin: bool,
can_change_status: bool,
waypoint: &Waypoint,
cx: &mut Context,
) -> Flex {
// Una cuenta pendiente de verificar su email también se puede activar directamente, p. ej. si
@ -377,9 +343,9 @@ fn edit_actions(
("true", "btn-grant-admin", "confirm-grant-admin")
};
let password_href = waypoint.append_to(cx.route(user_path(user_id, "password")));
let status_action = waypoint.append_to(cx.route(user_path(user_id, "status")));
let admin_action = waypoint.append_to(cx.route(user_path(user_id, "admin")));
let password_href = cx.route(user_path(user_id, "password"));
let status_action = cx.route(user_path(user_id, "status"));
let admin_action = cx.route(user_path(user_id, "admin"));
let mut status_form = Form::new()
.with_action(status_action.clone())
@ -403,6 +369,7 @@ fn edit_actions(
.with_style(button::Style::Solid(Intent::Primary))
.with_prop(PropsOp::set("form", USER_ADMIN_FORM_ID)),
)
.with_child(cancel_link(cx.route(ADMIN_USERS_PATH.as_str())))
.with_child(
Button::anchor(Lc::t("btn-reset-password", &LOCALES_USER), password_href)
.with_style(button::Style::Solid(Intent::Neutral)),
@ -433,10 +400,9 @@ fn edit_actions(
pub(crate) async fn edit_get(
request: HttpRequest,
web::Path(id): web::Path<i32>,
web::Query(waypoint): web::Query<Waypoint>,
) -> Result<Response, ErrorPage> {
require_manageable(&request, id).await?;
Ok(render_user_edit(request, id, None, waypoint).await)
Ok(render_user_edit(request, id, None).await)
}
#[derive(Deserialize)]
@ -463,12 +429,11 @@ pub(crate) struct EditUserFormData {
pub(crate) async fn edit_post(
request: HttpRequest,
web::Path(id): web::Path<i32>,
web::Query(waypoint): web::Query<Waypoint>,
raw: web::RawForm,
) -> Result<Response, ErrorPage> {
let user = require_manageable(&request, id).await?;
let Ok(form) = serde_qs::from_bytes::<EditUserFormData>(&raw.0) else {
return Err(ErrorPage::BadRequest(Some(request)));
return Err(ErrorPage::BadRequest(request));
};
let role_ids = parse_role_ids(&form.role_ids);
@ -492,7 +457,7 @@ pub(crate) async fn edit_post(
match result {
Ok(()) => {
let cx = Context::admin(request);
let target = waypoint.or(cx.route(ADMIN_USERS_PATH.as_str()));
let target = cx.route(ADMIN_USERS_PATH.as_str());
Ok(Redirect::see_other(target).into_response())
}
Err(err) => {
@ -508,7 +473,7 @@ pub(crate) async fn edit_post(
.with_theme(form.theme)
.with_roles(roles)
.with_error(map_auth_error(&err));
Ok(render_edit_page(request, id, status, user.is_admin, form, waypoint).await)
Ok(render_edit_page(request, id, status, user.is_admin, form).await)
}
}
}
@ -520,19 +485,18 @@ pub(crate) async fn edit_post(
pub(crate) async fn view_get(
request: HttpRequest,
web::Path(id): web::Path<i32>,
web::Query(waypoint): web::Query<Waypoint>,
) -> Result<Response, ErrorPage> {
let user = match user_admin::find_user(id).await {
Ok(user) => user,
Err(_) => return Err(ErrorPage::NotFound(Some(request))),
Err(_) => return Err(ErrorPage::NotFound(request)),
};
let roles = match user_admin::user_roles(id).await {
Ok(roles) => roles,
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
Err(_) => return Err(ErrorPage::InternalError(request)),
};
let mut page = Page::admin(request);
let back_href = waypoint.or(page.route(ADMIN_USERS_PATH.as_str()));
let back_href = page.route(ADMIN_USERS_PATH.as_str());
let details_block = user_details(&user, page.context_mut()).await;
let roles_block = user_view_roles(&roles, user.is_admin, page.context_mut()).await;
@ -619,13 +583,12 @@ pub(crate) struct StatusFormData {
pub(crate) async fn status_post(
request: HttpRequest,
web::Path(id): web::Path<i32>,
web::Query(waypoint): web::Query<Waypoint>,
web::Form(form): web::Form<StatusFormData>,
) -> Result<Response, ErrorPage> {
require_permission(&request, &UserPermission::BlockAccounts)?;
require_manageable(&request, id).await?;
let Some(account) = request.extension::<Account>().cloned() else {
return Err(ErrorPage::AccessDenied(Some(request)));
return Err(ErrorPage::AccessDenied(request));
};
let new_status = match form.status.as_str() {
@ -640,14 +603,14 @@ pub(crate) async fn status_post(
match user_admin::set_user_status(id, new_status, account.id()).await {
Ok(()) => {
let cx = Context::admin(request);
let edit_href = waypoint.append_to(cx.route(user_path(id, "edit")));
let edit_href = cx.route(user_path(id, "edit"));
if is_htmx {
Ok(HtmxResponse::empty().redirect(edit_href).into_response())
} else {
Ok(Redirect::see_other(edit_href).into_response())
}
}
Err(err) => Ok(render_user_edit(request, id, Some(map_auth_error(&err)), waypoint).await),
Err(err) => Ok(render_user_edit(request, id, Some(map_auth_error(&err))).await),
}
}
@ -658,7 +621,7 @@ pub(crate) struct AdminFormData {
is_admin: String,
}
/// POST /admin/user/users/{id}/admin - Concede o revoca el acceso irrestricto (`is_admin`).
/// POST /admin/user/users/{id}/admin - Concede o revoca el acceso total (`is_admin`).
///
/// No pasa por `require_permission`: conceder o revocar este flag no es un permiso del catálogo,
/// se comprueba directamente contra `account.is_admin()` para que sólo un administrador pueda
@ -666,14 +629,13 @@ pub(crate) struct AdminFormData {
pub(crate) async fn admin_post(
request: HttpRequest,
web::Path(id): web::Path<i32>,
web::Query(waypoint): web::Query<Waypoint>,
web::Form(form): web::Form<AdminFormData>,
) -> Result<Response, ErrorPage> {
let Some(account) = request.extension::<Account>().cloned() else {
return Err(ErrorPage::AccessDenied(Some(request)));
return Err(ErrorPage::AccessDenied(request));
};
if !account.is_admin() {
return Err(ErrorPage::AccessDenied(Some(request)));
return Err(ErrorPage::AccessDenied(request));
}
let new_is_admin = form.is_admin == "true";
@ -687,14 +649,14 @@ pub(crate) async fn admin_post(
match user_admin::set_user_admin(id, new_is_admin, account.id()).await {
Ok(()) => {
let cx = Context::admin(request);
let edit_href = waypoint.append_to(cx.route(user_path(id, "edit")));
let edit_href = cx.route(user_path(id, "edit"));
if is_htmx {
Ok(HtmxResponse::empty().redirect(edit_href).into_response())
} else {
Ok(Redirect::see_other(edit_href).into_response())
}
}
Err(err) => Ok(render_user_edit(request, id, Some(map_auth_error(&err)), waypoint).await),
Err(err) => Ok(render_user_edit(request, id, Some(map_auth_error(&err))).await),
}
}
@ -705,21 +667,14 @@ pub(crate) async fn admin_post(
pub(crate) async fn password_get(
request: HttpRequest,
web::Path(id): web::Path<i32>,
web::Query(waypoint): web::Query<Waypoint>,
) -> Result<Response, ErrorPage> {
let user = require_manageable(&request, id).await?;
let page = Page::admin(request);
let edit_href = waypoint.append_to(page.route(user_path(id, "edit")));
let title = Lc::t("title-admin-user-password", &LOCALES_USER);
Ok(page
.with_title(title)
.with_child(user_summary(&user))
.with_child(
AdminPasswordForm::new()
.with_user_id(id)
.with_waypoint(waypoint),
)
.with_child(back_link(edit_href))
.with_child(AdminPasswordForm::new().with_user_id(id))
.render()
.await
.into_response())
@ -736,7 +691,6 @@ pub(crate) struct AdminPasswordFormData {
pub(crate) async fn password_post(
request: HttpRequest,
web::Path(id): web::Path<i32>,
web::Query(waypoint): web::Query<Waypoint>,
web::Form(form): web::Form<AdminPasswordFormData>,
) -> Result<Response, ErrorPage> {
let user = require_manageable(&request, id).await?;
@ -750,12 +704,11 @@ pub(crate) async fn password_post(
Ok(user) => {
send_notice(&request, Notice::PasswordChangedByAdmin, &user);
let cx = Context::admin(request);
let edit_href = waypoint.append_to(cx.route(user_path(id, "edit")));
let edit_href = cx.route(user_path(id, "edit"));
Ok(Redirect::see_other(edit_href).into_response())
}
Err(err) => {
let page = Page::admin(request);
let edit_href = waypoint.append_to(page.route(user_path(id, "edit")));
let title = Lc::t("title-admin-user-password", &LOCALES_USER);
Ok(page
.with_title(title)
@ -763,10 +716,8 @@ pub(crate) async fn password_post(
.with_child(
AdminPasswordForm::new()
.with_user_id(id)
.with_error(map_auth_error(&err))
.with_waypoint(waypoint),
.with_error(map_auth_error(&err)),
)
.with_child(back_link(edit_href))
.render()
.await
.into_response())

View file

@ -158,7 +158,7 @@ pub async fn logout_post(request: HttpRequest) -> Response {
/// GET /user/register - Formulario de registro de cuenta.
pub async fn register_get(request: HttpRequest) -> Result<Markup, ErrorPage> {
if !SETTINGS.allow_registration {
return Err(ErrorPage::NotFound(Some(request)));
return Err(ErrorPage::NotFound(request));
}
Page::new(request)
.with_title(Lc::t("title-register", &LOCALES_USER))
@ -175,7 +175,7 @@ pub async fn register_post(
web::Form(form): web::Form<RegisterFormData>,
) -> Response {
if !SETTINGS.allow_registration {
return ErrorPage::NotFound(Some(request)).into_response();
return ErrorPage::NotFound(request).into_response();
}
let cx = Context::new(request.clone());
let result = if throttle::allow(&request) {
@ -289,7 +289,7 @@ pub async fn password_reset_confirm_get(
.await
.unwrap_or(false)
{
return Err(ErrorPage::NotFound(Some(request)));
return Err(ErrorPage::NotFound(request));
}
let page = Page::new(request)
.with_title(Lc::t("title-new-password", &LOCALES_USER))
@ -378,7 +378,7 @@ pub async fn verify_email_get(
.await
.unwrap_or(false)
{
return Err(ErrorPage::NotFound(Some(request)));
return Err(ErrorPage::NotFound(request));
}
Ok(no_referrer(
confirm_page(
@ -430,7 +430,7 @@ pub async fn verify_email_post(
MessageLevel::Info,
Lc::t("msg-email-verified", &LOCALES_USER),
),
Err(_) => ErrorPage::NotFound(Some(request)).into_response(),
Err(_) => ErrorPage::NotFound(request).into_response(),
}
}

View file

@ -159,6 +159,25 @@ Los inicios de sesión fallidos se limitan también por dirección IP (`max_ip_f
frenar a quien prueba unas pocas contraseñas habituales en muchas cuentas sin llegar a bloquear
ninguna. Detrás de un *proxy* inverso, los límites por IP requieren configurar
`server.client_ip_header`.
## Cookies
Al iniciar sesión se crea la *cookie* de sesión (`cookie_name` de `[user.session]`, `pagetop` por
defecto). Es propia, `HttpOnly` y con un identificador aleatorio que la aplicación guarda en la base
de datos. Se borra al cerrar sesión.
Sin marcar "Recuérdame", el navegador la borra al cerrarse, y la sesión deja de valer tras
`idle_secs` sin uso. Es una *cookie* de autenticación para un servicio que el propio usuario pide,
así que en España y en la Unión Europea no requiere su aceptación: las normas y guías en que se basa
están en [*Cookies*](pagetop::web#cookies), en el módulo `web` de PageTop.
Con "Recuérdame", la sesión se conserva aunque se cierre el navegador, hasta `remember_idle_secs`
sin uso (14 días por defecto). El dictamen 04/2012 del Grupo de Trabajo del Artículo 29 (WP194) no
exime estas *cookies* de inicio de sesión persistente, pero considera suficiente que sea el usuario
quien la pida marcando expresamente la casilla, siempre que sepa que se usa una *cookie*. Por eso el
formulario de acceso lo indica en el texto de ayuda de la casilla, que además desaconseja marcarla
en un equipo compartido. La aplicación sólo tiene que declararla también en su política de
*cookies*.
*/
use pagetop::prelude::*;
@ -450,7 +469,10 @@ impl Extension for User {
&format!("{}/{{uid}}/{{token}}", VERIFY_PATH),
web::get(handlers::auth::verify_email_get).post(handlers::auth::verify_email_post),
)
.admin_route(ADMIN_USERS, web::get(handlers::admin::users::list_get))
.admin_route(
ADMIN_USERS,
web::remember_query(web::get(handlers::admin::users::list_get)),
)
.admin_route(
&format!("{ADMIN_USERS}/new"),
web::get(handlers::admin::users::new_get).post(handlers::admin::users::new_post),
@ -476,7 +498,10 @@ impl Extension for User {
web::get(handlers::admin::users::password_get)
.post(handlers::admin::users::password_post),
)
.admin_route(ADMIN_ROLES, web::get(handlers::admin::roles::list_get))
.admin_route(
ADMIN_ROLES,
web::remember_query(web::get(handlers::admin::roles::list_get)),
)
.admin_route(
&format!("{ADMIN_ROLES}/new"),
web::get(handlers::admin::roles::new_get).post(handlers::admin::roles::new_post),

View file

@ -226,6 +226,8 @@ help-password-min-length = At least { $n } characters.
help-email-readonly = To change it, use "Change email" in your profile.
help-remember-me = Keeps you signed in using a cookie. Do not check on a shared device.
help-machine-name-immutable =
Lowercase letters, digits and underscores only. Cannot be changed after creation.
@ -247,7 +249,7 @@ btn-block = Block
btn-activate = Activate
btn-grant-admin = Grant administrator
btn-revoke-admin = Revoke administrator
link-back-to-list = Back to list
link-back = Back
# **< Admin: confirmations and badges >**

View file

@ -206,7 +206,7 @@ field-label = Etiqueta
field-description = Descripción
field-weight = Peso
field-roles = Roles
field-is-admin = Administrador (acceso irrestricto)
field-is-admin = Administrador (acceso total)
field-search-users = Buscar por usuario, email o nombre...
help-username-strict =
@ -227,6 +227,8 @@ help-password-min-length = Al menos { $n } caracteres.
help-email-readonly = Para cambiarla, usa «Cambiar email» en tu perfil.
help-remember-me = Mantiene la sesión abierta usando una cookie. No marcar en un equipo compartido.
help-machine-name-immutable =
Sólo minúsculas, dígitos y guiones bajos. No se puede cambiar tras crearlo.
@ -248,14 +250,14 @@ btn-block = Bloquear
btn-activate = Activar
btn-grant-admin = Conceder administrador
btn-revoke-admin = Revocar administrador
link-back-to-list = Volver al listado
link-back = Volver
# **< Administración: confirmaciones y distintivos >**
confirm-delete-role = ¿Eliminar este rol? Esta acción no se puede deshacer.
confirm-change-status = ¿Cambiar el estado de esta cuenta?
confirm-grant-admin = ¿Conceder acceso irrestricto a esta cuenta?
confirm-revoke-admin = ¿Revocar el acceso irrestricto de esta cuenta?
confirm-grant-admin = ¿Conceder acceso total a esta cuenta?
confirm-revoke-admin = ¿Revocar el acceso total de esta cuenta?
badge-system-role = Sistema
badge-admin = Administrador
badge-no-permissions = Sin permisos
@ -273,6 +275,6 @@ error-role-locked = Este rol es de sistema y no se puede modifi
error-role-in-use = Este rol tiene usuarios asignados y no se puede eliminar.
error-last-administrator = No se puede quitar al último administrador.
error-cannot-block-self = No puedes bloquear tu propia cuenta.
error-cannot-modify-own-admin-flag = No puedes conceder ni revocar tu propio acceso irrestricto.
error-cannot-modify-own-admin-flag = No puedes conceder ni revocar tu propio acceso total.
error-user-not-found = Usuario no encontrado.
error-unknown-permission = Clave de permiso desconocida.

View file

@ -12,6 +12,7 @@ use std::sync::Arc;
use pagetop::prelude::*;
use crate::account::{Account, PermissionSet};
use crate::config::SETTINGS;
use crate::session;
// Permisos del rol "anonymous", insertados en las peticiones sin sesión. Un tipo propio para que no
@ -47,17 +48,17 @@ pub(crate) async fn session_middleware(
let mut response = next.run(req).await;
// No se pisa una cookie que ya fije el handler (p. ej. la de expiración al cerrar sesión).
// No se pisa la cookie de sesión que ya fije el handler (p. ej. la de expiración al cerrar
// sesión). Las demás (mensajes, estado de un listado) conviven con la renovación: si la
// impidieran, la cookie caducaría en el navegador antes que la sesión.
if let Some(cookie) = renewed_cookie
&& !response
.headers()
.contains_key(web::http::header::SET_COOKIE)
&& !sets_cookie(response.headers(), &SETTINGS.session.cookie_name)
{
match web::http::HeaderValue::try_from(cookie) {
Ok(value) => {
response
.headers_mut()
.insert(web::http::header::SET_COOKIE, value);
.append(web::http::header::SET_COOKIE, value);
}
Err(_) => trace::warn!("session: invalid renewed cookie, header discarded"),
}
@ -65,6 +66,19 @@ pub(crate) async fn session_middleware(
response
}
// Si la respuesta ya fija (o borra) la cookie `name`.
fn sets_cookie(headers: &web::http::HeaderMap, name: &str) -> bool {
headers
.get_all(web::http::header::SET_COOKIE)
.iter()
.any(|value| {
value
.as_bytes()
.strip_prefix(name.as_bytes())
.is_some_and(|rest| rest.starts_with(b"="))
})
}
// **< check_rbac_permission >**********************************************************************
/// Handler de la acción [`CheckPermission`](pagetop::base::action::auth::CheckPermission) para el
@ -88,3 +102,33 @@ pub(crate) fn check_rbac_permission(
*granted = true;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn headers(cookies: &[&'static str]) -> web::http::HeaderMap {
let mut headers = web::http::HeaderMap::new();
for cookie in cookies {
headers.append(
web::http::header::SET_COOKIE,
web::http::HeaderValue::from_static(cookie),
);
}
headers
}
#[pagetop::test]
async fn only_the_session_cookie_itself_blocks_its_renewal() {
// Other cookies (flash messages, the state of a list) must not stop the renewal.
let others = headers(&[
"pagetop_flash=iSaved; Path=/",
"pagetop_list_0=q=a; Path=/x",
]);
assert!(!sets_cookie(&others, "session"));
let logout = headers(&["pagetop_flash=iBye; Path=/", "session=; Path=/; Max-Age=0"]);
assert!(sets_cookie(&logout, "session"));
// A cookie whose name only starts like the session one is a different cookie.
assert!(!sets_cookie(&headers(&["session_old=x"]), "session"));
}
}

View file

@ -35,7 +35,7 @@ impl MigrationTrait for Migration {
.col(integer(Users::FailedLoginCount).default(0))
.col(timestamp_null(Users::FailedLoginAt))
.col(timestamp_null(Users::LockedUntil))
// Acceso irrestricto al sistema, sin pasar por roles ni permisos.
// Acceso total al sistema, sin pasar por roles ni permisos.
.col(boolean(Users::IsAdmin).default(false))
.to_owned(),
)

View file

@ -16,7 +16,7 @@ pub enum UserPermission {
/// "Sobre mí" y fecha de alta.
ViewProfiles,
/// Editar los datos del perfil propio: email, nombre visible, "Sobre mí", idioma, zona horaria
/// y tema. Nunca los roles, el estado de la cuenta ni el acceso irrestricto.
/// y tema. Nunca los roles, el estado de la cuenta ni el acceso total.
EditOwnProfile,
/// Cambiar el nombre de usuario propio. Complementa a `EditOwnProfile`: el campo está en el
/// mismo formulario, así que sin aquel no tiene efecto.

View file

@ -473,7 +473,7 @@ pub(crate) async fn set_user_status(
// **< set_user_admin >*****************************************************************************
/// Concede o revoca el acceso irrestricto (`is_admin`). No es un permiso del catálogo: sólo un
/// Concede o revoca el acceso total (`is_admin`). No es un permiso del catálogo: sólo un
/// administrador puede concederlo o revocarlo (el handler comprueba `account.is_admin()`
/// directamente, sin pasar por `require_permission`).
///

View file

@ -2,7 +2,7 @@
//!
//! Incluye también los permisos del rol "anonymous", que se aplican a las peticiones sin sesión.
use std::sync::{Arc, PoisonError, RwLock};
use std::sync::{Arc, RwLock};
use std::time::Instant;
use pagetop::prelude::*;
@ -308,9 +308,7 @@ static ANONYMOUS_CACHE: RwLock<AnonymousCache> = RwLock::new(AnonymousCache {
/// a intentar en la siguiente petición.
pub(crate) async fn anonymous_permissions() -> Arc<PermissionSet> {
let generation = {
let cache = ANONYMOUS_CACHE
.read()
.unwrap_or_else(PoisonError::into_inner);
let cache = ANONYMOUS_CACHE.read().unwrap();
if let Some((loaded_at, permissions)) = &cache.loaded
&& loaded_at.elapsed() < ANONYMOUS_TTL
{
@ -334,9 +332,7 @@ pub(crate) async fn anonymous_permissions() -> Arc<PermissionSet> {
}
};
let mut cache = ANONYMOUS_CACHE
.write()
.unwrap_or_else(PoisonError::into_inner);
let mut cache = ANONYMOUS_CACHE.write().unwrap();
if cache.generation == generation {
cache.loaded = Some((Instant::now(), Arc::clone(&permissions)));
}
@ -346,9 +342,7 @@ pub(crate) async fn anonymous_permissions() -> Arc<PermissionSet> {
/// Descarta los permisos de "anonymous" guardados en memoria, para que la siguiente petición sin
/// sesión los vuelva a leer. Se llama al cambiar los permisos de ese rol.
pub(crate) fn invalidate_anonymous_permissions() {
let mut cache = ANONYMOUS_CACHE
.write()
.unwrap_or_else(PoisonError::into_inner);
let mut cache = ANONYMOUS_CACHE.write().unwrap();
cache.generation = cache.generation.wrapping_add(1);
cache.loaded = None;
}

View file

@ -7,7 +7,7 @@ use crate::config::SETTINGS;
use std::collections::{HashMap, VecDeque};
use std::net::{IpAddr, Ipv6Addr};
use std::sync::{LazyLock, Mutex, PoisonError};
use std::sync::{LazyLock, Mutex};
use std::time::{Duration as StdDuration, Instant};
// Momentos de las solicitudes de cada dirección dentro de la ventana, y última limpieza.
@ -41,7 +41,7 @@ pub(crate) fn allow(request: &HttpRequest) -> bool {
return true;
};
let allowed = allow_at(
&mut lock(&REQUESTS),
&mut REQUESTS.lock().unwrap(),
network(ip),
Instant::now(),
SETTINGS.max_ip_requests,
@ -63,7 +63,7 @@ pub(crate) fn allow_login(request: &HttpRequest) -> bool {
return true;
};
let allowed = allow_at(
&mut lock(&FAILED_LOGINS),
&mut FAILED_LOGINS.lock().unwrap(),
network(ip),
Instant::now(),
SETTINGS.max_ip_failed_logins,
@ -78,14 +78,10 @@ pub(crate) fn allow_login(request: &HttpRequest) -> bool {
/// Retira un intento anotado por [`allow_login()`] que no ha resultado fallido.
pub(crate) fn forget_login(request: &HttpRequest) {
if let Some(ip) = request.client_ip() {
forget_at(&mut lock(&FAILED_LOGINS), network(ip));
forget_at(&mut FAILED_LOGINS.lock().unwrap(), network(ip));
}
}
fn lock(log: &Log) -> std::sync::MutexGuard<'_, Requests> {
log.lock().unwrap_or_else(PoisonError::into_inner)
}
fn window(secs: i64) -> StdDuration {
StdDuration::from_secs(u64::try_from(secs).unwrap_or(0))
}

View file

@ -1,8 +1,8 @@
// End-to-end account flows against a real database. `config/common.toml` gives these tests an
// in-memory SQLite database with a single connection, the memory mail transport, email
// verification on sign-up, `max_failed_logins = 3`, `max_ip_requests = 3`,
// `max_ip_failed_logins = 3` and `max_email_changes = 2` (`max_password_resets` keeps its
// default, 3).
// `max_ip_failed_logins = 3`, `max_email_changes = 2` (`max_password_resets` keeps its default,
// 3) and `write_interval_secs = 0`, so "remember me" sessions renew their cookie on every request.
//
// Every scenario shares the same database, so they run one after another in a single test (and a
// single runtime, which also keeps the database connection alive). Each one uses its own accounts
@ -198,6 +198,8 @@ async fn account_flows() {
requests_are_limited_by_address(&client).await;
failed_logins_are_limited_by_address(&client).await;
anonymous_visitors_are_offered_to_sign_in(&client).await;
user_and_role_lists_remember_their_state(&client).await;
remembered_sessions_are_renewed_alongside_other_cookies(&client).await;
}
async fn registration_requires_confirming_the_address(client: &Client) {
@ -876,3 +878,61 @@ async fn anonymous_visitors_are_offered_to_sign_in(client: &Client) {
);
assert!(reply.header("set-cookie").starts_with("pagetop_flash="));
}
// The lists of users and roles remember their search, order and page: coming back to them without
// parameters, as the back links and the redirections after saving do, restores the state, and
// "Clear" forgets it.
async fn user_and_role_lists_remember_their_state(client: &Client) {
let admin = client.login("admin", "admin-password").await.unwrap();
for (list, state) in [
("/admin/user/users", "q=gil&sort=email&dir=desc&page=1"),
("/admin/user/roles", "sort=label&dir=desc&page=1"),
] {
let filtered = client.get(&format!("{list}?{state}"), Some(&admin)).await;
assert_eq!(filtered.status, Status::OK, "{list}");
let saved = filtered.header("set-cookie").split(';').next().unwrap();
assert!(saved.starts_with("pagetop_list_"), "{list}: {saved}");
let cookies = format!("{admin}; {saved}");
let back = client.get(list, Some(&cookies)).await;
assert_eq!(back.status, Status::SEE_OTHER, "{list}");
assert_eq!(back.location(), format!("{list}?{state}"));
let reset = client.get(&format!("{list}?reset"), Some(&cookies)).await;
assert_eq!(reset.location(), list);
}
}
// A "remember me" session renews its cookie even when the response sets another one, such as the
// state of a list: otherwise the cookie would expire in the browser before the session does.
async fn remembered_sessions_are_renewed_alongside_other_cookies(client: &Client) {
let fields = form(&[
("username", "admin"),
("password", "admin-password"),
("remember", "true"),
]);
let login = client.post("/user/login", &fields, None).await;
assert_eq!(login.status, Status::SEE_OTHER);
let session = login.session_cookie().expect("login sets the cookie");
let reply = client
.get("/admin/user/users?q=renewal", Some(&session))
.await;
assert_eq!(reply.status, Status::OK);
let cookies: Vec<&str> = reply
.headers
.get_all("set-cookie")
.iter()
.filter_map(|value| value.to_str().ok())
.collect();
assert!(
cookies.iter().any(|c| c.starts_with("pagetop_list_")),
"{cookies:?}"
);
assert!(
cookies
.iter()
.any(|c| c.starts_with(&format!("{session};")) && c.contains("Max-Age=")),
"{cookies:?}"
);
}

View file

@ -50,7 +50,7 @@ async fn dashboard(request: HttpRequest) -> Response {
async fn section_page(request: HttpRequest) -> Response {
let path = strip_admin_path(request.path()).unwrap_or_default();
let Some(section) = AdminRegistry::global().section_by_path(path) else {
return ErrorPage::NotFound(Some(request)).into_response();
return ErrorPage::NotFound(request).into_response();
};
let page = Page::admin(request.clone());

View file

@ -1,7 +1,5 @@
//! Prepara y ejecuta una aplicación creada con PageTop.
mod figfont;
use crate::admin;
use crate::core::extension;
use crate::core::extension::ExtensionRef;
@ -16,6 +14,7 @@ use crate::{PAGETOP_VERSION, global, trace};
use axum::extract::DefaultBodyLimit;
use axum::middleware::Next;
use figlet_rs::FIGlet;
use tower::{Layer, ServiceExt};
use tower_http::catch_panic::CatchPanicLayer;
use tracing_appender::non_blocking::WorkerGuard;
@ -146,7 +145,7 @@ impl Application {
use colored::Colorize;
use terminal_size::{Width, terminal_size};
if global::SETTINGS.app.startup_banner != global::StartupBanner::Off {
if global::SETTINGS.app.startup_banner {
// Nombre de la aplicación, ajustado al ancho del terminal si es necesario.
let mut app_ff = String::new();
let app_name = &global::SETTINGS.app.name;
@ -158,7 +157,10 @@ impl Application {
if app_name.chars().count() > maxlen {
app = format!("{app}...");
}
if let Some(ff) = figfont::FIGFONT.convert(&app) {
// Esta fuente incluye la `ñ` y las vocales con tilde.
if let Ok(font) = FIGlet::from_content(include_str!("../assets/figfonts/slant.flf"))
&& let Some(ff) = font.convert(&app)
{
app_ff = ff.to_string();
}
}

View file

@ -1,20 +0,0 @@
use crate::global;
use std::sync::LazyLock;
use figlet_rs::FIGlet;
pub static FIGFONT: LazyLock<FIGlet> = LazyLock::new(|| {
let slant = include_str!("slant.flf");
let small = include_str!("small.flf");
let speed = include_str!("speed.flf");
let starwars = include_str!("starwars.flf");
FIGlet::from_content(match global::SETTINGS.app.startup_banner {
global::StartupBanner::Off | global::StartupBanner::Slant => slant,
global::StartupBanner::Small => small,
global::StartupBanner::Speed => speed,
global::StartupBanner::Starwars => starwars,
})
.unwrap()
});

View file

@ -1,719 +0,0 @@
flf2a$ 7 6 22 15 4
starwars.flf by Ryan Youck (youck@cs.uregina.ca) Dec 25/1994
I am not responsible for use of this font
Based on Big.flf by Glenn Chappell
$ $@
$ $@
$ $@
$ $@
$ $@
$ $@
$ $@@
__ $@
| |$@
| |$@
| |$@
|__|$@
(__)$@
$@@
_ _ @
( | )@
V V @
$ @
$ @
$ @
@@
_ _ @
_| || |_$@
|_ __ _|@
_| || |_ @
|_ __ _|@
|_||_| $@
@@
__,--,_.@
/ |@
| (----`@
\ \ $@
.----) | $@
|_ __/ $@
'--' $@@
_ ___$ @
/ \ / /$ @
( o ) / / $ @
\_/ / / _$ @
/ / / \ @
/ / ( o )@
/__/ \_/ @@
@
___ @
( _ ) $@
/ _ \/\@
| (_> <@
\___/\/@
$@@
__ @
(_ )@
|/ @
$ @
$ @
$ @
@@
___@
/ /@
| |$@
| |$@
| |$@
| |$@
\__\@@
___ @
\ \ @
| |@
| |@
| |@
| |@
/__/ @@
_ @
/\| |/\ @
\ ` ' /$@
|_ _|@
/ , . \$@
\/|_|\/ @
@@
@
_ @
_| |_$@
|_ _|@
|_| $@
$ @
@@
@
@
$ @
$ @
__ @
(_ )@
|/ @@
@
@
______ @
|______|@
$ @
$ @
@@
@
@
@
$ @
__ @
(__)@
@@
___@
/ /@
/ / @
/ /$ @
/ /$ @
/__/$ @
@@
___ $@
/ _ \ $@
| | | |$@
| | | |$@
| |_| |$@
\___/ $@
$@@
__ $@
/_ |$@
| |$@
| |$@
| |$@
|_|$@
$@@
___ $@
|__ \ $@
$) |$@
/ / $@
/ /_ $@
|____|$@
$@@
____ $@
|___ \ $@
__) |$@
|__ < $@
___) |$@
|____/ $@
$@@
_ _ $@
| || | $@
| || |_ $@
|__ _|$@
| | $@
|_| $@
$@@
_____ $@
| ____|$@
| |__ $@
|___ \ $@
___) |$@
|____/ $@
$@@
__ $@
/ / $@
/ /_ $@
| '_ \ $@
| (_) |$@
\___/ $@
$@@
______ $@
|____ |$@
$/ / $@
/ / $@
/ / $@
/_/ $@
$@@
___ $@
/ _ \ $@
| (_) |$@
> _ < $@
| (_) |$@
\___/ $@
$@@
___ $@
/ _ \ $@
| (_) |$@
\__, |$@
/ / $@
/_/ $@
$@@
@
_ @
(_)@
$ @
_ @
(_)@
@@
@
_ @
(_)@
$ @
_ @
( )@
|/ @@
___@
/ /@
/ /$@
< <$ @
\ \$@
\__\@
@@
@
______ @
|______|@
______ @
|______|@
@
@@
___ @
\ \$ @
\ \ @
> >@
/ / @
/__/$ @
@@
______ $@
| \ $@
`----) |$@
/ / $@
|__| $@
__ $@
(__) $@@
____ @
/ __ \ @
/ / _` |@
| | (_| |@
\ \__,_|@
\____/ @
@@
___ $ @
/ \ $ @
/ ^ \$ @
/ /_\ \$ @
/ _____ \$ @
/__/ \__\$@
$@@
.______ $@
| _ \ $@
| |_) |$@
| _ < $@
| |_) |$@
|______/ $@
$@@
______$@
/ |@
| ,----'@
| | $@
| `----.@
\______|@
$@@
_______ $@
| \$@
| .--. |@
| | | |@
| '--' |@
|_______/$@
$@@
_______ @
| ____|@
| |__ $@
| __| $@
| |____ @
|_______|@
@@
_______ @
| ____|@
| |__ $@
| __| $@
| | $ @
|__| @
@@
_______ @
/ _____|@
| | __ $@
| | |_ |$@
| |__| |$@
\______|$@
$@@
__ __ $@
| | | |$@
| |__| |$@
| __ |$@
| | | |$@
|__| |__|$@
$@@
__ $@
| |$@
| |$@
| |$@
| |$@
|__|$@
$@@
__ $@
| |$@
| |$@
.--. | |$@
| `--' |$@
\______/ $@
$@@
__ ___$@
| |/ /$@
| ' / $@
| < $@
| . \ $@
|__|\__\$@
$@@
__ $@
| | $@
| | $@
| | $@
| `----.@
|_______|@
$@@
.___ ___.$@
| \/ |$@
| \ / |$@
| |\/| |$@
| | | |$@
|__| |__|$@
$@@
.__ __.$@
| \ | |$@
| \| |$@
| . ` |$@
| |\ |$@
|__| \__|$@
$@@
______ $@
/ __ \ $@
| | | |$@
| | | |$@
| `--' |$@
\______/ $@
$@@
.______ $@
| _ \ $@
| |_) |$@
| ___/ $@
| | $ @
| _| $ @
$ @@
______ $ @
/ __ \ $ @
| | | | $ @
| | | | $ @
| `--' '--. @
\_____\_____\@
$ @@
.______ $ @
| _ \ $ @
| |_) | $ @
| / $ @
| |\ \----.@
| _| `._____|@
$@@
_______.@
/ |@
| (----`@
\ \ $@
.----) | $@
|_______/ $@
$@@
.___________.@
| |@
`---| |----`@
| | $ @
| | $ @
|__| $ @
$ @@
__ __ $@
| | | |$@
| | | |$@
| | | |$@
| `--' |$@
\______/ $@
$@@
____ ____$@
\ \ / /$@
\ \/ /$ @
\ /$ @
\ /$ @
\__/$ @
$ @@
____ __ ____$@
\ \ / \ / /$@
\ \/ \/ /$ @
\ /$ @
\ /\ /$ @
\__/ \__/$ @
$ @@
___ ___$@
\ \ / /$@
\ V / $@
> < $@
/ . \ $@
/__/ \__\$@
$@@
____ ____$@
\ \ / /$@
\ \/ /$ @
\_ _/$ @
| |$ @
|__|$ @
$ @@
________ $@
| / $@
`---/ / $@
/ / $@
/ /----.@
/________|@
$@@
____ @
| |@
| |-`@
| | $@
| | $@
| |-.@
|____|@@
___ @
\ \ $ @
\ \$ @
\ \$ @
\ \$@
\__\@
@@
____ @
| |@
`-| |@
| |@
| |@
.-| |@
|____|@@
___ @
/ \ @
/--^--\@
$@
$@
$@
$@@
@
@
@
$ @
$ @
______ @
|______|@@
__ @
( _)@
\| @
$ @
$ @
$ @
@@
___ $ @
/ \ $ @
/ ^ \$ @
/ /_\ \$ @
/ _____ \$ @
/__/ \__\$@
$@@
.______ $@
| _ \ $@
| |_) |$@
| _ < $@
| |_) |$@
|______/ $@
$@@
______$@
/ |@
| ,----'@
| | $@
| `----.@
\______|@
$@@
_______ $@
| \$@
| .--. |@
| | | |@
| '--' |@
|_______/$@
$@@
_______ @
| ____|@
| |__ $@
| __| $@
| |____ @
|_______|@
@@
_______ @
| ____|@
| |__ $@
| __| $@
| | $ @
|__| @
@@
_______ @
/ _____|@
| | __ $@
| | |_ |$@
| |__| |$@
\______|$@
$@@
__ __ $@
| | | |$@
| |__| |$@
| __ |$@
| | | |$@
|__| |__|$@
$@@
__ $@
| |$@
| |$@
| |$@
| |$@
|__|$@
$@@
__ $@
| |$@
| |$@
.--. | |$@
| `--' |$@
\______/ $@
$@@
__ ___$@
| |/ /$@
| ' / $@
| < $@
| . \ $@
|__|\__\$@
$@@
__ $@
| | $@
| | $@
| | $@
| `----.@
|_______|@
$@@
.___ ___.$@
| \/ |$@
| \ / |$@
| |\/| |$@
| | | |$@
|__| |__|$@
$@@
.__ __.$@
| \ | |$@
| \| |$@
| . ` |$@
| |\ |$@
|__| \__|$@
$@@
______ $@
/ __ \ $@
| | | |$@
| | | |$@
| `--' |$@
\______/ $@
$@@
.______ $@
| _ \ $@
| |_) |$@
| ___/ $@
| | $ @
| _| $ @
$ @@
______ $ @
/ __ \ $ @
| | | | $ @
| | | | $ @
| `--' '--. @
\_____\_____\@
$ @@
.______ $ @
| _ \ $ @
| |_) | $ @
| / $ @
| |\ \----.@
| _| `._____|@
$@@
_______.@
/ |@
| (----`@
\ \ $@
.----) | $@
|_______/ $@
$@@
.___________.@
| |@
`---| |----`@
| | $ @
| | $ @
|__| $ @
$ @@
__ __ $@
| | | |$@
| | | |$@
| | | |$@
| `--' |$@
\______/ $@
$@@
____ ____$@
\ \ / /$@
\ \/ /$ @
\ /$ @
\ /$ @
\__/$ @
$ @@
____ __ ____$@
\ \ / \ / /$@
\ \/ \/ /$ @
\ /$ @
\ /\ /$ @
\__/ \__/$ @
$ @@
___ ___$@
\ \ / /$@
\ V / $@
> < $@
/ . \ $@
/__/ \__\$@
$@@
____ ____$@
\ \ / /$@
\ \/ /$ @
\_ _/$ @
| |$ @
|__|$ @
$ @@
________ $@
| / $@
`---/ / $@
/ / $@
/ /----.@
/________|@
$@@
___@
/ /@
| |$@
/ /$ @
\ \$ @
| |$@
\__\@@
__ $@
| |$@
| |$@
| |$@
| |$@
| |$@
|__|$@@
___ @
\ \$ @
| | @
\ \@
/ /@
| | @
/__/$ @@
__ _ @
/ \/ |@
|_/\__/ @
$ @
$ @
$ @
@@
_ _ @
(_)_(_) @
/ \ @
/ _ \ @
/ ___ \ @
/_/ \_\@
@@
_ _ @
(_)_(_)@
/ _ \ @
| | | |@
| |_| |@
\___/ @
@@
_ _ @
(_) (_)@
| | | |@
| | | |@
| |_| |@
\___/ @
@@
_ _ @
(_) (_)@
__ _ @
/ _` |@
| (_| |@
\__,_|@
@@
_ _ @
(_) (_)@
___ @
/ _ \ @
| (_) |@
\___/ @
@@
_ _ @
(_) (_)@
_ _ @
| | | |@
| |_| |@
\__,_|@
@@
___ @
/ _ \ @
| | ) |@
| |< < @
| | ) |@
| ||_/ @
|_| @@

View file

@ -319,7 +319,7 @@ pub fn require_permission(request: &HttpRequest, perm: PermissionRef) -> Result<
Ok(())
} else {
trace_denied(request);
Err(ErrorPage::AccessDenied(Some(request.clone())))
Err(ErrorPage::AccessDenied(request.clone()))
}
}
@ -383,7 +383,7 @@ pub fn deny_access(request: HttpRequest) -> Response {
{
return response;
}
ErrorPage::AccessDenied(Some(request)).into_response()
ErrorPage::AccessDenied(request).into_response()
}
// Los anónimos van en `debug` porque bots y sesiones caducadas los hacen frecuentes y poco

View file

@ -57,6 +57,12 @@ pub mod intro;
#[doc(inline)]
pub use intro::Intro;
mod list_filter;
pub use list_filter::ListFilter;
mod list_view;
pub use list_view::ListView;
mod messages;
pub use messages::Messages;

View file

@ -1,7 +1,6 @@
use crate::prelude::*;
/// Marco de una página del panel de administración, alrededor de la región
/// [`CoreRegions::Content`].
/// Marco de las páginas de administración, alrededor de [`CoreRegions::Content`].
///
/// Pinta, para la ruta de la petición actual, las migas de pan del panel, el título de la página
/// ([`Contextual::title()`]) con sus botones de acción ([`AdminAction`]), las pestañas de la

View file

@ -47,6 +47,8 @@ pub struct Checkbox {
name: AttrName,
/// Devuelve la etiqueta del control.
label: Lc,
/// Devuelve el texto de ayuda del control.
help_text: Lc,
/// Devuelve si el control debe estar marcado/activo por defecto.
checked: bool,
/// Devuelve si el control recibe el foco automáticamente al cargar la página.
@ -104,6 +106,7 @@ impl Component for Checkbox {
let checkbox_id = util::join!(&container_id, "-checkbox");
let label = form::parts::Label::check(self.label(), Some(&checkbox_id))
.with_required(*self.required());
let help = form::parts::Help::new(self.help_text(), Some(&checkbox_id));
let is_switch = *self.checkbox_kind() == form::CheckboxKind::Switch;
Ok(html! {
@ -118,8 +121,10 @@ impl Component for Checkbox {
checked[*self.checked()]
autofocus[*self.autofocus()]
required[*self.required()]
disabled[*self.disabled()];
disabled[*self.disabled()]
aria-describedby=[help.id()];
(label.render(cx))
(help.render(cx))
}
})
}
@ -175,6 +180,12 @@ impl Checkbox {
self
}
/// Establece el texto de ayuda del control (usa [`Lc::none()`] para quitarlo).
pub fn with_help_text(mut self, help_text: Lc) -> Self {
self.help_text = help_text;
self
}
/// Establece si el control debe aparecer marcado/activo por defecto.
pub fn with_checked(mut self, checked: bool) -> Self {
self.checked = checked;

View file

@ -0,0 +1,242 @@
use crate::prelude::*;
use crate::base::component::form;
/// Componente para crear los **filtros de un listado** (ver [`ListView`]).
///
/// Es un formulario GET con los campos en fila y el botón para aplicarlos que se coloca en la
/// página por encima del listado ([`ListView`]), no dentro: si se reemplazara con él, un campo de
/// texto perdería el foco en cada pulsación.
///
/// Envía los campos a la ruta de [`with_filter_action()`], que vuelve a pintar el listado ya
/// filtrado:
///
/// ```html
/// <form class="list-filter" action="...">
/// ... <!-- campos -->
/// <button type="submit">...</button> <!-- "Filtrar", si no se indica otro texto -->
/// <a href="..." target="_top">...</a> <!-- "Limpiar": el listado sin filtros -->
/// </form>
/// ```
///
/// Por defecto, los filtros **no** se envían solos: se aplican al pulsar el botón (o Enter en un
/// campo de texto), de modo que se pueden ajustar varios campos y pedir el listado una sola vez.
/// Con [`with_auto_submit(true)`] se aplican en cuanto cambia cualquier campo, sin botón.
///
/// Junto al botón aparece por defecto el enlace "Limpiar", que muestra el listado limpio: sin
/// filtros y con el orden y la página por defecto. Recarga la página entera para que también se
/// vacíen los campos del filtro. Se puede quitar con [`with_reset(false)`].
///
/// "Limpiar" apunta a la ruta del filtro con el parámetro `reset` (p. ej. `/items?reset`, más
/// `lang` si la ruta lo lleva). Si el listado se monta con [`web::remember_query()`], ese parámetro
/// hace además que olvide el estado que recordaba. Si no, el *handler* lo recibe como un parámetro
/// más y lo ignora, salvo que rechace los desconocidos (`#[serde(deny_unknown_fields)]`).
///
/// Con el botón, y si hay JavaScript, cada campo cuyo valor ya no coincide con el del filtro
/// aplicado se marca (clase `list-filter-changed` en su contenedor, `list-filter-pending` en el
/// formulario) hasta que se pulsa el botón, y un aviso oculto lo anuncia a los lectores de
/// pantalla. Así se sabe que el listado aún no corresponde a lo que muestra el filtro. El aspecto
/// de las marcas lo da cada tema.
///
/// Al enviar un formulario GET, el navegador descarta los parámetros que ya traiga la ruta de
/// destino, así que el idioma (`lang`) de la ruta se conserva en un campo oculto.
///
/// Como [`ListView`], no sabe nada de HTMX. Para aplicar los filtros sin recargar la página, se le
/// añaden los atributos necesarios con [`with_prop()`].
///
/// # Ejemplo
///
/// ```rust,no_run
/// use pagetop::prelude::*;
///
/// let filter = ListFilter::new()
/// .with_filter_action("/items")
/// .with_field(
/// form::input::Field::search()
/// .with_name("q")
/// .with_placeholder(Lc::n("Search...")),
/// );
/// ```
///
/// [`with_filter_action()`]: Self::with_filter_action
/// [`with_prop()`]: Self::with_prop
/// [`with_auto_submit(true)`]: Self::with_auto_submit
/// [`with_reset(false)`]: Self::with_reset
/// [`web::remember_query()`]: crate::web::remember_query
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct ListFilter {
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
props: Props,
/// Devuelve la ruta del formulario del filtro (su atributo `action`).
filter_action: Route,
/// Devuelve los campos de los filtros.
fields: Children,
/// Devuelve el texto del botón, o [`Lc::none()`] para el predeterminado ("Filtrar").
submit: Lc,
/// Devuelve si los filtros se aplican en cuanto cambia un campo, sin botón (por defecto, no).
#[getters(copy)]
auto_submit: bool,
/// Devuelve si se muestra el enlace "Limpiar" (por defecto, sí).
#[default(true)]
#[getters(copy)]
reset: bool,
}
#[async_trait]
impl Component for ListFilter {
fn new() -> Self {
Self::default()
}
fn id(&self) -> Option<String> {
self.props.get_id()
}
fn setup(&mut self, _cx: &mut Context) {
self.alter_prop(PropsOp::prepend_classes("list-filter"));
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let action = self.filter_action().try_resolve(cx);
let lang = action
.as_ref()
.and_then(|route| route.param("lang"))
.map(|lang| form::Hidden::field("lang", lang));
let label = if self.submit().is_none() {
Lc::l("list_filter_submit")
} else {
self.submit().clone()
};
let submit = Button::submit(label)
.with_style(button::Style::Solid(Intent::Neutral))
.render(cx)
.await;
// `target="_top"` navega igual que un enlace normal, pero las librerías que interceptan los
// enlaces para cargar sólo una parte de la página (como HTMX con `hx-boost`) dejan pasar
// los que tienen un `target` propio. Así se recarga la página entera y se vacían los
// campos, que no se volverían a pintar si sólo se actualizara el listado.
let reset = match (&action, self.reset()) {
(Some(route), true) => Some(
Button::anchor(Lc::l("list_filter_reset"), route.clone().with_flag("reset"))
.with_style(button::Style::Link)
.with_prop(PropsOp::set("target", "_top"))
.render(cx)
.await,
),
_ => None,
};
let auto_submit = self.auto_submit();
// Con el botón, un script del componente marca los campos cambiados y no aplicados todavía,
// y el aviso oculto los anuncia a los lectores de pantalla (`role="status"`).
let pending = (!auto_submit).then(|| Lc::l("list_filter_pending").lookup(cx));
if pending.is_some() {
cx.alter_assets(
JavaScript::defer("/pagetop/js/list-filter.min.js").with_version(PAGETOP_VERSION),
);
}
Ok(html! {
form
(self.props().unpack(cx))
action=[action]
onchange=[auto_submit.then_some("this.requestSubmit()")]
{
@if let Some(mut lang) = lang { (lang.render(cx).await) }
(self.fields().render(cx).await)
@if auto_submit { noscript { (submit) } } @else { (submit) }
@if let Some(reset) = reset { (reset) }
@if let Some(pending) = pending {
span
class="list-filter-status visually-hidden"
role="status"
data-pending=[pending]
{}
}
}
})
}
}
#[builder_impl]
impl ListFilter {
// **< ListFilter BUILDER >*********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id);
self
}
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
pub fn with_prop(mut self, op: impl Into<PropsOp>) -> Self {
self.props.alter_prop(op);
self
}
/// Establece la ruta del formulario del filtro: el atributo `action` del `<form>` que genera el
/// componente, es decir, la ruta a la que se envían los filtros.
///
/// Normalmente es la del propio listado. Su *handler* recibe los campos en la consulta
/// (`?q=...`) y vuelve a pintar el listado con ellos aplicados: la página entera en una
/// petición normal o, con filtrado en vivo, sólo el listado. No tiene que ver con las acciones
/// de PageTop ([`core::action`](crate::core::action)).
///
/// Acepta un literal, un `String` o una [`Route`]; como en cualquier enlace, se le añade el
/// idioma (`lang`) cuando corresponde, y el componente lo conserva en un campo oculto para que
/// el formulario no lo pierda al enviarse.
///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// // GET /items?q=... vuelve a pintar el listado con la búsqueda aplicada.
/// let filter = ListFilter::new()
/// .with_filter_action("/items")
/// .with_field(form::input::Field::search().with_name("q"));
/// ```
pub fn with_filter_action(mut self, action: impl Into<Route>) -> Self {
self.filter_action = action.into();
self
}
/// Añade un campo de filtro (texto, desplegable, casilla...).
pub fn with_field(mut self, op: impl Into<ChildOp>) -> Self {
self.fields.alter_child(op);
self
}
/// Aplica los filtros en cuanto cambia cualquier campo, sin pulsar el botón.
///
/// **Por defecto está desactivado** (`false`): los filtros se aplican sólo con el botón.
/// Con JavaScript activo, el filtro se muestra **sin botón**: un desplegable o una casilla se
/// aplican al cambiar, y un campo de texto al pulsar Enter o al salir de él (no con cada
/// tecla). Sin JavaScript, el botón sigue apareciendo y los filtros se aplican al pulsarlo.
///
/// Cada cambio pide de nuevo el listado. Conviene en filtros de uno o dos campos; con muchos,
/// el botón evita consultas intermedias que el usuario no quería.
///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// let filter = ListFilter::new()
/// .with_filter_action("/items")
/// .with_field(form::Checkbox::check().with_name("active").with_label(Lc::n("Active")))
/// .with_auto_submit(true);
/// ```
pub fn with_auto_submit(mut self, auto_submit: bool) -> Self {
self.auto_submit = auto_submit;
self
}
/// Muestra u oculta el enlace "Limpiar", que vuelve al listado sin filtros.
///
/// **Por defecto se muestra** (`true`), al contrario que
/// [`with_auto_submit()`](Self::with_auto_submit); con `false` se quita, por ejemplo en un
/// filtro de un único campo de texto, que ya se limpia vaciándolo.
pub fn with_reset(mut self, reset: bool) -> Self {
self.reset = reset;
self
}
/// Cambia el texto del botón; con [`Lc::none()`] vuelve al predeterminado ("Filtrar").
pub fn with_submit(mut self, label: Lc) -> Self {
self.submit = label;
self
}
}

View file

@ -0,0 +1,150 @@
use crate::prelude::*;
/// Componente para presentar un **listado**: botones de acción, mensajes, tabla y paginador.
///
/// Reúne las piezas de cualquier pantalla de listado y las pinta siempre en el mismo orden, sea
/// cual sea el orden en que se añadan:
///
/// ```html
/// <div class="list-view" id="..." data-summary="...">
/// <div class="list-view-actions">...</div> <!-- botones, si los hay -->
/// ... <!-- mensajes del contexto, si los hay -->
/// <table class="table">...</table>
/// <nav class="pager">...</nav> <!-- si hay más de una página -->
/// </div>
/// ```
///
/// Los mensajes son los que haya en el contexto al renderizar el listado (ver [`Messages`]), así
/// que un error o un aviso empujado antes, por ejemplo al rechazar un borrado, aparece junto a la
/// tabla también cuando se actualiza sólo el listado.
///
/// El listado lleva además un resumen del número de resultados (atributo `data-summary`, p. ej.
/// "23 resultados"): el total del paginador o, sin él, las filas de la tabla. Si JavaScript está
/// activo, cuando el listado se actualiza sin recargar la página, al filtrar, ordenar o cambiar de
/// página, el resumen se anuncia a los lectores de pantalla.
///
/// No sabe nada de HTMX. Para actualizar el listado sin recargar la página, se le da un
/// identificador con [`with_id()`](Self::with_id) y se apuntan a él los enlaces de la tabla y del
/// paginador. Los filtros y la búsqueda van **fuera** del listado, en la propia página: si se
/// reemplazaran con él, el campo de búsqueda perdería el foco en cada pulsación.
///
/// # Ejemplo
///
/// ```rust,no_run
/// use pagetop::prelude::*;
///
/// let list = ListView::new()
/// .with_id("item-list")
/// .with_action(
/// Button::anchor(Lc::n("New item"), "/items/new")
/// .with_style(button::Style::Solid(Intent::Primary)),
/// )
/// .with_table(
/// Table::new()
/// .with_column(Lc::n("Name"))
/// .with_empty(Lc::n("There are no items.")),
/// )
/// .with_pager(
/// Pager::new()
/// .with_base_path("/items")
/// .with_current_page(1)
/// .with_items_per_page(20)
/// .with_total_items(97),
/// );
/// ```
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct ListView {
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
props: Props,
/// Devuelve los botones de acción del listado.
actions: Children,
/// Devuelve la tabla del listado.
table: Embed<Table>,
/// Devuelve el paginador del listado.
pager: Embed<Pager>,
}
#[async_trait]
impl Component for ListView {
fn new() -> Self {
Self::default()
}
fn id(&self) -> Option<String> {
self.props.get_id()
}
fn setup(&mut self, _cx: &mut Context) {
self.alter_prop(PropsOp::prepend_classes("list-view"));
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
// Un script del componente anuncia el resumen cuando el listado se actualiza sin recargar
// la página (al cargarla no anuncia nada).
cx.alter_assets(
JavaScript::defer("/pagetop/js/list-view.min.js").with_version(PAGETOP_VERSION),
);
let count = match self.pager().get() {
Some(pager) => pager.total_items(),
None => self
.table()
.get()
.map_or(0, |table| table.rows().len() as u64),
};
let summary = Lc::l("list_view_summary")
.with_number("count", u32::try_from(count).unwrap_or(u32::MAX))
.lookup(cx);
let mut actions = Flex::new()
.with_prop(PropsOp::add_classes("list-view-actions"))
.with_wrap(flex::Behavior::Wrap)
.with_align(align::Items::Center)
.with_gap(align::Gap::Both(UnitValue::RelRem(0.5)));
for action in self.actions().iter() {
actions.alter_child(action.clone());
}
Ok(html! {
div (self.props().unpack(cx)) data-summary=[summary] {
(actions.render(cx).await)
(Messages::new().render(cx).await)
(self.table().render(cx).await)
(self.pager().render(cx).await)
}
})
}
}
#[builder_impl]
impl ListView {
// **< ListView BUILDER >***********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id);
self
}
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
pub fn with_prop(mut self, op: impl Into<PropsOp>) -> Self {
self.props.alter_prop(op);
self
}
/// Añade un botón de acción, o cualquier otro componente, sobre la tabla; habitualmente el de
/// crear un elemento nuevo.
pub fn with_action(mut self, op: impl Into<ChildOp>) -> Self {
self.actions.alter_child(op);
self
}
/// Establece la tabla del listado.
pub fn with_table(mut self, table: Table) -> Self {
self.table.alter_component(table);
self
}
/// Establece el paginador del listado.
pub fn with_pager(mut self, pager: Pager) -> Self {
self.pager.alter_component(pager);
self
}
}

View file

@ -11,10 +11,9 @@ use crate::response::read_flash_messages;
use crate::web::HttpRequest;
use crate::{CowStr, util};
use parking_lot::Mutex;
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Mutex;
mod assets_op;
pub use assets_op::AssetsOp;

View file

@ -481,7 +481,7 @@ pub trait Contextual {
segments
};
let count = {
let mut map = self.context().id_counters.lock();
let mut map = self.context().id_counters.lock().unwrap();
let n = map.entry(TypeId::of::<C>()).or_insert(0);
*n += 1;
*n

View file

@ -1,9 +1,7 @@
use crate::core::theme::ThemeRef;
use crate::{global, trace};
use parking_lot::RwLock;
use std::sync::LazyLock;
use std::sync::{LazyLock, RwLock};
// **< TEMAS >**************************************************************************************
@ -11,7 +9,7 @@ static THEMES: LazyLock<RwLock<Vec<ThemeRef>>> = LazyLock::new(|| RwLock::new(Ve
// Registra el tema si no lo estaba ya, para evitar duplicados. Devuelve `true` si lo ha añadido.
pub(crate) fn register_theme(theme: ThemeRef) -> bool {
let mut themes = THEMES.write();
let mut themes = THEMES.write().unwrap();
if themes.iter().any(|t| t.type_id() == theme.type_id()) {
return false;
}
@ -21,7 +19,7 @@ pub(crate) fn register_theme(theme: ThemeRef) -> bool {
/// Devuelve los temas habilitados en la aplicación, en el orden en que se registraron.
pub fn enabled_themes() -> Vec<ThemeRef> {
THEMES.read().clone()
THEMES.read().unwrap().clone()
}
/// Devuelve el tema identificado por su [`short_name()`](crate::core::AnyInfo::short_name).
@ -30,6 +28,7 @@ pub fn enabled_themes() -> Vec<ThemeRef> {
pub fn theme_by_short_name(short_name: &str) -> Option<ThemeRef> {
THEMES
.read()
.unwrap()
.iter()
.find(|t| t.short_name().eq_ignore_ascii_case(short_name))
.copied()

View file

@ -2,10 +2,8 @@ use crate::core::component::{Child, ChildOp, Children, Component};
use crate::core::theme::{CoreRegions, RegionRef, ThemeRef};
use crate::{AutoDefault, UniqueId, builder_impl};
use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::{Arc, LazyLock};
use std::sync::{Arc, LazyLock, RwLock};
// Lista de prototipos de componentes por nombre de región.
//
@ -90,7 +88,7 @@ impl ChildrenInRegions {
let region_name = region.name();
// 1. Prototipos globales comunes.
if let Some(global_protos) = COMMON_REGIONS.read().get(region_name) {
if let Some(global_protos) = COMMON_REGIONS.read().unwrap().get(region_name) {
result.add_many(
global_protos
.iter()
@ -102,7 +100,7 @@ impl ChildrenInRegions {
result.add_many(page_children);
}
// 3. Prototipos del tema activo.
if let Some(theme_region) = THEME_REGIONS.read().get(&theme.type_id())
if let Some(theme_region) = THEME_REGIONS.read().unwrap().get(&theme.type_id())
&& let Some(theme_protos) = theme_region.get(region_name)
{
result.add_many(
@ -190,6 +188,7 @@ impl InRegion {
InRegion::ForTheme(theme, region) => {
THEME_REGIONS
.write()
.unwrap()
.entry(theme.type_id())
.or_default()
.push((*region).name(), proto);
@ -200,6 +199,6 @@ impl InRegion {
#[inline]
fn add_to_common(region: RegionRef, proto: Arc<dyn Component>) {
COMMON_REGIONS.write().push(region.name(), proto);
COMMON_REGIONS.write().unwrap().push(region.name(), proto);
}
}

View file

@ -12,9 +12,6 @@ use std::sync::LazyLock;
mod lang_negotiation;
pub use lang_negotiation::LangNegotiation;
mod startup_banner;
pub use startup_banner::StartupBanner;
mod timezone_order;
pub use timezone_order::TimezoneOrder;
@ -178,10 +175,9 @@ pub struct AppSettings {
#[default = "/admin"]
#[serde(deserialize_with = "admin_path")]
pub admin_path: String,
/// Banner ASCII mostrado al inicio: *"Off"* (desactivado), *"Slant"*, *"Small"*, *"Speed"* o
/// *"Starwars"*.
#[default(StartupBanner::Slant)]
pub startup_banner: StartupBanner,
/// Muestra al iniciar un *banner* ASCII con el nombre de la aplicación (*true*) o no (*false*).
#[default = true]
pub startup_banner: bool,
/// Modo de ejecución, dado por la variable de entorno `PAGETOP_RUN_MODE`, o *"default"* si no
/// está definida o está vacía. Con la *feature* `testing` activa es siempre *"test"*.
pub run_mode: String,

View file

@ -1,45 +0,0 @@
use crate::AutoDefault;
use serde::de::Error;
use serde::{Deserialize, Deserializer};
/// Opciones para el *banner* ASCII mostrado al arrancar la aplicación.
///
/// Se obtiene de [`global::SETTINGS.app.startup_banner`] y controla si se muestra un *banner* en la
/// salida estándar al arrancar la aplicación.
///
/// [`global::SETTINGS.app.startup_banner`]: crate::global::AppSettings::startup_banner
#[derive(AutoDefault, Clone, Copy, Debug, Eq, PartialEq)]
pub enum StartupBanner {
/// No muestra ningún banner de inicio.
Off,
/// Banner en estilo "Slant". Es el comportamiento por defecto.
#[default]
Slant,
/// Banner en estilo "Small".
Small,
/// Banner en estilo "Speed".
Speed,
/// Banner en estilo "Starwars".
Starwars,
}
impl<'de> Deserialize<'de> for StartupBanner {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let raw = String::deserialize(deserializer)?;
match raw.trim().to_ascii_lowercase().as_str() {
"off" => Ok(Self::Off),
"slant" => Ok(Self::Slant),
"small" => Ok(Self::Small),
"speed" => Ok(Self::Speed),
"starwars" => Ok(Self::Starwars),
_ => Err(D::Error::unknown_variant(
&raw,
&["Off", "Slant", "Small", "Speed", "Starwars"],
)),
}
}
}

View file

@ -48,6 +48,18 @@ intro_text2 = PageTop brings back the essence of the classic web, renders on the
intro_code = Code
intro_have_fun = Coding is creating
# ListFilter component.
list_filter_submit = Filter
list_filter_reset = Clear
list_filter_pending = There are filters not applied yet
# ListView component.
list_view_summary = { $count ->
[0] No results
[one] 1 result
*[other] { $count } results
}
# Navbar component.
navbar_toggle = Toggle navigation

View file

@ -48,6 +48,18 @@ intro_text2 = PageTop reivindica la esencia de la web clásica, renderiza en el
intro_code = Código
intro_have_fun = Programar es crear
# ListFilter component.
list_filter_submit = Filtrar
list_filter_reset = Limpiar
list_filter_pending = Hay filtros sin aplicar
# ListView component.
list_view_summary = { $count ->
[0] Ningún resultado
[one] 1 resultado
*[other] { $count } resultados
}
# Navbar component.
navbar_toggle = Alternar navegación

View file

@ -41,9 +41,9 @@ struct Pending(Vec<(MessageLevel, String)>);
/// La *cookie* (`pagetop_flash`) sólo se crea cuando una respuesta usa este método; una aplicación
/// que no lo usa no envía ninguna. Es una *cookie* técnica: surge de una acción del usuario, dura
/// como mucho un minuto, se borra en cuanto se muestran los mensajes y no contiene datos que lo
/// identifiquen. Como *cookie* estrictamente necesaria para el servicio que el usuario ha pedido,
/// suele quedar exenta de consentimiento, aunque conviene declararla en la política de *cookies* de
/// la aplicación.
/// identifiquen. En España y en la Unión Europea no requiere la aceptación del usuario, aunque
/// conviene declararla en la política de *cookies* de la aplicación (ver
/// [*Cookies*](crate::web#cookies) en el módulo `web`).
///
/// El texto se muestra siempre como texto plano: el marcado que tenga una traducción aparecería
/// tal cual. Cada mensaje debe ser breve; los que no quepan en la *cookie* (unos 3,8 KB entre

View file

@ -23,9 +23,6 @@ use std::any::Any;
/// plantilla y el contenido del mensaje con los métodos específicos del tema, como
/// [`Theme::error_403()`], [`Theme::error_404()`] o [`Theme::error_fatal()`].
///
/// Sin `request` (`None`), la página se renderiza igualmente, pero sin el idioma negociado ni el
/// usuario actual, que dependen de la petición original.
///
/// [`Theme::error_403()`]: crate::core::theme::Theme::error_403
/// [`Theme::error_404()`]: crate::core::theme::Theme::error_404
/// [`Theme::error_fatal()`]: crate::core::theme::Theme::error_fatal
@ -33,24 +30,24 @@ use std::any::Any;
pub enum ErrorPage {
/// Petición incorrecta (400). El servidor no puede procesar la petición tal y como está
/// formulada (datos malformados, parámetros inválidos, etc.).
BadRequest(Option<HttpRequest>),
BadRequest(HttpRequest),
/// Acceso denegado (403). El usuario actual no tiene permiso para acceder al recurso.
///
/// Se renderiza con [`Theme::error_403()`](crate::core::theme::Theme::error_403).
AccessDenied(Option<HttpRequest>),
AccessDenied(HttpRequest),
/// Recurso no encontrado (404). La ruta solicitada no existe o no coincide con ningún handler.
///
/// Se renderiza con [`Theme::error_404()`](crate::core::theme::Theme::error_404).
NotFound(Option<HttpRequest>),
NotFound(HttpRequest),
/// Error interno del servidor (500). Un fallo controlado (no un `panic!`) impide completar la
/// petición.
InternalError(Option<HttpRequest>),
InternalError(HttpRequest),
/// Servicio no disponible (503). El servidor no puede atender la petición temporalmente
/// (mantenimiento, sobrecarga, etc.).
ServiceUnavailable(Option<HttpRequest>),
ServiceUnavailable(HttpRequest),
/// Tiempo de espera agotado (504). Una dependencia externa (proxy, servicio remoto) no ha
/// respondido a tiempo.
GatewayTimeout(Option<HttpRequest>),
GatewayTimeout(HttpRequest),
}
impl ErrorPage {
@ -72,12 +69,12 @@ impl ErrorPage {
let status = self.status_code();
let mut page = match self {
Self::AccessDenied(request) => {
let mut page = Page::default().with_request(request);
let mut page = Page::default().with_request(Some(request));
page.theme().error_403(&mut page);
page
}
Self::NotFound(request) => {
let mut page = Page::default().with_request(request);
let mut page = Page::default().with_request(Some(request));
page.theme().error_404(&mut page);
page
}
@ -85,7 +82,7 @@ impl ErrorPage {
| Self::InternalError(request)
| Self::ServiceUnavailable(request)
| Self::GatewayTimeout(request) => {
let mut page = Page::default().with_request(request);
let mut page = Page::default().with_request(Some(request));
page.theme().error_fatal(
&mut page,
status,
@ -126,7 +123,7 @@ impl IntoResponse for ErrorPage {
//
// Se registra como `.fallback()` del router principal desde [`Application`](crate::Application).
pub(crate) async fn route_not_found(request: HttpRequest) -> Result<Markup, ErrorPage> {
Err(ErrorPage::NotFound(Some(request)))
Err(ErrorPage::NotFound(request))
}
// Intercepta respuestas con un [`ErrorPage`] pendiente y las convierte en páginas HTML.

View file

@ -12,10 +12,12 @@ use crate::html::RoutePath;
/// página a la que ir para continuar.
///
/// `Waypoint` transporta ese valor a través de la cadena de pantallas. Se extrae de la petición
/// entrante con [`web::Query`](crate::web::Query), igual que cualquier otro parámetro, y se repone
/// en cada enlace o acción de formulario intermedia con [`append_to()`](Self::append_to) para que
/// sobreviva a la siguiente petición. Se resuelve con [`or()`](Self::or) al decidir el destino de
/// un enlace de vuelta o de una redirección.
/// entrante con [`web::Query`], igual que cualquier otro parámetro, y se repone en cada enlace o
/// acción de formulario intermedia con [`append_to()`] para que sobreviva a la siguiente petición.
/// Se resuelve con [`or()`] al decidir el destino de un enlace de vuelta o de una redirección.
///
/// Para volver a un listado con los filtros, el orden y la página en que se dejó no hace falta
/// transportarlo: basta con montar su ruta con [`web::remember_query()`].
///
/// # Ejemplo
///
@ -42,6 +44,11 @@ use crate::html::RoutePath;
/// Redirect::see_other(waypoint.or(ITEMS_PATH))
/// }
/// ```
///
/// [`append_to()`]: Self::append_to
/// [`or()`]: Self::or
/// [`web::Query`]: crate::web::Query
/// [`web::remember_query()`]: crate::web::remember_query
#[derive(AutoDefault, Clone, Debug, Deserialize)]
#[serde(from = "RawWaypoint")]
pub struct Waypoint {

View file

@ -22,8 +22,8 @@ pub use tracing::{debug_span, error_span, info_span, trace_span, warn_span};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::EnvFilter;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, PoisonError};
// Avisos generados antes de iniciar las trazas. La configuración se lee antes, porque las trazas
// dependen de la sección `[log]`, así que sus avisos se guardan aquí y se emiten al iniciarlas.
@ -34,9 +34,7 @@ static DEFERRED_WARNINGS: Mutex<Option<Vec<String>>> = Mutex::new(Some(Vec::new(
// basta para la configuración global, que `init()` lee antes de recoger los avisos. Usarla después
// es un error de programación: se emite como `error!` con el aviso incluido, para que no se pierda.
pub(crate) fn defer_warning(message: String) {
let mut deferred = DEFERRED_WARNINGS
.lock()
.unwrap_or_else(PoisonError::into_inner);
let mut deferred = DEFERRED_WARNINGS.lock().unwrap();
match deferred.as_mut() {
Some(warnings) => warnings.push(message),
None => {
@ -70,7 +68,7 @@ pub(crate) fn init() -> Option<WorkerGuard> {
// Al leer `SETTINGS` en la línea anterior ya se han guardado los avisos de la configuración.
let mut warnings = DEFERRED_WARNINGS
.lock()
.unwrap_or_else(PoisonError::into_inner)
.unwrap()
.take() // Deja `None`, desde ahora, `defer_warning()` trata cualquier aviso como mal uso.
.unwrap_or_default();
if !enabled {

View file

@ -32,6 +32,93 @@
//! conexiones HTTP sin cifrar fuera de `localhost`) se comprueban comparando `Origin` con `Host`.
//!
//! Ninguna protección frente a CSRF resiste un fallo de XSS en la propia aplicación.
//!
//! # *Cookies*
//!
//! PageTop sólo crea dos *cookies*, ambas propias (de la aplicación, no de terceros) y únicamente
//! cuando las provoca una acción del usuario:
//!
//! | *Cookie* | Para qué | Duración |
//! |------------------|----------------------------------------------------------------|-----------------------------------------------------------------|
//! | `pagetop_flash` | Mensajes para la página siguiente ([`ResponseExt`]) | Un minuto como máximo; se borra al mostrar los mensajes |
//! | `pagetop_list_*` | Filtros, orden y página de un listado ([`remember_query()`]) | La sesión del navegador; se borra al limpiar los filtros |
//!
//! Las extensiones pueden añadir las suyas; `pagetop-user`, por ejemplo, la de la sesión iniciada.
//!
//! ## Sin aceptación de *cookies*
//!
//! PageTop y sus extensiones propias (las que se publican con él, como `pagetop-user`) están
//! pensados para que una aplicación no tenga que pedir la aceptación de *cookies* sólo por usarlos.
//! Para ello, todas las *cookies* que crean cumplen los criterios que las principales normas de
//! privacidad del mundo tratan como necesarias para el servicio:
//!
//! - Son propias de la aplicación; ninguna es de terceros.
//! - Sólo existen para prestar algo que el usuario pide, y se crean por una acción suya.
//! - No identifican al usuario fuera de la aplicación ni sirven para seguirlo entre sitios. No se
//! usan para analítica, publicidad ni perfiles, y no se venden ni se comparten.
//! - Duran lo imprescindible para su función.
//!
//! Las normas que exigen consentimiento previo (las de la Unión Europea y otras de inspiración
//! europea) eximen expresamente las *cookies* necesarias para el servicio que pide el usuario. Las
//! que sólo obligan a ofrecer al usuario la posibilidad de oponerse (las de varios estados de
//! Estados Unidos, por ejemplo) se dirigen a la venta o el intercambio de datos y a la publicidad
//! dirigida, que estas *cookies* no hacen. En unas y otras, lo que sí se exige casi siempre es
//! informar: describirlas en la política de *cookies* o de privacidad de la aplicación (nombre,
//! finalidad, duración y si son propias), y la tabla anterior sirve para ello.
//!
//! La única que no queda exenta por sí sola es la de la sesión de `pagetop-user` cuando el usuario
//! marca "Recuérdame", porque se conserva aunque cierre el navegador. Pero es él quien la pide, y
//! marcar la casilla sabiendo que usa una *cookie* es ya su consentimiento. Es el criterio para
//! cualquier función que necesite una *cookie* que el usuario deba aceptar: el consentimiento se
//! pide en el propio gesto que la activa, nunca con un aviso aparte.
//!
//! La exención depende del uso: si una aplicación aprovechara estas *cookies* para otra cosa, o
//! alargara su duración, dejaría de valer. Las que añada cada aplicación (analítica, publicidad...)
//! sí suelen necesitar consentimiento.
//!
//! ## Unión Europea y España
//!
//! Es el marco más exigente y el que se ha tomado como referencia. La norma europea es una
//! directiva: no se aplica directamente, sino que cada Estado miembro (y también Islandia,
//! Liechtenstein y Noruega, del Espacio Económico Europeo) la incorpora a su propia ley, y la
//! autoridad de protección de datos de cada país publica sus propias guías, de modo que los
//! detalles pueden variar de un país a otro. Aquí se analizan la ley española y la guía de la
//! autoridad española.
//!
//! Guardar o leer información en el dispositivo del usuario exige su consentimiento previo, salvo
//! cuando es estrictamente necesario para prestar un servicio que el propio usuario ha pedido
//! (artículo 5.3 de la Directiva 2002/58/CE, la «Directiva ePrivacy», modificada por la Directiva
//! 2009/136/CE; en España, artículo 22.2 de la Ley 34/2002, de servicios de la sociedad de la
//! información, LSSI). El dictamen 04/2012 del Grupo de Trabajo del Artículo 29 sobre la exención
//! del requisito de consentimiento de las *cookies* (WP194), criterio que mantiene el Comité
//! Europeo de Protección de Datos, y la *Guía sobre el uso de las cookies* de la Agencia Española
//! de Protección de Datos (AEPD) concretan esa excepción. Entre sus ejemplos de *cookies* exentas
//! están las que recuerdan lo que el usuario ha hecho durante la sesión y las de personalización de
//! la interfaz que él mismo elige.
//!
//! Las dos de PageTop encajan en esa excepción, así que **no requieren la aceptación del usuario**
//! ni un aviso de *cookies* que la pida:
//!
//! - `pagetop_flash` completa una acción que el usuario acaba de pedir (guardar un formulario,
//! iniciar sesión...): lleva el aviso del resultado a la página siguiente y desaparece en cuanto
//! se muestra.
//! - `pagetop_list_*` es una personalización de la interfaz que el usuario activa al filtrar,
//! ordenar o paginar un listado, y dura lo que la sesión del navegador.
//!
//! El texto de un filtro puede contener datos personales (un nombre buscado), pero queda sólo en el
//! navegador de quien lo escribió. La AEPD recomienda describir también las *cookies* exentas en la
//! política de *cookies* de la aplicación.
//!
//! ## Otros países
//!
//! Fuera de la Unión Europea, los criterios anteriores se basan en lo que comparten las normas más
//! extendidas, no en un análisis país por país. Antes de desplegar en un país concreto conviene
//! contrastarlos con su normativa, que además cambia con frecuencia.
//!
//! Es el criterio de las normas y guías citadas, no un asesoramiento jurídico: en un despliegue con
//! exigencias legales concretas, el responsable del tratamiento debe confirmarlo.
//!
//! [`ResponseExt`]: crate::response::ResponseExt
use crate::{StaticFile, global};
@ -77,6 +164,10 @@ pub use routes::{Layers, Routes, StaticFiles};
mod endpoint;
pub use endpoint::Endpoint;
// Estado de los listados (filtros, orden, página) recordado entre pantallas.
mod remember;
pub use remember::remember_query;
use axum::body::Body;
use axum::extract::FromRequestParts;

View file

@ -45,7 +45,7 @@ pub(crate) async fn reject_cross_origin(request: Request, next: Next) -> Respons
);
let (mut parts, _) = request.into_parts();
let Ok(request) = HttpRequest::from_request_parts(&mut parts, &()).await;
ErrorPage::AccessDenied(Some(request)).into_response()
ErrorPage::AccessDenied(request).into_response()
}
// Con HTTP/2 el servidor llega en la URI (`:authority`) y no siempre en `Host`.

View file

@ -65,8 +65,8 @@ const FORWARDED_HEADERS: [http::HeaderName; 6] = [
/// .serve(&request)
/// .await
/// .map_err(|err| match err {
/// web::UploadError::NotFound(_) => ErrorPage::NotFound(Some(request)),
/// _ => ErrorPage::InternalError(Some(request)),
/// web::UploadError::NotFound(_) => ErrorPage::NotFound(request),
/// _ => ErrorPage::InternalError(request),
/// })
/// }
/// ```

384
src/web/remember.rs Normal file
View file

@ -0,0 +1,384 @@
use std::borrow::Cow;
use crate::web::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header};
use crate::web::{IntoResponse, MethodRouter, Request, Response};
use axum::extract::OriginalUri;
use axum::middleware::{self, Next};
// Prefijo del nombre de las *cookies*; cada listado añade el *hash* de su ruta.
const COOKIE_PREFIX: &str = "pagetop_list_";
// Longitud del nombre de las *cookies*: el prefijo y 16 cifras hexadecimales.
const NAME_LEN: usize = COOKIE_PREFIX.len() + 16;
const SEC_FETCH_SITE: HeaderName = HeaderName::from_static("sec-fetch-site");
// Atributos comunes. Sin `Max-Age` es una *cookie* de sesión.
const COOKIE_ATTRS: &str = "; HttpOnly; SameSite=Lax";
// Estado más largo que esto no se recuerda: un listado no necesita tanto y la *cookie* viaja en
// cada petición a su ruta y a las que cuelgan de ella.
const MAX_STATE_LEN: usize = 1024;
// Parámetro que olvida el estado guardado. Lo añade el enlace "Limpiar" de `ListFilter`.
const RESET_PARAM: &str = "reset";
/// Hace que un listado recuerde su último estado (filtros, orden y página) mientras dure la sesión
/// del navegador.
///
/// Envuelve el `MethodRouter` de la ruta de un listado. Cada vez que la página se pide con
/// parámetros en la *query string* (al filtrar, ordenar o paginar, también desde HTMX) y responde
/// con éxito, los guarda. Cuando se vuelve a pedir **sin parámetros**, como hacen los enlaces de
/// vuelta, las redirecciones tras guardar un formulario o el menú, redirige (`303`) a la misma
/// ruta con el estado guardado. Así no hay que transportar el estado del listado por cada pantalla
/// intermedia, como haría [`Waypoint`].
///
/// Si todos los parámetros llegan vacíos (`?q=&status=`, un filtro enviado sin rellenar), equivale
/// a no filtrar: no se guarda nada y se olvida el estado anterior.
///
/// Con el parámetro `reset` (`?reset`), que añade el enlace "Limpiar" de [`ListFilter`], olvida el
/// estado y redirige a la ruta sin parámetros. El parámetro `lang` no se guarda nunca: se conserva
/// el de la petición en curso. Las peticiones de HTMX se redirigen igual: HTMX sigue la redirección
/// y, si actualiza el historial del navegador, guarda la URL final, con el estado.
///
/// Si el estado guardado deja de dar una página válida (por ejemplo, un error `400` porque un
/// parámetro ha cambiado en una versión posterior de la aplicación), se olvida.
///
/// El estado guardado sólo cambia con las peticiones que salen de la propia aplicación o que se
/// escriben a mano (según la cabecera `Sec-Fetch-Site` que envían los navegadores): un enlace desde
/// otro sitio no puede fijar ni borrar los filtros que recuerda quien lo sigue.
///
/// Sólo actúa en las peticiones `GET`; las demás llegan al *handler* sin cambios.
///
/// # Qué necesita el listado
///
/// Basta con montar su ruta con esta función: los enlaces de vuelta, los botones de cancelar y las
/// redirecciones tras guardar no cambian, siguen apuntando a la ruta del listado sin parámetros.
/// Para que funcione:
///
/// - El estado del listado debe ir en la *query string*. Así lo hacen [`ListFilter`] (un
/// formulario `GET`), [`Pager`] y los enlaces de orden de [`Table`], también con HTMX. Un estado
/// que no esté en la URL (filtros enviados por `POST`, sólo en JavaScript) no se recuerda.
/// - Un enlace a la ruta con parámetros propios es un estado nuevo y no restaura el guardado.
/// - Cada ruta tiene su propio estado: `/projects/5/tasks` y `/projects/6/tasks` se recuerdan por
/// separado.
/// - Un formulario de filtros propio, en lugar de [`ListFilter`], debe enlazar su "Limpiar" a la
/// ruta con `?reset` (con [`RoutePath::with_flag("reset")`][with_flag]); si no, volvería a
/// restaurar el filtro que se quería quitar.
///
/// # *Cookies*
///
/// El estado se guarda en el navegador, en una *cookie* por listado (`pagetop_list_` seguido de un
/// código derivado de la ruta, limitada a esa ruta con `Path`), sin nada en el servidor. Es una
/// *cookie* técnica de sesión: sólo se crea cuando el usuario filtra, ordena o pagina, sólo
/// contiene los parámetros del listado y el navegador la borra al cerrarse (salvo los que restauran
/// la sesión anterior al abrirse de nuevo, que la conservan). En España y en la Unión Europea no
/// requiere la aceptación del usuario, aunque conviene declararla en la política de *cookies* de la
/// aplicación (ver [*Cookies*](crate::web#cookies) en el módulo `web`). Las ventanas y pestañas del
/// navegador comparten el mismo estado. No se recuerda un estado de más de 1024 caracteres ni uno
/// con caracteres que una *cookie* no admite (los navegadores ya los codifican en la URL).
///
/// # Ejemplo
///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// # async fn list_items() -> &'static str { "" }
/// fn configure_router(routes: web::Routes) -> web::Routes {
/// routes.public_route("/items", web::remember_query(web::get(list_items)))
/// }
/// ```
///
/// [`ListFilter`]: crate::base::component::ListFilter
/// [`Pager`]: crate::base::component::Pager
/// [`Table`]: crate::base::component::Table
/// [`Waypoint`]: crate::response::Waypoint
/// [with_flag]: crate::html::RoutePath::with_flag
pub fn remember_query(method_router: MethodRouter) -> MethodRouter {
method_router.layer(middleware::from_fn(remember))
}
async fn remember(request: Request, next: Next) -> Response {
if request.method() != Method::GET {
return next.run(request).await;
}
// Copia de la URI (sólo una cuenta de referencias), para que la ruta y la *query* sigan
// disponibles tras pasar la petición al *handler*. Dentro de un `Router` anidado la URI llega
// sin el prefijo; la *cookie* necesita la ruta real.
let uri = request
.extensions()
.get::<OriginalUri>()
.map_or_else(|| request.uri().clone(), |uri| uri.0.clone());
let raw_query = uri.query().unwrap_or_default();
let path = uri.path();
// Un `;` en la ruta rompería el atributo `Path` de la *cookie*. Y una ruta que empiece por `//`
// o `/\` (posible si el listado se monta en una ruta comodín) haría de la redirección una URL
// de otro sitio para el navegador.
if path.contains(';') || path.starts_with("//") || path.starts_with("/\\") {
return next.run(request).await;
}
let name = cookie_name(path);
// El estado guardado se vuelve a separar: una *cookie* manipulada podría traer `lang`, `reset`
// o nada útil (`&`), y redirigir con ella repetiría la redirección sin fin. Una con caracteres
// no válidos queda sin estado, como la que no trae nada útil, y se borra igual.
let saved = cookie_value(request.headers(), &name).map(|v| match str::from_utf8(v) {
Ok(v) if is_valid_state(v) => Params::split(v).state.into_owned(),
_ => String::new(),
});
// Sin parámetros ni estado guardado no hay nada que hacer.
if raw_query.is_empty() && saved.is_none() {
return next.run(request).await;
}
let query = Params::split(raw_query);
let writable = is_own_request(request.headers());
if query.reset {
let mut response = see_other(query.location(path, None));
if writable {
set_cookie(&mut response, &name, "", path, true);
}
return response;
}
if query.state.is_empty() {
match saved {
Some(saved) if !is_blank(&saved) => {
return see_other(query.location(path, Some(&saved)));
}
Some(_) => {
let mut response = next.run(request).await;
if writable {
set_cookie(&mut response, &name, "", path, true);
}
return response;
}
None => return next.run(request).await,
}
}
let state = &query.state;
let unchanged = saved.as_deref() == Some(state.as_ref());
let mut response = next.run(request).await;
if !writable {
return response;
}
if !response.status().is_success() {
// Un estado guardado que ya no da una página válida (parámetros de una versión anterior de
// la aplicación, un *handler* que redirige...) se olvida: si no, cada vuelta al listado
// repetiría el error, o la redirección, hasta cerrar el navegador.
if unchanged {
set_cookie(&mut response, &name, "", path, true);
}
return response;
}
if is_blank(state) {
if saved.is_some() {
set_cookie(&mut response, &name, "", path, true);
}
} else if !unchanged && state.len() <= MAX_STATE_LEN && is_valid_state(state) {
set_cookie(&mut response, &name, state, path, false);
}
response
}
// Redirección `303` a `location`, sin pasar por `Redirect`, que copia la cadena. La ruta sale de la
// URI de la petición y el estado está validado, así que siempre es una cabecera válida; si no lo
// fuera, mejor un `500`, como haría `Redirect`, que una redirección sin destino.
fn see_other(location: String) -> Response {
match HeaderValue::try_from(location) {
Ok(location) => (StatusCode::SEE_OTHER, [(header::LOCATION, location)]).into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}
// Sólo cambian el estado guardado las peticiones de la propia aplicación o escritas a mano
// (`Sec-Fetch-Site` igual a `same-origin` o `none`): un enlace o una redirección desde otro sitio,
// o desde otro subdominio, no puede fijar ni borrar los filtros de quien lo sigue. Sin la cabecera
// (navegadores antiguos, otros clientes) se admite, con el mismo criterio que la protección CSRF.
fn is_own_request(headers: &HeaderMap) -> bool {
headers
.get(SEC_FETCH_SITE)
.is_none_or(|site| matches!(site.as_bytes(), b"same-origin" | b"none"))
}
// Un estado con todos los valores vacíos (`q=&status=`, un filtro enviado sin rellenar) equivale a
// no filtrar: no merece una *cookie*.
fn is_blank(state: &str) -> bool {
state.split('&').all(|pair| {
pair.split_once('=')
.is_none_or(|(_, value)| value.is_empty())
})
}
// Parámetros de la petición separados en estado del listado, `lang` y la marca `reset`. Sin `lang`
// ni `reset`, lo habitual, el estado es la propia *query* y no se copia.
struct Params<'a> {
state: Cow<'a, str>,
lang: String,
reset: bool,
}
impl<'a> Params<'a> {
fn split(query: &'a str) -> Self {
let mut pairs = query.split('&');
if pairs.all(|pair| !pair.is_empty() && !matches!(key_of(pair), "lang" | RESET_PARAM)) {
return Params {
state: Cow::Borrowed(query),
lang: String::new(),
reset: false,
};
}
let mut state = String::with_capacity(query.len());
let mut split = Params {
state: Cow::Borrowed(""),
lang: String::new(),
reset: false,
};
for pair in query.split('&').filter(|pair| !pair.is_empty()) {
let target = match key_of(pair) {
"lang" => &mut split.lang,
RESET_PARAM => {
split.reset = true;
continue;
}
_ => &mut state,
};
if !target.is_empty() {
target.push('&');
}
target.push_str(pair);
}
split.state = Cow::Owned(state);
split
}
// Ruta del listado con el estado indicado y el `lang` de la petición en curso.
fn location(&self, path: &str, state: Option<&str>) -> String {
let state = state.unwrap_or_default();
let mut location = String::with_capacity(path.len() + state.len() + self.lang.len() + 2);
location.push_str(path);
for part in [state, self.lang.as_str()] {
if !part.is_empty() {
location.push(if location.len() == path.len() {
'?'
} else {
'&'
});
location.push_str(part);
}
}
location
}
}
fn key_of(pair: &str) -> &str {
pair.split_once('=').map_or(pair, |(key, _)| key)
}
// Nombre de la *cookie* de un listado, en la pila: el prefijo y el *hash* FNV-1a de 64 bits de la
// ruta en hexadecimal. Es estable entre procesos e instancias, a diferencia de `RandomState`, y
// basta para distinguir las rutas de una aplicación.
fn cookie_name(path: &str) -> [u8; NAME_LEN] {
let hash = path.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
});
let mut name = [0; NAME_LEN];
name[..COOKIE_PREFIX.len()].copy_from_slice(COOKIE_PREFIX.as_bytes());
for (i, digit) in name[COOKIE_PREFIX.len()..].iter_mut().enumerate() {
*digit = b"0123456789abcdef"[(hash >> (60 - 4 * i) & 0xf) as usize];
}
name
}
// Sólo caracteres admitidos en el valor de una *cookie* (RFC 6265: ASCII visible salvo `"`, `,`,
// `;` y `\`). Una *query string* que tenga otros no se recuerda; uno guardado que los tenga (una
// *cookie* manipulada) se ignora. Así el valor también es seguro en la cabecera `Location`.
fn is_valid_state(state: &str) -> bool {
!state.is_empty()
&& state
.bytes()
.all(|b| b.is_ascii_graphic() && !matches!(b, b'"' | b',' | b';' | b'\\'))
}
// Valor de la *cookie* `name`, si la petición la trae, sin validar toda la cabecera. Con HTTP/2 el
// navegador puede repartir las *cookies* en varias cabeceras `cookie`.
fn cookie_value<'a>(headers: &'a HeaderMap, name: &[u8]) -> Option<&'a [u8]> {
headers
.get_all(header::COOKIE)
.iter()
.flat_map(|value| value.as_bytes().split(|&b| b == b';'))
.filter_map(|part| part.trim_ascii().strip_prefix(name)?.strip_prefix(b"="))
.find(|value| !value.is_empty())
}
fn set_cookie(response: &mut Response, name: &[u8], value: &str, path: &str, expired: bool) {
let mut cookie = String::with_capacity(NAME_LEN + value.len() + path.len() + 40);
// El nombre es ASCII: el prefijo y cifras hexadecimales.
cookie.extend(name.iter().map(|&b| char::from(b)));
cookie.push('=');
cookie.push_str(value);
cookie.push_str("; Path=");
cookie.push_str(path);
cookie.push_str(COOKIE_ATTRS);
if expired {
cookie.push_str("; Max-Age=0");
}
if let Ok(cookie) = HeaderValue::try_from(cookie) {
response.headers_mut().append(header::SET_COOKIE, cookie);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lang_and_reset_are_kept_apart_from_the_state() {
let query = Params::split("q=acer&lang=es&page=2&reset");
assert_eq!(query.state, "q=acer&page=2");
assert_eq!(query.lang, "lang=es");
assert!(query.reset);
}
#[test]
fn a_query_without_lang_or_reset_is_not_copied() {
assert!(matches!(
Params::split("q=acer&page=2").state,
Cow::Borrowed("q=acer&page=2")
));
assert!(matches!(Params::split("q=a&lang=es").state, Cow::Owned(_)));
}
#[test]
fn location_joins_path_state_and_lang() {
let query = Params::split("lang=es");
assert_eq!(query.location("/items", Some("q=a")), "/items?q=a&lang=es");
assert_eq!(query.location("/items", None), "/items?lang=es");
assert_eq!(
Params::split("").location("/items", Some("q=a")),
"/items?q=a"
);
}
#[test]
fn cookie_names_are_stable_and_distinct_per_path() {
// Changing the hash would silently drop the state every browser has saved.
assert_eq!(&cookie_name("/items"), b"pagetop_list_fca267fbaf9eb12a");
assert_ne!(cookie_name("/items"), cookie_name("/items/archived"));
}
#[test]
fn a_state_is_blank_only_when_every_value_is_empty() {
assert!(is_blank("q=&status="));
assert!(is_blank("q"));
assert!(!is_blank("q=&status=active"));
assert!(!is_blank("page=1"));
}
#[test]
fn states_with_characters_not_allowed_in_cookies_are_rejected() {
assert!(is_valid_state("q=a%20b&sort=name&dir=asc"));
assert!(!is_valid_state("q=a,b"));
assert!(!is_valid_state("q=\"a\""));
assert!(!is_valid_state(""));
}
}

View file

@ -362,7 +362,7 @@ impl Drop for SavedFiles {
/// // Volver a mostrar el formulario con `err.message()`...
/// # todo!()
/// }
/// Err(_) => return Err(ErrorPage::InternalError(Some(request))),
/// Err(_) => return Err(ErrorPage::InternalError(request)),
/// };
/// let Some(photo) = sent.file("photo") else {
/// // Campo obligatorio sin archivo: volver a mostrar el formulario...

View file

@ -18,7 +18,7 @@ fn help() -> Lc {
#[pagetop::test]
async fn single_controls_point_to_their_help_text() {
let cases: [(String, &str); 5] = [
let cases: [(String, &str); 6] = [
(
render(
&mut form::input::Field::text()
@ -49,6 +49,15 @@ async fn single_controls_point_to_their_help_text() {
.await,
"edit-e-select-help",
),
(
render(
&mut form::Checkbox::check()
.with_name("g")
.with_help_text(help()),
)
.await,
"edit-g-checkbox-help",
),
];
for (html, id) in cases {
assert!(

View file

@ -0,0 +1,127 @@
use pagetop::prelude::*;
// **< ListFilter >*********************************************************************************
#[pagetop::test]
async fn renders_a_get_form_with_its_fields_and_the_button() {
let mut filter = ListFilter::new()
.with_filter_action("/items")
.with_field(form::input::Field::search().with_name("q"));
let html = filter.render(&mut Context::default()).await.into_string();
assert!(html.starts_with("<form"), "{html}");
assert!(html.contains(r#"class="list-filter""#), "{html}");
assert!(html.contains(r#"action="/items""#), "{html}");
assert!(
!html.contains("method="),
"a GET form needs no method: {html}"
);
assert!(html.contains(r#"name="q""#), "{html}");
assert!(html.contains(r#"type="submit""#), "{html}");
}
#[pagetop::test]
async fn keeps_the_language_of_the_action_in_a_hidden_field() {
// A GET form drops the query of its action, so the language must travel as a field.
let mut filter =
ListFilter::new().with_filter_action(RoutePath::new("/items").with_param("lang", "es-ES"));
let html = filter.render(&mut Context::default()).await.into_string();
assert!(html.contains(r#"type="hidden""#), "{html}");
assert!(html.contains(r#"name="lang""#), "{html}");
assert!(html.contains(r#"value="es-ES""#), "{html}");
}
#[pagetop::test]
async fn the_button_label_can_be_changed() {
let mut filter = ListFilter::new()
.with_filter_action("/items")
.with_submit(Lc::n("Search"));
let html = filter.render(&mut Context::default()).await.into_string();
assert!(html.contains("Search"), "{html}");
}
#[pagetop::test]
async fn by_default_it_applies_with_the_button() {
let mut filter = ListFilter::new().with_filter_action("/items");
let html = filter.render(&mut Context::default()).await.into_string();
assert!(!html.contains("onchange"), "{html}");
assert!(!html.contains("<noscript>"), "{html}");
}
#[pagetop::test]
async fn auto_submit_applies_on_change_and_keeps_the_button_only_without_javascript() {
let mut filter = ListFilter::new()
.with_filter_action("/items")
.with_auto_submit(true);
let html = filter.render(&mut Context::default()).await.into_string();
assert!(
html.contains(r#"onchange="this.requestSubmit()""#),
"{html}"
);
assert!(
html.contains(r#"<noscript><button type="submit""#),
"{html}"
);
}
#[pagetop::test]
async fn the_reset_link_goes_back_to_the_list_with_no_filters() {
let mut filter = ListFilter::new().with_filter_action("/items");
let html = filter.render(&mut Context::default()).await.into_string();
let link = html
.find("<a")
.map(|start| &html[start..])
.expect("reset link");
// `reset` also forgets the state a list may remember with `web::remember_query()`.
assert!(link.contains(r#"href="/items?reset""#), "{html}");
// Not intercepted by libraries that load only part of the page, so the fields are emptied too.
assert!(link.contains(r#"target="_top""#), "{html}");
}
#[pagetop::test]
async fn the_reset_link_can_be_removed() {
let mut filter = ListFilter::new()
.with_filter_action("/items")
.with_reset(false);
let html = filter.render(&mut Context::default()).await.into_string();
assert!(!html.contains("<a"), "{html}");
}
#[pagetop::test]
async fn with_the_button_it_marks_pending_changes() {
let mut cx = Context::default();
let mut filter = ListFilter::new().with_filter_action("/items");
let html = filter.render(&mut cx).await.into_string();
let assets = cx.render_assets().into_string();
// The script marks changed fields; the hidden status announces them to screen readers.
assert!(
assets.contains("/pagetop/js/list-filter.min.js"),
"{assets}"
);
assert!(
html.contains(r#"class="list-filter-status visually-hidden""#),
"{html}"
);
assert!(html.contains(r#"role="status""#), "{html}");
assert!(html.contains("data-pending="), "{html}");
}
#[pagetop::test]
async fn auto_submit_has_nothing_pending_to_mark() {
let mut cx = Context::default();
let mut filter = ListFilter::new()
.with_filter_action("/items")
.with_auto_submit(true);
let html = filter.render(&mut cx).await.into_string();
let assets = cx.render_assets().into_string();
assert!(!assets.contains("list-filter.min.js"), "{assets}");
assert!(!html.contains("list-filter-status"), "{html}");
}

View file

@ -0,0 +1,86 @@
use pagetop::prelude::*;
// **< ListView >***********************************************************************************
fn pager() -> Pager {
Pager::new()
.with_base_path("/items")
.with_current_page(1)
.with_items_per_page(10)
.with_total_items(50)
}
fn table() -> Table {
Table::new()
.with_column(Lc::n("Name"))
.with_empty(Lc::n("No items"))
}
#[pagetop::test]
async fn renders_its_id_and_class() {
let mut list = ListView::new().with_id("item-list").with_table(table());
let html = list.render(&mut Context::default()).await.into_string();
assert!(html.starts_with("<div"), "{html}");
assert!(html.contains(r#"id="item-list""#), "{html}");
assert!(html.contains(r#"class="list-view""#), "{html}");
}
#[pagetop::test]
async fn renders_the_parts_in_a_fixed_order() {
// Added in reverse order on purpose: the output order must not depend on it.
let mut list = ListView::new()
.with_pager(pager())
.with_table(table())
.with_action(Button::anchor(Lc::n("New item"), "/items/new"));
let mut cx = Context::default();
cx.push_message(MessageLevel::Error, Lc::n("Something failed"));
let html = list.render(&mut cx).await.into_string();
let actions = html.find("list-view-actions").expect("actions");
let message = html.find("Something failed").expect("message");
let table = html.find("<table").expect("table");
let pager = html.find("<nav").expect("pager");
assert!(actions < message && message < table && table < pager);
}
#[pagetop::test]
async fn without_actions_there_is_no_actions_row() {
let mut list = ListView::new().with_table(table());
let html = list.render(&mut Context::default()).await.into_string();
assert!(!html.contains("list-view-actions"));
assert!(html.contains("No items"));
}
#[pagetop::test]
async fn it_carries_a_summary_of_the_results_and_its_script() {
let mut cx = Context::default();
let mut list = ListView::new().with_table(table()).with_pager(pager());
let html = list.render(&mut cx).await.into_string();
let assets = cx.render_assets().into_string();
// The total of the pager, not only the rows on this page.
assert!(html.contains(r#"data-summary="50 results""#), "{html}");
assert!(assets.contains("/pagetop/js/list-view.min.js"), "{assets}");
}
#[pagetop::test]
async fn without_a_pager_the_summary_counts_the_rows() {
let mut list = ListView::new().with_table(
table()
.with_row(table::Row::new().with_cell(Lc::n("A")))
.with_row(table::Row::new().with_cell(Lc::n("B"))),
);
let html = list.render(&mut Context::default()).await.into_string();
assert!(html.contains(r#"data-summary="2 results""#), "{html}");
let mut one =
ListView::new().with_table(table().with_row(table::Row::new().with_cell(Lc::n("A"))));
let html = one.render(&mut Context::default()).await.into_string();
assert!(html.contains(r#"data-summary="1 result""#), "{html}");
let mut none = ListView::new().with_table(table());
let html = none.render(&mut Context::default()).await.into_string();
assert!(html.contains(r#"data-summary="No results""#), "{html}");
}

314
tests/web_remember_query.rs Normal file
View file

@ -0,0 +1,314 @@
use pagetop::prelude::*;
use web::http::{StatusCode, header};
struct ListExtension;
#[async_trait]
impl Extension for ListExtension {
fn configure_router(&self, routes: Routes) -> Routes {
routes
.public_route(
"/items",
web::remember_query(web::get(list).post(|| async { "posted" })),
)
.public_route("/failing", web::remember_query(web::get(failing)))
.public_route("/picky", web::remember_query(web::get(picky)))
.public_route("/{*rest}", web::remember_query(web::get(list)))
.route(
"/private",
Access::Authenticated,
web::remember_query(web::get(list)),
)
.nest(
"/nested",
Access::Public,
Router::new().route("/items", web::remember_query(web::get(list))),
)
}
}
async fn list(request: HttpRequest) -> String {
format!("query: {}", request.query_string())
}
async fn failing(request: HttpRequest) -> Result<Markup, ErrorPage> {
Err(ErrorPage::NotFound(request))
}
// Accepts any query but `q=stale`, as a list does with parameters from an older release.
async fn picky(request: HttpRequest) -> Result<String, ErrorPage> {
match request.query_string() {
"q=stale" => Err(ErrorPage::BadRequest(request)),
query => Ok(format!("query: {query}")),
}
}
async fn send(request: web::test::TestRequest) -> Response {
send_edited(request, |_| {}).await
}
// Sends `request` after `edit` changes its headers, for what `TestRequest` cannot express.
async fn send_edited(
request: web::test::TestRequest,
edit: impl FnOnce(&mut web::http::HeaderMap),
) -> Response {
let mut request = request.to_request();
edit(request.headers_mut());
let app = web::test::init_router(Application::prepare(&ListExtension).await.test());
web::test::send_request(&app, request).await
}
fn get(uri: &str, cookie: Option<&str>) -> web::test::TestRequest {
let request = web::test::TestRequest::get().uri(uri);
match cookie {
Some(cookie) => request.header("cookie", cookie),
None => request,
}
}
fn set_cookie(response: &Response) -> Option<&str> {
response
.headers()
.get(header::SET_COOKIE)
.and_then(|value| value.to_str().ok())
}
// `name=value` of the cookie set by `response`.
fn list_cookie(response: &Response) -> String {
let cookie = set_cookie(response).expect("the response sets the list cookie");
assert!(cookie.starts_with("pagetop_list_"), "{cookie}");
cookie.split(';').next().unwrap().to_owned()
}
fn location(response: &Response) -> &str {
response
.headers()
.get(header::LOCATION)
.and_then(|value| value.to_str().ok())
.expect("redirect location")
}
#[pagetop::test]
async fn a_list_remembers_its_state_and_restores_it_when_requested_without_it() {
let filtered = send(get("/items?q=acer&page=2&lang=es", None)).await;
assert_eq!(filtered.status(), StatusCode::OK);
let cookie = set_cookie(&filtered).unwrap();
assert!(
cookie.contains("=q=acer&page=2;"),
"lang is not saved: {cookie}"
);
assert!(cookie.contains("Path=/items;"), "{cookie}");
assert!(cookie.contains("HttpOnly"), "{cookie}");
assert!(!cookie.contains("Max-Age"), "a session cookie: {cookie}");
let cookie = list_cookie(&filtered);
let back = send(get("/items", Some(&cookie))).await;
assert_eq!(back.status(), StatusCode::SEE_OTHER);
assert_eq!(location(&back), "/items?q=acer&page=2");
// The language of the current request is kept.
let back = send(get("/items?lang=en", Some(&cookie))).await;
assert_eq!(location(&back), "/items?q=acer&page=2&lang=en");
}
#[pagetop::test]
async fn without_a_saved_state_the_list_is_served_as_is() {
let response = send(get("/items", None)).await;
assert_eq!(response.status(), StatusCode::OK);
assert!(set_cookie(&response).is_none());
assert_eq!(web::test::read_body_text(response).await, "query: ");
}
#[pagetop::test]
async fn the_same_state_is_not_saved_again() {
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let again = send(get("/items?q=acer", Some(&cookie))).await;
assert_eq!(again.status(), StatusCode::OK);
assert!(set_cookie(&again).is_none());
}
#[pagetop::test]
async fn reset_forgets_the_state() {
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let reset = send(get("/items?reset&lang=es", Some(&cookie))).await;
assert_eq!(reset.status(), StatusCode::SEE_OTHER);
assert_eq!(location(&reset), "/items?lang=es");
let expired = set_cookie(&reset).unwrap();
assert!(expired.starts_with(&cookie[..cookie.find('=').unwrap() + 1]));
assert!(expired.contains("Max-Age=0"), "{expired}");
}
#[pagetop::test]
async fn an_empty_filter_saves_nothing_and_forgets_the_state() {
// Submitting the filter with every field empty is the same as not filtering.
let blank = send(get("/items?q=&status=&lang=es", None)).await;
assert_eq!(blank.status(), StatusCode::OK);
assert!(set_cookie(&blank).is_none());
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let blank = send(get("/items?q=&status=", Some(&cookie))).await;
assert_eq!(blank.status(), StatusCode::OK);
let expired = set_cookie(&blank).expect("the saved state is forgotten");
assert!(expired.starts_with(&cookie[..cookie.find('=').unwrap() + 1]));
assert!(expired.contains("Max-Age=0"), "{expired}");
}
#[pagetop::test]
async fn htmx_requests_without_parameters_are_redirected_too() {
// HTMX follows the redirection, so a boosted back link also shows the remembered state.
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let request = get("/items", Some(&cookie)).header("hx-request", "true");
let response = send(request).await;
assert_eq!(response.status(), StatusCode::SEE_OTHER);
assert_eq!(location(&response), "/items?q=acer");
}
#[pagetop::test]
async fn failed_responses_and_other_methods_save_nothing() {
let failed = send(get("/failing?q=acer", None)).await;
assert_eq!(failed.status(), StatusCode::NOT_FOUND);
assert!(set_cookie(&failed).is_none());
let posted = send(web::test::TestRequest::post().uri("/items?q=acer")).await;
assert_eq!(posted.status(), StatusCode::OK);
assert!(set_cookie(&posted).is_none());
}
#[pagetop::test]
async fn a_saved_state_that_no_longer_gives_a_page_is_forgotten() {
let cookie = list_cookie(&send(get("/picky?q=fine", None)).await);
let name = &cookie[..cookie.find('=').unwrap()];
let stale = format!("{name}=q=stale");
// Coming back restores it, and the list now refuses it: the state is dropped, so the next visit
// does not fail again.
let back = send(get("/picky", Some(&stale))).await;
assert_eq!(location(&back), "/picky?q=stale");
let refused = send(get("/picky?q=stale", Some(&stale))).await;
assert_eq!(refused.status(), StatusCode::BAD_REQUEST);
let expired = set_cookie(&refused).expect("the stale state is forgotten");
assert!(expired.contains("Max-Age=0"), "{expired}");
// A failing request with other parameters keeps the saved state.
let refused = send(get("/picky?q=stale", Some(&cookie))).await;
assert_eq!(refused.status(), StatusCode::BAD_REQUEST);
assert!(set_cookie(&refused).is_none());
}
#[pagetop::test]
async fn states_that_cannot_go_in_a_cookie_are_not_saved() {
let long = format!("/items?q={}", "a".repeat(1100));
assert!(set_cookie(&send(get(&long, None)).await).is_none());
assert!(set_cookie(&send(get("/items?q=a,b", None)).await).is_none());
}
#[pagetop::test]
async fn a_tampered_cookie_is_ignored() {
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let name = &cookie[..cookie.find('=').unwrap()];
let tampered = format!("{name}=q=\"x\"");
let response = send(get("/items", Some(&tampered))).await;
assert_eq!(response.status(), StatusCode::OK);
let expired = set_cookie(&response).expect("the invalid cookie is removed");
assert!(expired.contains("Max-Age=0"), "{expired}");
}
#[pagetop::test]
async fn a_tampered_cookie_with_no_usable_state_is_forgotten_without_redirecting() {
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let name = &cookie[..cookie.find('=').unwrap()];
// Redirecting with any of these would land on the same list again, forever.
for value in ["&", "lang=es", "reset", "q=&status="] {
let tampered = format!("{name}={value}");
let response = send(get("/items", Some(&tampered))).await;
assert_eq!(response.status(), StatusCode::OK, "{value}");
let expired = set_cookie(&response).expect("the useless cookie is removed");
assert!(expired.contains("Max-Age=0"), "{value}: {expired}");
}
// Saved `lang` is never replayed: the one of the current request wins.
let tampered = format!("{name}=q=a&lang=fr");
let response = send(get("/items?lang=es", Some(&tampered))).await;
assert_eq!(location(&response), "/items?q=a&lang=es");
}
#[pagetop::test]
async fn links_from_other_sites_cannot_change_the_saved_state() {
// Without this, a page elsewhere could link to `/items?q=...` and fix what the list shows to
// whoever follows the link, every time they come back to it.
for site in ["cross-site", "same-site"] {
let foreign = get("/items?q=planted", None).header("sec-fetch-site", site);
let response = send(foreign).await;
assert_eq!(response.status(), StatusCode::OK, "{site}");
assert!(set_cookie(&response).is_none(), "{site}");
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
for uri in ["/items?reset", "/items?q=", "/items?q=other"] {
let foreign = get(uri, Some(&cookie)).header("sec-fetch-site", site);
assert!(set_cookie(&send(foreign).await).is_none(), "{site} {uri}");
}
// Restoring only reads the state, so it works whatever the origin of the link.
let foreign = get("/items", Some(&cookie)).header("sec-fetch-site", site);
assert_eq!(location(&send(foreign).await), "/items?q=acer", "{site}");
}
// Requests from the application itself, or typed by hand, do change it.
for site in ["same-origin", "none"] {
let own = get("/items?q=acer", None).header("sec-fetch-site", site);
assert!(set_cookie(&send(own).await).is_some(), "{site}");
}
}
#[pagetop::test]
async fn the_access_of_the_route_is_checked_before_the_saved_state() {
// An anonymous visitor with a cookie for a protected list gets neither a redirection that
// reveals the saved state nor a new cookie: access is checked first.
let cookie = "pagetop_list_c36367b4cdbc13dd=q=secret"; // The cookie name of `/private`.
for uri in ["/private", "/private?q=other", "/private?reset"] {
let response = send(get(uri, Some(cookie))).await;
assert_eq!(response.status(), StatusCode::FORBIDDEN, "{uri}");
assert!(set_cookie(&response).is_none(), "{uri}");
assert!(response.headers().get(header::LOCATION).is_none(), "{uri}");
}
}
#[pagetop::test]
async fn a_path_that_a_browser_would_read_as_another_site_is_left_alone() {
// A list mounted on a catch-all route also matches `//other.example`; redirecting there would
// send the browser to another site.
let response = send(get("//other.example/?q=a", None)).await;
assert_eq!(response.status(), StatusCode::OK);
assert!(set_cookie(&response).is_none());
}
#[pagetop::test]
async fn each_list_has_its_own_cookie_with_its_full_path() {
let top = list_cookie(&send(get("/items?q=a", None)).await);
let nested = send(get("/nested/items?q=b", None)).await;
assert!(set_cookie(&nested).unwrap().contains("Path=/nested/items;"));
let nested = list_cookie(&nested);
assert_ne!(
top.split('=').next(),
nested.split('=').next(),
"different lists, different cookies"
);
let back = send(get("/nested/items", Some(&nested))).await;
assert_eq!(location(&back), "/nested/items?q=b");
// The state of one list is never restored in another.
let other = send(get("/items", Some(&nested))).await;
assert_eq!(other.status(), StatusCode::OK);
assert!(other.headers().get(header::LOCATION).is_none());
}
#[pagetop::test]
async fn the_cookie_is_found_in_any_cookie_header() {
// With HTTP/2 the browser may split the cookies into several `cookie` headers.
let cookie = list_cookie(&send(get("/items?q=acer", None)).await);
let response = send_edited(get("/items", Some("theme=dark")), |headers| {
headers.append(header::COOKIE, cookie.parse().unwrap());
})
.await;
assert_eq!(location(&response), "/items?q=acer");
}