diff --git a/Cargo.lock b/Cargo.lock index cf831a0a..24ba63ca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2308,7 +2308,6 @@ dependencies = [ "argon2", "base64ct", "pagetop", - "pagetop-admin", "pagetop-htmx", "pagetop-mail", "pagetop-seaorm", diff --git a/README.md b/README.md index 74acf94c..6d7a322e 100644 --- a/README.md +++ b/README.md @@ -53,8 +53,8 @@ struct HelloWorld; #[async_trait] impl Extension for HelloWorld { - fn configure_router(&self, router: Router) -> Router { - router.route("/", web::get(hello_world)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/", web::get(hello_world)) } } @@ -102,8 +102,8 @@ El código se organiza en un *workspace* donde actualmente se incluyen los sigui ### Extensiones * **[pagetop-admin](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-admin)**, - panel de administración extensible, al que cada extensión añade sus secciones, páginas y - formularios de configuración. + páginas de ajustes del panel de administración que se guardan en la base de datos y se cambian + desde el propio panel. * **[pagetop-aliner](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-aliner)**, es un tema para demos y pruebas que muestra esquemáticamente la composición de las páginas HTML. @@ -128,7 +128,7 @@ El código se organiza en un *workspace* donde actualmente se incluyen los sigui integra [SeaORM](https://www.sea-ql.org/SeaORM) para acceder a bases de datos relacionales. * **[pagetop-user](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-user)**, - gestiona usuarios, autenticación, roles y permisos, con su administración en `pagetop-admin`. + gestiona usuarios, autenticación, roles y permisos, con su administración en el panel. ## Pruebas diff --git a/assets/scss/basic.scss b/assets/scss/basic.scss index 8165962b..7b7c7d6c 100644 --- a/assets/scss/basic.scss +++ b/assets/scss/basic.scss @@ -34,6 +34,9 @@ // Theme regions. @use "basic/regions"; +// Frame of the administration pages. +@use "basic/admin"; + // Styles for the pages of the `pagetop-user` extension. @use "basic/user"; diff --git a/assets/scss/basic/_admin.scss b/assets/scss/basic/_admin.scss new file mode 100644 index 00000000..624a278c --- /dev/null +++ b/assets/scss/basic/_admin.scss @@ -0,0 +1,51 @@ +// Frame of an administration page (`AdminFrame`), painted by the `Admin` template around the +// `Content` region: title with its action links, then the local tasks as tabs. + +.admin-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: .5rem 1rem; + margin: 1rem 0; +} + +.admin-page-title { + margin: 0; +} + +.admin-actions-list, +.admin-tasks-list { + display: flex; + flex-wrap: wrap; + gap: .5rem; + margin: 0; + padding: 0; + list-style: none; +} + +.admin-action-link { + display: inline-block; + padding: .375rem .75rem; + border: 1px solid var(--val-color--primary); + border-radius: .375rem; + text-decoration: none; +} + +.admin-local-tasks { + margin-bottom: 1rem; + border-bottom: 1px solid var(--val-color--bg--muted); +} + +.admin-task a { + display: block; + padding: .5rem .75rem; + margin-bottom: -1px; + border-bottom: 2px solid transparent; + text-decoration: none; +} + +.admin-task-active a { + border-bottom-color: var(--val-color--primary); + font-weight: 600; +} diff --git a/config/reference.toml b/config/reference.toml index 1b845948..189ebf6b 100644 --- a/config/reference.toml +++ b/config/reference.toml @@ -76,6 +76,10 @@ timezone_order = "Nearest" # Orden de esas regiones al elegir zona h timezone_per_user = true # Si cada usuario puede tener su propia zona horaria (true) o # se usa siempre 'timezone' (false). Con false no se ofrece # elegirla y la guardada se conserva por si se reactiva. +admin_path = "/admin" # Ruta raíz del panel de administración. Debe empezar por + # "/", 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". @@ -121,11 +125,11 @@ trusted_origins = [] # Otros orígenes desde los que un navega dir = "uploads" # Directorio de los archivos subidos, absoluto o relativo al # directorio de trabajo. Se crea al guardar el primero. max_request_size = 33_554_432 # Tamaño máximo en bytes de un envío 'multipart/form-data' - # completo (32 MiB), con todos sus archivos y campos; sustituye - # a 'server.max_body_size' en estas peticiones. Para admitir - # varios archivos debe ser varias veces mayor que - # 'max_file_size'. Uno mayor se rechaza con 413. 0 -> sin - # límite. + # completo (32 MiB), con todos sus archivos y campos; + # sustituye a 'server.max_body_size' en estas peticiones. + # Para admitir varios archivos debe ser varias veces mayor + # que 'max_file_size'. Uno mayor se rechaza con 413. 0 -> + # sin límite. max_file_size = 8_388_608 # Tamaño máximo en bytes de cada archivo por separado # (8 MiB). La aplicación puede cambiarlo en una subida # concreta. 0 -> sólo limita 'max_request_size'. diff --git a/examples/form-controls.rs b/examples/form-controls.rs index 6b82c06b..231548f5 100644 --- a/examples/form-controls.rs +++ b/examples/form-controls.rs @@ -11,8 +11,8 @@ impl Extension for FormControls { vec![&pagetop_aliner::Aliner, &pagetop_bootsier::Bootsier] } - fn configure_router(&self, router: Router) -> Router { - router.route("/", web::get(form_controls).post(form_controls)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/", web::get(form_controls).post(form_controls)) } } diff --git a/examples/hello-name.rs b/examples/hello-name.rs index a98cf05f..f4a0049f 100644 --- a/examples/hello-name.rs +++ b/examples/hello-name.rs @@ -4,8 +4,8 @@ struct HelloName; #[async_trait] impl Extension for HelloName { - fn configure_router(&self, router: Router) -> Router { - router.route("/hello/{name}", web::get(hello_name)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/hello/{name}", web::get(hello_name)) } } diff --git a/examples/hello-world.rs b/examples/hello-world.rs index bbbc3994..83d5cd5d 100644 --- a/examples/hello-world.rs +++ b/examples/hello-world.rs @@ -4,8 +4,8 @@ struct HelloWorld; #[async_trait] impl Extension for HelloWorld { - fn configure_router(&self, router: Router) -> Router { - router.route("/", web::get(hello_world)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/", web::get(hello_world)) } } diff --git a/examples/intro-colors.rs b/examples/intro-colors.rs index 2cea5c84..ae11ca2a 100644 --- a/examples/intro-colors.rs +++ b/examples/intro-colors.rs @@ -6,8 +6,8 @@ struct IntroColors; #[async_trait] impl Extension for IntroColors { - fn configure_router(&self, router: Router) -> Router { - router.route("/", web::get(intro_colors)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/", web::get(intro_colors)) } } diff --git a/examples/intro-datetime.rs b/examples/intro-datetime.rs index c15afb0b..92bbd1ee 100644 --- a/examples/intro-datetime.rs +++ b/examples/intro-datetime.rs @@ -6,8 +6,8 @@ struct IntroDatetime; #[async_trait] impl Extension for IntroDatetime { - fn configure_router(&self, router: Router) -> Router { - router.route("/", web::get(intro_datetime)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/", web::get(intro_datetime)) } } diff --git a/examples/intro-flex.rs b/examples/intro-flex.rs index 4f810f61..200be7d3 100644 --- a/examples/intro-flex.rs +++ b/examples/intro-flex.rs @@ -10,8 +10,8 @@ impl Extension for IntroFlex { vec![&pagetop_bootsier::Bootsier] } - fn configure_router(&self, router: Router) -> Router { - router.route("/", web::get(intro_flex)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/", web::get(intro_flex)) } } diff --git a/examples/intro-grid.rs b/examples/intro-grid.rs index 71d7b6c6..5cef1352 100644 --- a/examples/intro-grid.rs +++ b/examples/intro-grid.rs @@ -10,8 +10,8 @@ impl Extension for IntroGrid { vec![&pagetop_bootsier::Bootsier] } - fn configure_router(&self, router: Router) -> Router { - router.route("/", web::get(intro_grid)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/", web::get(intro_grid)) } } diff --git a/examples/intro-responsive.rs b/examples/intro-responsive.rs index 3b06df66..3aabcad8 100644 --- a/examples/intro-responsive.rs +++ b/examples/intro-responsive.rs @@ -10,8 +10,8 @@ impl Extension for IntroResponsive { vec![&pagetop_bootsier::Bootsier] } - fn configure_router(&self, router: Router) -> Router { - router.route("/", web::get(intro_responsive)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/", web::get(intro_responsive)) } } diff --git a/examples/intro-spacing.rs b/examples/intro-spacing.rs index a3b0d51a..e3c692c7 100644 --- a/examples/intro-spacing.rs +++ b/examples/intro-spacing.rs @@ -10,8 +10,8 @@ impl Extension for IntroSpacing { vec![&pagetop_bootsier::Bootsier] } - fn configure_router(&self, router: Router) -> Router { - router.route("/", web::get(intro_spacing)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/", web::get(intro_spacing)) } } diff --git a/examples/navbar-menus.rs b/examples/navbar-menus.rs index 97c2009d..249669b0 100644 --- a/examples/navbar-menus.rs +++ b/examples/navbar-menus.rs @@ -11,8 +11,8 @@ impl Extension for NavbarMenus { vec![&pagetop_bootsier::Bootsier] } - fn configure_router(&self, router: Router) -> Router { - router.route("/", web::get(navbar_menus)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/", web::get(navbar_menus)) } } diff --git a/extensions/pagetop-admin/Cargo.toml b/extensions/pagetop-admin/Cargo.toml index c61c2550..38d0d657 100644 --- a/extensions/pagetop-admin/Cargo.toml +++ b/extensions/pagetop-admin/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "pagetop-admin" -description = "Panel de administración extensible para PageTop." +description = "Ajustes guardados en la base de datos para el panel de administración de PageTop." version = "0.1.0" categories = ["web-programming", "development-tools"] keywords = ["pagetop", "admin", "cms", "settings", "ssr"] diff --git a/extensions/pagetop-admin/README.md b/extensions/pagetop-admin/README.md index 92396a03..df6a190e 100644 --- a/extensions/pagetop-admin/README.md +++ b/extensions/pagetop-admin/README.md @@ -2,7 +2,7 @@

PageTop Admin

-

Panel de administración extensible para PageTop.

+

Ajustes guardados en la base de datos para el panel de administración de PageTop.

[![Doc API](https://img.shields.io/docsrs/pagetop-admin?label=Doc%20API&style=for-the-badge&logo=Docs.rs)](https://docs.rs/pagetop-admin) [![Crates.io](https://img.shields.io/crates/v/pagetop-admin.svg?style=for-the-badge&logo=ipfs)](https://crates.io/crates/pagetop-admin) @@ -11,11 +11,8 @@ -Añade a una aplicación PageTop un panel de administración en `/admin` que cada extensión amplía con -sus propias secciones, páginas, pestañas y botones, declarados con acciones. Trae las secciones -habituales (personas, estructura, configuración, informes y ayuda), formularios de configuración -que se guardan en la base de datos y un menú de navegación hecho sólo con componentes del núcleo, -para que funcione con cualquier tema. +Añade al panel de administración de PageTop **ajustes que se guardan en la base de datos** y que un +administrador cambia desde el propio panel, con la aplicación en marcha. ## Sobre PageTop @@ -23,6 +20,35 @@ para que funcione con cualquier tema. clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y configurables, basadas en HTML, CSS y JavaScript. +## Qué aporta + +- **Páginas de ajustes sin código propio.** Una extensión describe los campos con un + `SettingsSchema` y declara la página con `DeclareConfigForms`. `pagetop-admin` monta su ruta, + pinta el formulario con los valores guardados y guarda lo que se envía, salvo que falte algún + campo obligatorio o llegue vacío. +- **El almacén de los valores.** La tabla `settings`, que crea al arrancar, y las funciones del + módulo `settings` para leerlos (`settings::get_or()` y compañía) y escribirlos desde código. +- **El formulario** (`ConfigForm`), por si una página propia quiere mostrar el de un esquema. + +## En qué se apoya + +El panel en sí es de PageTop (el módulo `pagetop::admin`): su página de inicio, sus secciones, la +navegación, las migas de pan y la plantilla de administración (`Page::admin()`). Cada página de +ajustes es una `AdminPage` del núcleo, así que aparece en el panel como cualquier otra, con su +sección y su permiso, y se pinta con cualquier tema. Una extensión que sólo añade páginas propias al +panel, sin ajustes, no necesita `pagetop-admin`. + +## Cuándo usarlo + +Para valores que decide quien administra el sitio y que cambian con el tiempo: un aviso en la +portada, un número de plazas, abrir o cerrar las inscripciones... Lo que fija quien despliega la +aplicación (la base de datos, el servidor de correo, los límites) va en los archivos de +configuración (ver el módulo `pagetop::config`), que no se pueden cambiar desde el panel y exigen +reiniciar. + +Los valores que envía el formulario se guardan como texto, también los de los campos numéricos y las +casillas (`"42"`, `"true"`): se leen como `String` y se convierten al usarlos. + ## Guía rápida **Añade la dependencia** a tu `Cargo.toml`: @@ -32,16 +58,15 @@ configurables, basadas en HTML, CSS y JavaScript. pagetop-admin = "..." ``` -La configuración se guarda con `pagetop-seaorm`: la aplicación elige el motor de base de datos con -su *feature* (`postgres`, `mysql` o `sqlite`) y configura la conexión en la sección `[database]`. +Los ajustes se guardan con `pagetop-seaorm`: la aplicación elige el motor de base de datos con su +*feature* (`postgres`, `mysql` o `sqlite`) y configura la conexión en la sección `[database]`. -**Declara la extensión** como dependencia de la tuya (`&pagetop_admin::Admin`) y **añade al panel** -tus secciones, páginas o formularios de configuración: +**Declara la extensión** como dependencia de la tuya (`&pagetop_admin::Admin`); si no, sus páginas +de ajustes no se montan. Después **declara tus páginas de ajustes**, cada una con su permiso: ```rust,no_run use pagetop::prelude::*; use pagetop_admin::prelude::*; -use pagetop_admin::settings::{SettingField, SettingsSchema}; pub struct MyApp; @@ -52,25 +77,17 @@ impl Extension for MyApp { } fn actions(&self) -> Vec { - actions![ - DeclareAdminPages::new(declare_pages), - ] - } - - fn configure_router(&self, router: Router) -> Router { - router.route("/admin/config/myapp", web::get(config_handler)) + actions![DeclareConfigForms::new(declare_forms)] } } -fn declare_pages(bag: &mut PageBag) { - bag.add(AdminPage { - path: "/admin/config/myapp".to_owned(), - section: "config".to_owned(), - title: Lc::n("My App"), - description: Some(Lc::n("Configure My App.")), - weight: 0, - permission: &MyPermission::Config, - kind: AdminPageKind::View, +fn declare_forms(bag: &mut ConfigFormBag) { + bag.add(ConfigFormPage { + page: AdminPage::new("config/myapp", "config", Lc::n("My App"), &MyPermission::Config) + .with_description(Lc::n("Name of the site.")), + schema: SettingsSchema::new("myapp").with_field( + SettingField::text("site_name", Lc::n("Site name")).with_required(true), + ), }); } @@ -87,31 +104,12 @@ impl Permission for MyPermission { } } -async fn config_handler(request: HttpRequest) -> Result { - let schema = SettingsSchema::new("myapp.config") - .with_field(SettingField::text("site_name", "Site name").with_required(true)); - - let title = "My App configuration"; - let mut form = ConfigForm::with_schema(schema); - let mut cx = Context::new(request.clone()); - let content = form.render(&mut cx).await; - - Page::admin(request) - .with_title(Lc::n(title)) - .with_child( - AdminFrame::new() - .with_title(Lc::n(title)) - .with_child(Html::with(move |_| content.clone())), - ) - .render() - .await +// Los valores se guardan con la clave `<ámbito>.`. +async fn site_name() -> String { + pagetop_admin::settings::get_or("myapp.site_name", String::new()).await } ``` -Para formularios de configuración enteramente automáticos (GET y POST gestionados por -`pagetop-admin`), usa `AdminPageKind::ConfigForm(schema)` en lugar de `View` y no registres la ruta -tú mismo. - ## Advertencia **PageTop** es un proyecto personal para aprender [Rust](https://www.rust-lang.org/es) y conocer su diff --git a/extensions/pagetop-admin/src/action.rs b/extensions/pagetop-admin/src/action.rs index 99117a3b..de4159ec 100644 --- a/extensions/pagetop-admin/src/action.rs +++ b/extensions/pagetop-admin/src/action.rs @@ -1,286 +1,119 @@ -//! Tipos de acción que `pagetop-admin` expone para que otras extensiones registren -//! secciones, páginas, tareas y acciones en el panel de administración. -//! -//! El flujo de `registry::build()` despacha estas acciones en este orden: -//! -//! 1. `DeclareAdminSections` - secciones (agrupaciones del sidebar). -//! 2. `DeclareAdminPages` - páginas del panel. -//! 3. `DeclareAdminTasks` - tareas (pestañas) locales por página. -//! 4. `DeclareAdminActions` - acciones locales (botones) por página. +//! Acción para declarar páginas de ajustes que `pagetop-admin` pinta y guarda por sí solo. use pagetop::prelude::*; -use crate::registry::{AdminAction, AdminPage, AdminSection, AdminTask}; +use std::collections::BTreeMap; +use std::sync::OnceLock; -// **< Tipo de callbacks >************************************************************************** +use crate::settings::SettingsSchema; -pub type FnSectionBag = fn(&mut SectionBag); -pub type FnPageBag = fn(&mut PageBag); -pub type FnTaskBag = fn(&mut TaskBag); -pub type FnActionBag = fn(&mut ActionBag); +// **< ConfigFormPage >***************************************************************************** -// **< Bolsas de declaración >********************************************************************** - -/// Bolsa de secciones para [`DeclareAdminSections`]. -pub struct SectionBag { - pub(crate) sections: Vec, -} - -impl SectionBag { - /// Añade una sección al registro. - pub fn add(&mut self, section: AdminSection) { - self.sections.push(section); - } -} - -/// Bolsa de páginas para [`DeclareAdminPages`]. -pub struct PageBag { - pub(crate) pages: Vec, -} - -impl PageBag { - /// Añade una página al registro. - pub fn add(&mut self, page: AdminPage) { - self.pages.push(page); - } -} - -/// Bolsa de tareas para [`DeclareAdminTasks`]. -pub struct TaskBag { - pub(crate) tasks: Vec, -} - -impl TaskBag { - /// Añade una tarea local al registro. - pub fn add(&mut self, task: AdminTask) { - self.tasks.push(task); - } -} - -/// Bolsa de acciones locales para [`DeclareAdminActions`]. -pub struct ActionBag { - pub(crate) actions: Vec, -} - -impl ActionBag { - /// Añade una acción local al registro. - pub fn add(&mut self, action: AdminAction) { - self.actions.push(action); - } -} - -// **< DeclareAdminSections >*********************************************************************** - -/// Acción para declarar secciones del panel de administración. +/// Página de ajustes del panel: una [`AdminPage`] y el esquema de su formulario. /// -/// Se despacha durante `registry::build()` (dentro de `initialize()`). El callback -/// recibe un [`SectionBag`] y puede llamar a `add()` para registrar secciones. +/// `pagetop-admin` la añade al registro del panel como cualquier otra página, monta su ruta y +/// responde a su `GET` (el formulario con los valores guardados) y a su `POST` (los guarda en la +/// base de datos). La extensión que la declara no registra ninguna ruta. +#[derive(Clone)] +pub struct ConfigFormPage { + /// Página del panel, con su ruta relativa a la raíz del panel. + pub page: AdminPage, + /// Esquema del formulario. + pub schema: SettingsSchema, +} + +/// Bolsa de páginas de ajustes para [`DeclareConfigForms`]. +pub struct ConfigFormBag { + forms: Vec, +} + +impl ConfigFormBag { + /// Añade una página de ajustes. + pub fn add(&mut self, form: ConfigFormPage) { + self.forms.push(form); + } +} + +// **< DeclareConfigForms >************************************************************************* + +/// Tipo de función para declarar páginas de ajustes. +pub type FnActionDeclareConfigForms = fn(bag: &mut ConfigFormBag); + +/// Acción para declarar páginas de ajustes que gestiona `pagetop-admin` (ver [`ConfigFormPage`]). /// /// # Ejemplo /// /// ```rust,no_run /// use pagetop::prelude::*; -/// use pagetop_admin::action::{DeclareAdminSections, SectionBag}; -/// use pagetop_admin::registry::AdminSection; +/// use pagetop_admin::prelude::*; /// -/// fn declare_sections(bag: &mut SectionBag) { -/// bag.add(AdminSection { -/// key: "tools".to_owned(), -/// path: "/admin/tools".to_owned(), -/// title: Lc::n("Tools"), -/// weight: 60, -/// }); +/// #[derive(Clone, Copy, Debug)] +/// enum MyPermission { +/// Config, /// } -/// // En Extension::actions(): -/// // DeclareAdminSections::new(declare_sections) -/// ``` -pub struct DeclareAdminSections { - f: FnSectionBag, - weight: Weight, -} - -impl ActionDispatcher for DeclareAdminSections { - fn weight(&self) -> Weight { - self.weight - } -} - -impl DeclareAdminSections { - pub fn new(f: FnSectionBag) -> Self { - DeclareAdminSections { f, weight: 0 } - } - - pub fn with_weight(mut self, w: Weight) -> Self { - self.weight = w; - self - } - - pub(crate) fn dispatch(bag: &mut SectionBag) { - dispatch_actions(|action: &Self| (action.f)(bag)); - } -} - -// **< DeclareAdminPages >************************************************************************** - -/// Acción para declarar páginas del panel de administración. /// -/// Se despacha durante `registry::build()`. El callback recibe un [`PageBag`]. -/// -/// # Ejemplo -/// -/// ```rust,no_run -/// use pagetop::prelude::*; -/// use pagetop_admin::action::{DeclareAdminPages, PageBag}; -/// use pagetop_admin::registry::{AdminPage, AdminPageKind}; -/// -/// struct ExportPermission; -/// -/// impl Permission for ExportPermission { +/// impl Permission for MyPermission { /// fn key(&self) -> CowStr { -/// "tools:export".into() +/// "myapp:config".into() /// } /// } /// -/// fn declare_pages(bag: &mut PageBag) { -/// bag.add(AdminPage { -/// path: "/admin/tools/export".to_owned(), -/// section: "tools".to_owned(), -/// title: Lc::n("Export"), -/// description: Some(Lc::n("Export site data.")), -/// weight: 0, -/// permission: &ExportPermission, -/// kind: AdminPageKind::View, +/// fn declare_forms(bag: &mut ConfigFormBag) { +/// bag.add(ConfigFormPage { +/// page: AdminPage::new("config/myapp", "config", Lc::n("My App"), &MyPermission::Config) +/// .with_description(Lc::n("Configure My App.")), +/// schema: SettingsSchema::new("myapp.config").with_field( +/// SettingField::text("site_name", Lc::n("Site name")).with_required(true), +/// ), /// }); /// } /// // En Extension::actions(): -/// // DeclareAdminPages::new(declare_pages) +/// // DeclareConfigForms::new(declare_forms) /// ``` -pub struct DeclareAdminPages { - f: FnPageBag, +pub struct DeclareConfigForms { + f: FnActionDeclareConfigForms, weight: Weight, } -impl ActionDispatcher for DeclareAdminPages { +impl ActionDispatcher for DeclareConfigForms { fn weight(&self) -> Weight { self.weight } } -impl DeclareAdminPages { - pub fn new(f: FnPageBag) -> Self { - DeclareAdminPages { f, weight: 0 } +impl DeclareConfigForms { + /// Registra una nueva acción para declarar páginas de ajustes. + pub fn new(f: FnActionDeclareConfigForms) -> Self { + DeclareConfigForms { f, weight: 0 } } - pub fn with_weight(mut self, w: Weight) -> Self { - self.weight = w; + /// Opcional. Acciones con pesos más bajos se aplican antes. Se pueden usar valores negativos. + pub fn with_weight(mut self, value: Weight) -> Self { + self.weight = value; self } - - pub(crate) fn dispatch(bag: &mut PageBag) { - dispatch_actions(|action: &Self| (action.f)(bag)); - } } -// **< DeclareAdminTasks >************************************************************************** +// **< Registro de las páginas de ajustes >********************************************************* -/// Acción para declarar tareas (pestañas) locales en páginas del panel. -/// -/// Se despacha durante `registry::build()`. El callback recibe un [`TaskBag`]. -/// Cada [`AdminTask`] indica en `parent_path` la página a la que pertenece. -/// -/// # Ejemplo -/// -/// ```rust,no_run -/// use pagetop::prelude::*; -/// use pagetop_admin::action::{DeclareAdminTasks, TaskBag}; -/// use pagetop_admin::registry::AdminTask; -/// -/// fn declare_tasks(bag: &mut TaskBag) { -/// bag.add(AdminTask { -/// path: "/admin/tools/export/csv".to_owned(), -/// parent_path: "/admin/tools/export".to_owned(), -/// title: Lc::n("CSV"), -/// weight: 0, -/// is_default: true, -/// permission: None, -/// }); -/// } -/// // En Extension::actions(): -/// // DeclareAdminTasks::new(declare_tasks) -/// ``` -pub struct DeclareAdminTasks { - f: FnTaskBag, - weight: Weight, +// Esquemas de las páginas de ajustes, por su ruta relativa a la raíz del panel. +static CONFIG_FORMS: OnceLock> = OnceLock::new(); + +// Añade las páginas de ajustes al registro del panel. `pagetop-admin` lo registra como una acción +// `DeclareAdminPages`, así que se ejecuta una sola vez, cuando el núcleo construye el registro. +pub(crate) fn declare_config_form_pages(bag: &mut AdminPageBag) { + let mut forms = ConfigFormBag { forms: Vec::new() }; + dispatch_actions(|action: &DeclareConfigForms| (action.f)(&mut forms)); + let mut schemas = BTreeMap::new(); + for form in forms.forms { + schemas.insert(form.page.path().to_owned(), form.schema); + bag.add(form.page); + } + let _ = CONFIG_FORMS.set(schemas); } -impl ActionDispatcher for DeclareAdminTasks { - fn weight(&self) -> Weight { - self.weight - } -} - -impl DeclareAdminTasks { - pub fn new(f: FnTaskBag) -> Self { - DeclareAdminTasks { f, weight: 0 } - } - - pub fn with_weight(mut self, w: Weight) -> Self { - self.weight = w; - self - } - - pub(crate) fn dispatch(bag: &mut TaskBag) { - dispatch_actions(|action: &Self| (action.f)(bag)); - } -} - -// **< DeclareAdminActions >************************************************************************ - -/// Acción para declarar acciones locales (botones de acción) en páginas del panel. -/// -/// Se despacha durante `registry::build()`. El callback recibe un [`ActionBag`]. -/// Cada [`AdminAction`] indica en `for_path` la página en la que aparece el botón. -/// -/// # Ejemplo -/// -/// ```rust,no_run -/// use pagetop::prelude::*; -/// use pagetop_admin::action::{DeclareAdminActions, ActionBag}; -/// use pagetop_admin::registry::AdminAction; -/// -/// fn declare_actions(bag: &mut ActionBag) { -/// bag.add(AdminAction { -/// url: "/admin/tools/export/new".to_owned(), -/// for_path: "/admin/tools/export".to_owned(), -/// title: Lc::n("Add export"), -/// weight: 0, -/// }); -/// } -/// // En Extension::actions(): -/// // DeclareAdminActions::new(declare_actions) -/// ``` -pub struct DeclareAdminActions { - f: FnActionBag, - weight: Weight, -} - -impl ActionDispatcher for DeclareAdminActions { - fn weight(&self) -> Weight { - self.weight - } -} - -impl DeclareAdminActions { - pub fn new(f: FnActionBag) -> Self { - DeclareAdminActions { f, weight: 0 } - } - - pub fn with_weight(mut self, w: Weight) -> Self { - self.weight = w; - self - } - - pub(crate) fn dispatch(bag: &mut ActionBag) { - dispatch_actions(|action: &Self| (action.f)(bag)); - } +// Esquemas de las páginas de ajustes, por su ruta relativa a la raíz del panel. +pub(crate) fn config_forms() -> &'static BTreeMap { + static EMPTY: BTreeMap = BTreeMap::new(); + CONFIG_FORMS.get().unwrap_or(&EMPTY) } diff --git a/extensions/pagetop-admin/src/component.rs b/extensions/pagetop-admin/src/component.rs index e6325daf..c4f85a61 100644 --- a/extensions/pagetop-admin/src/component.rs +++ b/extensions/pagetop-admin/src/component.rs @@ -1,9 +1,5 @@ //! Componentes de renderizado del panel de administración. -mod admin_frame; -mod admin_menu; mod config_form; -pub use admin_frame::AdminFrame; -pub use admin_menu::AdminMenu; pub use config_form::ConfigForm; diff --git a/extensions/pagetop-admin/src/component/admin_frame.rs b/extensions/pagetop-admin/src/component/admin_frame.rs deleted file mode 100644 index 690d9074..00000000 --- a/extensions/pagetop-admin/src/component/admin_frame.rs +++ /dev/null @@ -1,150 +0,0 @@ -use pagetop::prelude::*; - -use crate::LOCALES_ADMIN; -use crate::registry; - -/// Componente de layout principal de una página del panel de administración. -/// -/// Renderiza breadcrumb, encabezado (título + acciones locales), tareas locales (pestañas) y el -/// contenido de la página. No incluye ningún menú de navegación: mostrar las secciones del panel -/// (el "sidebar" o el "menú superior", según el tema) es responsabilidad del tema que intercepte -/// [`CoreTemplates::Admin`](pagetop::core::theme::CoreTemplates::Admin) (por ejemplo -/// `pagetop-bootsier`) leyendo directamente [`crate::registry::global()`]. El tema básico de -/// PageTop no lo hace, y una página de administración sigue siendo completamente navegable sin él, -/// a través del *dashboard* (`/admin`), las páginas de sección y este mismo breadcrumb. -/// -/// ```html -/// -///
-///

Title

-///
    ...
-///
-/// -///
...
-/// ``` -/// -/// El contenido son sus propios hijos ([`Children`]), igual que en cualquier otro componente -/// contenedor (p. ej. [`Block`](pagetop::base::component::Block)): admite tantos `with_child(...)` -/// como haga falta, cada uno renderizado en el ciclo normal de componentes. -#[derive(AutoDefault, Clone, Debug, Getters)] -pub struct AdminFrame { - /// Devuelve el título de la página. - title: Lc, - /// Devuelve la lista de componentes hijo de la página. - children: Children, -} - -#[async_trait] -impl Component for AdminFrame { - fn new() -> Self { - Self::default() - } - - async fn prepare(&self, cx: &mut Context) -> Result { - let path = cx - .request() - .map(|r| r.path().to_string()) - .unwrap_or_else(|| "/".to_string()); - - let breadcrumbs = render_breadcrumbs(cx, &path).await; - let local_tasks = render_local_tasks(cx, &path); - let local_acts = render_local_actions(cx, &path); - let body = self.children().render(cx).await; - - Ok(html! { - (breadcrumbs) - header class="admin-header" { - h1 class="admin-page-title" { (self.title().using(cx)) } - (local_acts) - } - @if !local_tasks.0.is_empty() { - nav class="admin-local-tasks" { (local_tasks) } - } - div class="admin-content" { - (body) - } - }) - } -} - -#[builder_impl] -impl AdminFrame { - /// Establece el título de la página. - pub fn with_title(mut self, title: Lc) -> Self { - self.title = title; - self - } - - /// Añade un componente hijo al contenido de la página. - pub fn with_child(mut self, op: impl Into) -> Self { - self.children.alter_child(op.into()); - self - } -} - -// **< Breadcrumbs >******************************************************************************** - -async fn render_breadcrumbs(cx: &mut Context, current_path: &str) -> Markup { - let reg = registry::global(); - let base = crate::ADMIN_BASE_PATH; - - let home_label = Lc::t("admin-breadcrumb-home", &LOCALES_ADMIN); - let mut bc = Breadcrumb::new().with_crumb(breadcrumb::Crumb::new(home_label, base)); - - if let Some(page) = reg.pages().get(current_path) { - if let Some(section) = reg.sections().get(&page.section) { - bc = bc.with_crumb(breadcrumb::Crumb::new( - section.title.clone(), - section.path.as_str(), - )); - } - bc = bc.with_crumb(breadcrumb::Crumb::current(page.title.clone())); - } else if let Some(section) = reg.sections().values().find(|s| s.path == current_path) { - // La ruta actual es la propia sección (su página de aterrizaje), no una `AdminPage` - // registrada dentro de ella. - bc = bc.with_crumb(breadcrumb::Crumb::current(section.title.clone())); - } - - bc.render(cx).await -} - -// **< Tareas locales >***************************************************************************** - -fn render_local_tasks(cx: &Context, current_path: &str) -> Markup { - let reg = registry::global(); - let tasks = reg.tasks_for(current_path); - if tasks.is_empty() { - return html! {}; - } - html! { - ul class="admin-tasks-list" { - @for task in tasks { - @let is_active = current_path == task.path; - li class=(if is_active { "admin-task admin-task-active" } else { "admin-task" }) { - a href=(cx.route(task.path.as_str())) { (task.title.using(cx)) } - } - } - } - } -} - -// **< Acciones locales >*************************************************************************** - -fn render_local_actions(cx: &Context, current_path: &str) -> Markup { - let reg = registry::global(); - let actions = reg.actions_for(current_path); - if actions.is_empty() { - return html! {}; - } - html! { - ul class="admin-actions-list" { - @for action in actions { - li class="admin-action" { - a class="admin-action-link" href=(cx.route(action.url.as_str())) { - (action.title.using(cx)) - } - } - } - } - } -} diff --git a/extensions/pagetop-admin/src/component/admin_menu.rs b/extensions/pagetop-admin/src/component/admin_menu.rs deleted file mode 100644 index 274abd74..00000000 --- a/extensions/pagetop-admin/src/component/admin_menu.rs +++ /dev/null @@ -1,38 +0,0 @@ -use pagetop::prelude::*; - -use crate::registry; - -/// Componente que renderiza la barra de navegación del panel de administración. -/// -/// Construye la [`Navbar`] en cada petición a partir de [`registry::admin_navbar()`], ya filtrada -/// por el usuario de la petición actual. Pensado para que un tema la registre en su propia región -/// de navegación e intercepte `Navbar`/`Nav`/`Dropdown` en -/// [`Theme::render_component()`](pagetop::core::theme::Theme::render_component) si quiere darle un -/// aspecto propio (p. ej. `pagetop-bootsier` la reconoce automáticamente al ser componentes del -/// núcleo); sin intercepción, se renderiza con el marcado por defecto de cada componente. -/// -/// Sólo se renderiza en páginas creadas con -/// [`Page::admin()`](pagetop::response::Page::admin) (plantilla -/// [`CoreTemplates::Admin`](pagetop::core::theme::CoreTemplates::Admin)). Es necesario comprobarlo -/// explícitamente porque, si se registra en una región de propósito general como -/// [`CoreRegions::Aside`](pagetop::core::theme::CoreRegions::Aside), se renderizaría también en -/// páginas `Standard` si no se autolimitara. -#[derive(AutoDefault, Clone, Debug)] -pub struct AdminMenu; - -#[async_trait] -impl Component for AdminMenu { - fn new() -> Self { - Self - } - - async fn prepare(&self, cx: &mut Context) -> Result { - if !matches!( - cx.template().downcast_ref::(), - Some(CoreTemplates::Admin) - ) { - return Ok(html! {}); - } - Ok(registry::admin_navbar(cx).render(cx).await) - } -} diff --git a/extensions/pagetop-admin/src/component/config_form.rs b/extensions/pagetop-admin/src/component/config_form.rs index 34f685b4..cc670a80 100644 --- a/extensions/pagetop-admin/src/component/config_form.rs +++ b/extensions/pagetop-admin/src/component/config_form.rs @@ -3,35 +3,27 @@ use pagetop::prelude::*; use crate::LOCALES_ADMIN; use crate::settings::{SettingFieldType, SettingsSchema, get_or}; -/// Componente que renderiza un formulario de configuración persistente. +/// Formulario de un [`SettingsSchema`], con los valores guardados en la tabla `settings`. /// -/// Genera campos HTML a partir de un [`SettingsSchema`] y carga los valores -/// actuales desde `settings`. El POST es procesado por el handler interno -/// `config_form_post`. +/// En las páginas declaradas con [`DeclareConfigForms`](crate::action::DeclareConfigForms), +/// `pagetop-admin` lo muestra y guarda lo que se envía. En una página propia sólo lo muestra: el +/// envío llega a la ruta de la página, o a la de [`with_action_path()`](Self::with_action_path), y +/// lo guarda su *handler* (ver [`settings::set()`](crate::settings::set)). /// /// # Ejemplo /// /// ```rust,no_run /// use pagetop::prelude::*; -/// use pagetop_admin::component::{AdminFrame, ConfigForm}; +/// use pagetop_admin::component::ConfigForm; /// use pagetop_admin::settings::{SettingField, SettingsSchema}; /// /// async fn settings_handler(request: HttpRequest) -> Result { /// let schema = SettingsSchema::new("myapp.general") -/// .with_field(SettingField::text("site_name", "Site name").with_required(true)); -/// -/// let title = "General settings"; -/// let mut form = ConfigForm::with_schema(schema); -/// let mut cx = Context::new(request.clone()); -/// let content = form.render(&mut cx).await; +/// .with_field(SettingField::text("site_name", Lc::n("Site name")).with_required(true)); /// /// Page::admin(request) -/// .with_title(Lc::n(title)) -/// .with_child( -/// AdminFrame::new() -/// .with_title(Lc::n(title)) -/// .with_child(Html::with(move |_| content.clone())), -/// ) +/// .with_title(Lc::n("General settings")) +/// .with_child(ConfigForm::with_schema(schema)) /// .render() /// .await /// } @@ -42,10 +34,6 @@ pub struct ConfigForm { schema: Option, /// Devuelve la ruta de destino del formulario, si se ha personalizado. action_path: Option, - /// Devuelve si el último envío se guardó correctamente. - saved: bool, - /// Devuelve si el último envío produjo un error al guardar. - error: bool, } #[async_trait] @@ -64,22 +52,11 @@ impl Component for ConfigForm { None => cx.route(cx.request().map(|r| r.path()).unwrap_or("/")), }; - let save_label = Lc::t("config-save-label", &LOCALES_ADMIN) - .lookup(cx) - .unwrap_or_else(|| "Save configuration".into()); - - let saved_msg = Lc::t("config-saved-ok", &LOCALES_ADMIN) - .lookup(cx) - .unwrap_or_else(|| "Configuration saved.".into()); - - let error_msg = Lc::t("config-saved-error", &LOCALES_ADMIN) - .lookup(cx) - .unwrap_or_else(|| "Could not save configuration.".into()); - - // Pre-computa los valores de BD para cada campo antes del macro html! (que es síncrono). + // Pre-computa los valores de BD para cada campo antes del macro html! (que es síncrono). El + // formulario guarda todos los valores como texto (`"42"`, `"true"`), así que se leen como + // texto también los de los campos numéricos y las casillas. struct FieldVals { raw_val: String, - num_val: String, checked: bool, } let mut prepared: Vec = Vec::with_capacity(schema.fields().len()); @@ -87,27 +64,18 @@ impl Component for ConfigForm { let key = schema.key_for(field.name()); let raw_val = get_or::(&key, field.default_value().cloned().unwrap_or_default()).await; - let num_val = get_or::(&key, 0.0).await.to_string(); - let checked = get_or::(&key, false).await; - prepared.push(FieldVals { - raw_val, - num_val, - checked, - }); + let checked = raw_val == "true"; + prepared.push(FieldVals { raw_val, checked }); } Ok(html! { - @if *self.saved() { - div class="admin-message admin-message-ok" { (&saved_msg) } - } - @if *self.error() { - div class="admin-message admin-message-error" { (&error_msg) } - } form class="admin-config-form" method="post" action=(action) { @for (i, field) in schema.fields().iter().enumerate() { @let pf = &prepared[i]; div class="admin-form-field" { - label class="admin-form-label" for=(field.name()) { (field.label()) } + label class="admin-form-label" for=(field.name()) { + (field.label().using(cx)) + } @match field.field_type() { SettingFieldType::Text { max_length } => { @if let Some(max) = max_length { @@ -133,7 +101,7 @@ impl Component for ConfigForm { type="number" id=(field.name()) name=(field.name()) - value=(&pf.num_val) + value=(&pf.raw_val) min=(lo) max=(hi) required[*field.required()]; @@ -142,7 +110,7 @@ impl Component for ConfigForm { type="number" id=(field.name()) name=(field.name()) - value=(&pf.num_val) + value=(&pf.raw_val) min=(lo) required[*field.required()]; } @else if let Some(hi) = max { @@ -150,7 +118,7 @@ impl Component for ConfigForm { type="number" id=(field.name()) name=(field.name()) - value=(&pf.num_val) + value=(&pf.raw_val) max=(hi) required[*field.required()]; } @else { @@ -158,7 +126,7 @@ impl Component for ConfigForm { type="number" id=(field.name()) name=(field.name()) - value=(&pf.num_val) + value=(&pf.raw_val) required[*field.required()]; } } @@ -178,22 +146,22 @@ impl Component for ConfigForm { { @for (val, label) in options { @if &pf.raw_val == val { - option value=(val) selected { (label) } + option value=(val) selected { (label.using(cx)) } } @else { - option value=(val) { (label) } + option value=(val) { (label.using(cx)) } } } } } } - @if let Some(help) = field.help_text() { - small class="admin-form-help" { (help) } + @if !field.help_text().is_none() { + small class="admin-form-help" { (field.help_text().using(cx)) } } } } div class="admin-form-actions" { button class="admin-btn admin-btn-primary" type="submit" { - (&save_label) + (Lc::t("config-save-label", &LOCALES_ADMIN).using(cx)) } } } @@ -212,17 +180,10 @@ impl ConfigForm { } } - pub fn with_action_path(mut self, v: impl Into>) -> Self { - if let Some(v) = v.into() { - self.action_path = Some(v); - } - self - } - - #[builder_skip] - pub(crate) fn with_saved(mut self, saved: bool, error: bool) -> Self { - self.saved = saved; - self.error = error; + /// Establece la ruta a la que se envía el formulario, o `None` para enviarlo a la de la + /// página. + pub fn with_action_path(mut self, path: impl Into>) -> Self { + self.action_path = path.into(); self } } diff --git a/extensions/pagetop-admin/src/handlers.rs b/extensions/pagetop-admin/src/handlers.rs index d197514f..ec57cf97 100644 --- a/extensions/pagetop-admin/src/handlers.rs +++ b/extensions/pagetop-admin/src/handlers.rs @@ -3,212 +3,128 @@ use std::collections::HashMap; use pagetop::prelude::*; use crate::LOCALES_ADMIN; -use crate::component::{AdminFrame, ConfigForm}; -use crate::registry::{self, AdminPageKind, AdminSection}; -use crate::settings; +use crate::action::config_forms; +use crate::component::ConfigForm; +use crate::settings::{self, SettingFieldType, SettingsSchema}; -// **< Dashboard >********************************************************************************** +// **< Config form >******************************************************************************** -/// GET /admin - Dashboard de administración: lista todas las secciones disponibles. -/// -/// Devuelve [`ErrorPage::AccessDenied`] si el usuario actual no tiene acceso a ninguna página. -pub async fn dashboard(request: HttpRequest) -> Result { - let cx = Context::new(request.clone()); - let sections = registry::global().ordered_sections(); - - let title = Lc::t("dashboard-title", &LOCALES_ADMIN); - let content = render_sections(&cx, §ions) - .ok_or_else(|| ErrorPage::AccessDenied(Some(request.clone())))?; - - Page::admin(request) - .with_title(title.clone()) - .with_child(AdminFrame::new().with_title(title).with_child(content)) - .render() - .await -} - -// **< Sección >************************************************************************************ - -/// GET /admin/{section} - Página de aterrizaje de una sección: lista sus páginas. -/// -/// Sólo se monta (ver `configure_router()` en `lib.rs`) para las secciones cuyo `path` no coincida -/// con ninguna [`AdminPage`](crate::registry::AdminPage) registrada explícitamente por una -/// extensión; si una extensión reclama esa ruta con su propia página, esa página gana y este -/// handler nunca llega a montarse para ella. -/// -/// Devuelve [`ErrorPage::AccessDenied`] si el usuario actual no tiene acceso a ninguna de sus -/// páginas. -pub async fn section_page(request: HttpRequest) -> Result { - let path = request.path().to_owned(); - let reg = registry::global(); - let section = reg - .sections() - .values() - .find(|s| s.path == path) - .ok_or_else(|| ErrorPage::NotFound(Some(request.clone())))?; - - let cx = Context::new(request.clone()); - let title = section.title.clone(); - let content = render_sections(&cx, &[section]) - .ok_or_else(|| ErrorPage::AccessDenied(Some(request.clone())))?; - - Page::admin(request) - .with_title(title.clone()) - .with_child(AdminFrame::new().with_title(title).with_child(content)) - .render() - .await -} - -// **< Render compartido >************************************************************************** - -// Rejilla de secciones con sus páginas (título + descripción). La usan tanto `dashboard()` (todas -// las secciones) como `section_page()` (una sola), filtrando siempre por permiso del usuario -// actual. Devuelve `None` si no queda ninguna sección visible con páginas accesibles. -fn render_sections(cx: &Context, candidates: &[&'static AdminSection]) -> Option { - let reg = registry::global(); - let sections_with_pages: Vec<_> = candidates - .iter() - .copied() - .map(|section| { - let pages: Vec<_> = reg - .pages_for_section(§ion.key) - .into_iter() - .filter(|p| p.is_accessible(cx)) - .collect(); - (section, pages) - }) - .filter(|(_, pages)| !pages.is_empty()) - .collect(); - if sections_with_pages.is_empty() { - return None; - } - let mut sections = Container::new().with_prop(PropsOp::add_classes("admin-dashboard-sections")); - for (section, pages) in sections_with_pages { - sections = sections.with_child( - Container::new() - .with_prop(PropsOp::add_classes("admin-dashboard-section")) - .with_child(Html::with(move |cx| { - html! { - h2 class="admin-dashboard-section-title" { - a href=(cx.route(section.path.as_str())) { (section.title.using(cx)) } - } - ul class="admin-dashboard-section-links" { - @for page in &pages { - li class="admin-dashboard-link" { - a href=(cx.route(page.path.as_str())) { - (page.title.using(cx)) - } - @if let Some(description) = &page.description { - span class="admin-dashboard-link-desc" { - " - " (description.using(cx)) - } - } - } - } - } - } - })), - ); - } - Some(sections) +// Página del registro y esquema de la página de ajustes de la petición. +fn config_form_page( + request: &HttpRequest, +) -> Result<(&'static AdminPage, &'static SettingsSchema), ErrorPage> { + let not_found = || ErrorPage::NotFound(Some(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)?; + Ok((page, schema)) } // **< Config form - GET >************************************************************************** -/// GET de una página [`AdminPageKind::ConfigForm`]. -/// -/// Lee el schema del registro y renderiza el formulario con los valores actuales. +// GET de una página de ajustes: el formulario con los valores guardados. pub async fn config_form_get(request: HttpRequest) -> Result { - let path = request.path().to_owned(); - let reg = registry::global(); - let page = reg - .pages() - .get(&path) - .ok_or_else(|| ErrorPage::NotFound(Some(request.clone())))?; - - let AdminPageKind::ConfigForm(ref schema) = page.kind else { - return Err(ErrorPage::NotFound(Some(request.clone()))); - }; - - require_permission(&request, page.permission)?; - - let title = page.title.clone(); - let mut form = ConfigForm::with_schema(schema.clone()); - let mut cx = Context::new(request.clone()); - let content = form.render(&mut cx).await; + let (page, schema) = config_form_page(&request)?; Page::admin(request) - .with_title(title.clone()) - .with_child( - AdminFrame::new() - .with_title(title) - .with_child(Html::with(move |_| content.clone())), - ) + .with_title(page.title().clone()) + .with_child(ConfigForm::with_schema(schema.clone())) .render() .await } // **< Config form - POST >************************************************************************* -/// POST de una página [`AdminPageKind::ConfigForm`]. -/// -/// Valida y persiste los valores en `settings`, luego redirige al GET con -/// estado `saved=true`. +// POST de una página de ajustes: guarda los valores enviados y vuelve a mostrar el formulario con +// un mensaje. Si falta algún campo obligatorio no guarda ninguno. pub async fn config_form_post( request: HttpRequest, web::Form(data): web::Form>, ) -> Result { - let path = request.path().to_owned(); - let reg = registry::global(); - let page = reg - .pages() - .get(&path) - .ok_or_else(|| ErrorPage::NotFound(Some(request.clone())))?; + let (page, schema) = config_form_page(&request)?; + let mut admin = Page::admin(request).with_title(page.title().clone()); - let AdminPageKind::ConfigForm(ref schema) = page.kind else { - return Err(ErrorPage::NotFound(Some(request.clone()))); - }; - - require_permission(&request, page.permission)?; - - let mut save_error = false; - - for field in schema.fields() { - let key = schema.key_for(field.name()); - - // Los checkbox HTML sólo envían el campo si están marcados. - let raw = match field.field_type() { - crate::settings::SettingFieldType::Boolean => data - .get(field.name()) - .map(|s| s.as_str()) - .unwrap_or("false") - .to_owned(), - _ => { - let Some(raw) = data.get(field.name()) else { - if *field.required() { - save_error = true; - } - continue; - }; - raw.clone() + let (level, message) = match submitted_values(schema, &data) { + None => (MessageLevel::Error, "config-required"), + Some(values) => { + let user_id = admin.current_user().id(); + let mut saved = true; + for (key, value) in values { + if let Err(error) = settings::set(&key, &value, schema.scope(), user_id).await { + trace::error!("Failed to save the setting \"{key}\": {error}"); + saved = false; + break; + } } - }; + if saved { + (MessageLevel::Info, "config-saved-ok") + } else { + (MessageLevel::Error, "config-saved-error") + } + } + }; + admin.push_message(level, Lc::t(message, &LOCALES_ADMIN)); - settings::set::(&key, &raw, schema.scope(), None).await; - } - - let title = page.title.clone(); - let mut form = ConfigForm::with_schema(schema.clone()).with_saved(!save_error, save_error); - let mut cx = Context::new(request.clone()); - let content = form.render(&mut cx).await; - - Page::admin(request) - .with_title(title.clone()) - .with_child( - AdminFrame::new() - .with_title(title) - .with_child(Html::with(move |_| content.clone())), - ) + admin + .with_child(ConfigForm::with_schema(schema.clone())) .render() .await } + +// Clave y valor de cada campo del esquema en el envío, o `None` si falta un campo obligatorio o +// llega vacío. Una casilla sin marcar no se envía, así que vale `"false"`. +fn submitted_values( + schema: &SettingsSchema, + data: &HashMap, +) -> Option> { + let mut values = Vec::with_capacity(schema.fields().len()); + for field in schema.fields() { + let value = match (field.field_type(), data.get(field.name())) { + (SettingFieldType::Boolean, value) => value.map_or("false", String::as_str), + (_, Some(value)) if !value.trim().is_empty() => value, + (_, _) if *field.required() => return None, + (_, value) => value.map_or("", String::as_str), + }; + values.push((schema.key_for(field.name()), value.to_owned())); + } + Some(values) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::settings::SettingField; + + fn schema() -> SettingsSchema { + SettingsSchema::new("garden") + .with_field(SettingField::text("name", Lc::n("Name")).with_required(true)) + .with_field(SettingField::text("notice", Lc::n("Notice"))) + .with_field(SettingField::boolean("open", Lc::n("Open"))) + } + + fn data(pairs: &[(&str, &str)]) -> HashMap { + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() + } + + #[pagetop::test] + async fn values_are_keyed_by_scope_and_an_unchecked_box_is_false() { + let values = submitted_values(&schema(), &data(&[("name", "Ours"), ("notice", "")])); + assert_eq!( + values.unwrap(), + [ + ("garden.name".to_owned(), "Ours".to_owned()), + ("garden.notice".to_owned(), String::new()), + ("garden.open".to_owned(), "false".to_owned()), + ] + ); + } + + #[pagetop::test] + async fn a_required_field_missing_or_blank_saves_nothing() { + assert!(submitted_values(&schema(), &data(&[("notice", "Hi")])).is_none()); + assert!(submitted_values(&schema(), &data(&[("name", " ")])).is_none()); + } +} diff --git a/extensions/pagetop-admin/src/lib.rs b/extensions/pagetop-admin/src/lib.rs index 1066b25a..c08c4dc5 100644 --- a/extensions/pagetop-admin/src/lib.rs +++ b/extensions/pagetop-admin/src/lib.rs @@ -3,7 +3,7 @@

PageTop Admin

-

Panel de administración extensible para PageTop.

+

Ajustes guardados en la base de datos para el panel de administración de PageTop.

[![Doc API](https://img.shields.io/docsrs/pagetop-admin?label=Doc%20API&style=for-the-badge&logo=Docs.rs)](https://docs.rs/pagetop-admin) [![Crates.io](https://img.shields.io/crates/v/pagetop-admin.svg?style=for-the-badge&logo=ipfs)](https://crates.io/crates/pagetop-admin) @@ -12,11 +12,8 @@ -Añade a una aplicación PageTop un panel de administración en `/admin` que cada extensión amplía con -sus propias secciones, páginas, pestañas y botones, declarados con acciones. Trae las secciones -habituales (personas, estructura, configuración, informes y ayuda), formularios de configuración -que se guardan en la base de datos y un menú de navegación hecho sólo con componentes del núcleo, -para que funcione con cualquier tema. +Añade al panel de administración de PageTop **ajustes que se guardan en la base de datos** y que un +administrador cambia desde el propio panel, con la aplicación en marcha. ## Sobre PageTop @@ -24,6 +21,36 @@ para que funcione con cualquier tema. clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y configurables, basadas en HTML, CSS y JavaScript. +## Qué aporta + +- **Páginas de ajustes sin código propio.** Una extensión describe los campos con un + [`SettingsSchema`] y declara la página con [`DeclareConfigForms`]. `pagetop-admin` monta su ruta, + pinta el formulario con los valores guardados y guarda lo que se envía, salvo que falte algún + campo obligatorio o llegue vacío. +- **El almacén de los valores.** La tabla `settings`, que crea al arrancar, y las funciones del + módulo [`settings`](mod@settings) para leerlos ([`settings::get_or()`] y compañía) y + escribirlos desde código. +- **El formulario** ([`ConfigForm`]), por si una página propia quiere mostrar el de un esquema. + +## En qué se apoya + +El panel en sí es de PageTop (el módulo [`pagetop::admin`]): su página de inicio, sus secciones, la +navegación, las migas de pan y la plantilla de administración ([`Page::admin()`]). Cada página de +ajustes es una [`AdminPage`] del núcleo, así que aparece en el panel como cualquier otra, con su +sección y su permiso, y se pinta con cualquier tema. Una extensión que sólo añade páginas propias al +panel, sin ajustes, no necesita `pagetop-admin`. + +## Cuándo usarlo + +Para valores que decide quien administra el sitio y que cambian con el tiempo: un aviso en la +portada, un número de plazas, abrir o cerrar las inscripciones... Lo que fija quien despliega la +aplicación (la base de datos, el servidor de correo, los límites) va en los archivos de +configuración (ver [`pagetop::config`]), que no se pueden cambiar desde el panel y exigen +reiniciar. + +Los valores que envía el formulario se guardan como texto, también los de los campos numéricos y las +casillas (`"42"`, `"true"`): se leen como `String` y se convierten al usarlos. + ## Guía rápida **Añade la dependencia** a tu `Cargo.toml`: @@ -33,16 +60,15 @@ configurables, basadas en HTML, CSS y JavaScript. pagetop-admin = "..." ``` -La configuración se guarda con `pagetop-seaorm`: la aplicación elige el motor de base de datos con -su *feature* (`postgres`, `mysql` o `sqlite`) y configura la conexión en la sección `[database]`. +Los ajustes se guardan con `pagetop-seaorm`: la aplicación elige el motor de base de datos con su +*feature* (`postgres`, `mysql` o `sqlite`) y configura la conexión en la sección `[database]`. -**Declara la extensión** como dependencia de la tuya (`&pagetop_admin::Admin`) y **añade al panel** -tus secciones, páginas o formularios de configuración: +**Declara la extensión** como dependencia de la tuya (`&pagetop_admin::Admin`); si no, sus páginas +de ajustes no se montan. Después **declara tus páginas de ajustes**, cada una con su permiso: ```rust,no_run use pagetop::prelude::*; use pagetop_admin::prelude::*; -use pagetop_admin::settings::{SettingField, SettingsSchema}; pub struct MyApp; @@ -53,25 +79,17 @@ impl Extension for MyApp { } fn actions(&self) -> Vec { - actions![ - DeclareAdminPages::new(declare_pages), - ] - } - - fn configure_router(&self, router: Router) -> Router { - router.route("/admin/config/myapp", web::get(config_handler)) + actions![DeclareConfigForms::new(declare_forms)] } } -fn declare_pages(bag: &mut PageBag) { - bag.add(AdminPage { - path: "/admin/config/myapp".to_owned(), - section: "config".to_owned(), - title: Lc::n("My App"), - description: Some(Lc::n("Configure My App.")), - weight: 0, - permission: &MyPermission::Config, - kind: AdminPageKind::View, +fn declare_forms(bag: &mut ConfigFormBag) { + bag.add(ConfigFormPage { + page: AdminPage::new("config/myapp", "config", Lc::n("My App"), &MyPermission::Config) + .with_description(Lc::n("Name of the site.")), + schema: SettingsSchema::new("myapp").with_field( + SettingField::text("site_name", Lc::n("Site name")).with_required(true), + ), }); } @@ -88,30 +106,11 @@ impl Permission for MyPermission { } } -async fn config_handler(request: HttpRequest) -> Result { - let schema = SettingsSchema::new("myapp.config") - .with_field(SettingField::text("site_name", "Site name").with_required(true)); - - let title = "My App configuration"; - let mut form = ConfigForm::with_schema(schema); - let mut cx = Context::new(request.clone()); - let content = form.render(&mut cx).await; - - Page::admin(request) - .with_title(Lc::n(title)) - .with_child( - AdminFrame::new() - .with_title(Lc::n(title)) - .with_child(Html::with(move |_| content.clone())), - ) - .render() - .await +// Los valores se guardan con la clave `<ámbito>.`. +async fn site_name() -> String { + pagetop_admin::settings::get_or("myapp.site_name", String::new()).await } ``` - -Para formularios de configuración enteramente automáticos (GET y POST gestionados por -`pagetop-admin`), usa `AdminPageKind::ConfigForm(schema)` en lugar de `View` y no registres la ruta -tú mismo. */ use pagetop::prelude::*; @@ -119,39 +118,24 @@ use pagetop_seaorm::install_migrations; include_locales!(LOCALES_ADMIN); -/// Ruta raíz del panel de administración. No es configurable: otras piezas del ecosistema (p. ej. -/// las rutas de `pagetop-user`, `/admin/user/...`) ya asumen este valor de forma literal. Es -/// pública para que otras extensiones enlacen al panel sin repetir la ruta. -pub const ADMIN_BASE_PATH: &str = "/admin"; - pub mod action; pub mod component; pub mod error; -pub mod registry; pub mod settings; pub(crate) mod entity; pub(crate) mod handlers; pub(crate) mod migration; -pub(crate) mod seed; -pub use action::{ - ActionBag, DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks, - PageBag, SectionBag, TaskBag, -}; -pub use component::{AdminFrame, AdminMenu, ConfigForm}; -pub use registry::{AdminAction, AdminPage, AdminPageKind, AdminSection, AdminTask}; +pub use action::{ConfigFormBag, ConfigFormPage, DeclareConfigForms}; +pub use component::ConfigForm; pub use settings::{SettingField, SettingFieldType, SettingsSchema}; /// Prelude de `pagetop-admin`. pub mod prelude { - pub use crate::action::{ - ActionBag, DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks, - PageBag, SectionBag, TaskBag, - }; - pub use crate::component::{AdminFrame, AdminMenu, ConfigForm}; + pub use crate::action::{ConfigFormBag, ConfigFormPage, DeclareConfigForms}; + pub use crate::component::ConfigForm; pub use crate::error::AdminError; - pub use crate::registry::{AdminAction, AdminPage, AdminPageKind, AdminSection, AdminTask}; pub use crate::settings::{SettingField, SettingFieldType, SettingsSchema}; } @@ -175,42 +159,22 @@ impl Extension for Admin { } fn actions(&self) -> Vec { - actions![action::DeclareAdminSections::new(seed::declare_default_sections).with_weight(-99),] + actions![pagetop::base::action::admin::DeclareAdminPages::new( + action::declare_config_form_pages + )] } async fn initialize(&self) -> Result<(), BoxError> { install_migrations!(m20260629_000001_create_settings)?; - registry::build(); - - // Región neutra del core: cualquier tema puede decidir renderizarla (o no) sin que - // `pagetop-admin` dependa de ninguno en concreto (ver `CoreRegions::Aside`). - InRegion::Global(&CoreRegions::Aside).add(component::AdminMenu::new()); Ok(()) } - fn configure_router(&self, router: Router) -> Router { - let base = ADMIN_BASE_PATH; - let reg = registry::global(); - - let mut r = router.route(base, web::get(handlers::dashboard)); - - // Página de aterrizaje de cada sección, salvo que una extensión ya haya reclamado esa - // misma ruta con su propia `AdminPage` (esa página gana y se monta más abajo). - for section in reg.sections().values() { - if !reg.pages().contains_key(§ion.path) { - r = r.route(section.path.as_str(), web::get(handlers::section_page)); - } - } - - for (path, page) in reg.pages() { - if let AdminPageKind::ConfigForm(_) = &page.kind { - r = r.route( - path.as_str(), - web::get(handlers::config_form_get).post(handlers::config_form_post), - ); - } - } - - r + fn configure_router(&self, routes: Routes) -> Routes { + action::config_forms().keys().fold(routes, |routes, path| { + routes.admin_route( + path, + web::get(handlers::config_form_get).post(handlers::config_form_post), + ) + }) } } diff --git a/extensions/pagetop-admin/src/locale/en-US/common.ftl b/extensions/pagetop-admin/src/locale/en-US/common.ftl index 31e38061..1bc4b2a3 100644 --- a/extensions/pagetop-admin/src/locale/en-US/common.ftl +++ b/extensions/pagetop-admin/src/locale/en-US/common.ftl @@ -1,21 +1,8 @@ extension_name = PageTop Admin -extension_description = Extensible administration panel for PageTop. - -# Dashboard -dashboard-title = Administration -dashboard-description = Manage your site. - -# Sections -section-people = People -section-structure = Structure -section-config = Configuration -section-reports = Reports -section-help = Help +extension_description = Settings stored in the database for the PageTop administration panel. # Config form config-save-label = Save configuration config-saved-ok = Configuration saved. config-saved-error = Could not save configuration. - -# Navigation -admin-breadcrumb-home = Administration +config-required = Fill in the required fields. Nothing was saved. diff --git a/extensions/pagetop-admin/src/locale/es-ES/common.ftl b/extensions/pagetop-admin/src/locale/es-ES/common.ftl index aa3b3eda..3f0d3293 100644 --- a/extensions/pagetop-admin/src/locale/es-ES/common.ftl +++ b/extensions/pagetop-admin/src/locale/es-ES/common.ftl @@ -1,21 +1,8 @@ extension_name = PageTop Admin -extension_description = Panel de administración extensible para PageTop. - -# Dashboard -dashboard-title = Administración -dashboard-description = Gestiona tu sitio. - -# Sections -section-people = Personas -section-structure = Estructura -section-config = Configuración -section-reports = Informes -section-help = Ayuda +extension_description = Ajustes guardados en la base de datos para el panel de administración de PageTop. # Config form config-save-label = Guardar configuración config-saved-ok = Configuración guardada. config-saved-error = No se pudo guardar la configuración. - -# Navigation -admin-breadcrumb-home = Administración +config-required = Rellena los campos obligatorios. No se ha guardado nada. diff --git a/extensions/pagetop-admin/src/registry.rs b/extensions/pagetop-admin/src/registry.rs deleted file mode 100644 index 586cfc45..00000000 --- a/extensions/pagetop-admin/src/registry.rs +++ /dev/null @@ -1,279 +0,0 @@ -//! Registro global de secciones, páginas, tareas y acciones del panel de administración. -//! -//! Se construye una única vez durante `Extension::initialize()` y permanece -//! inmutable durante la vida de la aplicación. - -use std::collections::BTreeMap; -use std::sync::OnceLock; - -use pagetop::prelude::*; - -use crate::action::{ - ActionBag, DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks, - PageBag, SectionBag, TaskBag, -}; -use crate::settings::SettingsSchema; - -// **< Tipos del registro >************************************************************************* - -/// Sección del panel de administración (agrupación de páginas en el menú y en el *dashboard*). -/// -/// Una sección no tiene permiso propio: se muestra a quien pueda acceder a alguna de sus páginas, y -/// se oculta si no le queda ninguna. -#[derive(Clone)] -pub struct AdminSection { - /// Identificador único de la sección (p. ej. `"config"`). - pub key: String, - /// Ruta base de la sección (p. ej. `"/admin/config"`). - pub path: String, - /// Título visible en el sidebar. - pub title: Lc, - /// Peso para ordenar en el sidebar (menor = antes). - pub weight: i32, -} - -/// Página del panel de administración. -#[derive(Clone)] -pub struct AdminPage { - /// Ruta exacta de la página (p. ej. `"/admin/config/site"`). - pub path: String, - /// Clave de la sección a la que pertenece. - pub section: String, - /// Título visible en el sidebar y encabezado de página. - pub title: Lc, - /// Descripción breve (para el dashboard y listas de páginas), si tiene una. - pub description: Option, - /// Peso dentro de la sección (menor = antes). - pub weight: i32, - /// Permiso requerido para acceder. Es obligatorio: cada página declara el suyo, y es también - /// el que decide si su sección se muestra. - pub permission: PermissionRef, - /// Tipo de página y datos asociados. - pub kind: AdminPageKind, -} - -impl AdminPage { - /// Devuelve `true` si el usuario actual puede acceder a esta página. - pub fn is_accessible(&self, cx: &Context) -> bool { - cx.request() - .is_some_and(|request| has_permission(request, self.permission)) - } -} - -/// Variantes de comportamiento de una [`AdminPage`]. -#[derive(Clone, Debug)] -pub enum AdminPageKind { - /// Página genérica cuyo handler se registra externamente. - View, - /// Formulario de configuración gestionado automáticamente por `pagetop-admin`. - ConfigForm(SettingsSchema), -} - -/// Tarea (pestaña) local dentro de una página de administración. -#[derive(Clone)] -pub struct AdminTask { - /// Ruta de la tarea. - pub path: String, - /// Ruta de la página padre. - pub parent_path: String, - /// Etiqueta de la pestaña. - pub title: Lc, - /// Peso (menor = primera pestaña). - pub weight: i32, - /// Si es la tarea por defecto (pestaña activa al entrar a la página padre). - pub is_default: bool, - /// Permiso requerido (`None` = mismo que la página padre). - pub permission: Option, -} - -/// Acción local (botón de acción) en una página de administración. -#[derive(Clone, Debug)] -pub struct AdminAction { - /// Ruta de destino de la acción. - pub url: String, - /// Página en la que aparece el botón. - pub for_path: String, - /// Etiqueta del botón. - pub title: Lc, - /// Peso (menor = primero). - pub weight: i32, -} - -// **< AdminRegistry >****************************************************************************** - -/// Registro global del panel de administración, construido una sola vez en `initialize()`. -#[derive(Getters)] -pub struct AdminRegistry { - /// Devuelve las secciones indexadas por clave (`BTreeMap` para orden estable por clave). - sections: BTreeMap, - /// Devuelve las páginas indexadas por ruta. - pages: BTreeMap, - /// Devuelve las tareas indexadas por ruta de página padre. - tasks: BTreeMap>, - /// Devuelve las acciones indexadas por ruta de página. - actions: BTreeMap>, -} - -impl AdminRegistry { - fn new() -> Self { - AdminRegistry { - sections: BTreeMap::new(), - pages: BTreeMap::new(), - tasks: BTreeMap::new(), - actions: BTreeMap::new(), - } - } - - /// Devuelve las páginas de una sección ordenadas por peso. - pub fn pages_for_section(&self, section_key: &str) -> Vec<&AdminPage> { - let mut pages: Vec<&AdminPage> = self - .pages - .values() - .filter(|p| p.section == section_key) - .collect(); - pages.sort_by_key(|p| p.weight); - pages - } - - /// Devuelve las secciones ordenadas por peso. - pub fn ordered_sections(&self) -> Vec<&AdminSection> { - let mut sections: Vec<&AdminSection> = self.sections.values().collect(); - sections.sort_by_key(|s| s.weight); - sections - } - - /// Devuelve las tareas de una página ordenadas por peso. - pub fn tasks_for(&self, path: &str) -> Vec<&AdminTask> { - let Some(tasks) = self.tasks.get(path) else { - return vec![]; - }; - let mut t: Vec<&AdminTask> = tasks.iter().collect(); - t.sort_by_key(|t| t.weight); - t - } - - /// Devuelve las acciones de una página ordenadas por peso. - pub fn actions_for(&self, path: &str) -> Vec<&AdminAction> { - let Some(actions) = self.actions.get(path) else { - return vec![]; - }; - let mut a: Vec<&AdminAction> = actions.iter().collect(); - a.sort_by_key(|a| a.weight); - a - } -} - -// **< Registro global >**************************************************************************** - -static REGISTRY: OnceLock = OnceLock::new(); - -/// Construye el registro despachando todas las acciones de declaración. -/// -/// Se llama una sola vez desde `Admin::initialize()`. -pub(crate) fn build() { - let mut registry = AdminRegistry::new(); - - // Secciones - let mut section_bag = SectionBag { - sections: Vec::new(), - }; - DeclareAdminSections::dispatch(&mut section_bag); - for s in section_bag.sections { - registry.sections.insert(s.key.clone(), s); - } - - // Páginas - let mut page_bag = PageBag { pages: Vec::new() }; - DeclareAdminPages::dispatch(&mut page_bag); - for p in page_bag.pages { - registry.pages.insert(p.path.clone(), p); - } - - // Tareas - let mut task_bag = TaskBag { tasks: Vec::new() }; - DeclareAdminTasks::dispatch(&mut task_bag); - for t in task_bag.tasks { - registry - .tasks - .entry(t.parent_path.clone()) - .or_default() - .push(t); - } - - // Acciones locales - let mut action_bag = ActionBag { - actions: Vec::new(), - }; - DeclareAdminActions::dispatch(&mut action_bag); - for a in action_bag.actions { - registry - .actions - .entry(a.for_path.clone()) - .or_default() - .push(a); - } - - REGISTRY.set(registry).ok(); -} - -/// Accede al registro global del panel de administración. -/// -/// # Panics -/// -/// Entra en pánico si se llama antes de que `Admin::initialize()` haya completado. -pub fn global() -> &'static AdminRegistry { - REGISTRY.get().expect("AdminRegistry not initialized") -} - -/// Devuelve `true` si el usuario de la petición actual tiene acceso a alguna página del panel, es -/// decir, si `/admin` no le devolvería un acceso denegado. -/// -/// Permite a otras extensiones (p. ej. el menú de cuenta de `pagetop-user`) ofrecer el enlace a -/// la administración sólo cuando procede. -pub fn can_access_admin(cx: &Context) -> bool { - let reg = global(); - reg.ordered_sections().into_iter().any(|section| { - reg.pages_for_section(§ion.key) - .into_iter() - .any(|page| page.is_accessible(cx)) - }) -} - -// **< Menú de administración >********************************************************************* - -/// Construye la barra de navegación de administración para el usuario de la petición actual: un -/// enlace al *dashboard* seguido de un desplegable por sección visible, con sus páginas accesibles -/// dentro. -/// -/// Pensado para que un tema la use como navegación de `CoreTemplates::Admin` -- ver -/// [`crate::component::AdminMenu`]. `pagetop-admin` no impone ningún marcado propio: la -/// [`Navbar`] resultante se renderiza con su aspecto por defecto salvo que el tema lo intercepte -/// en [`Theme::render_component()`](pagetop::core::theme::Theme::render_component). Se construye -/// enteramente con componentes del núcleo (`Navbar`/`Nav`/`Dropdown`), sin depender de ningún -/// tema concreto. -pub fn admin_navbar(cx: &Context) -> Navbar { - let reg = global(); - - let mut nav = Nav::new().with_item(nav::Item::link( - Lc::t("dashboard-title", &crate::LOCALES_ADMIN), - crate::ADMIN_BASE_PATH, - )); - - for section in reg.ordered_sections() { - let pages: Vec<_> = reg - .pages_for_section(§ion.key) - .into_iter() - .filter(|p| p.is_accessible(cx)) - .collect(); - if pages.is_empty() { - continue; - } - let mut menu = Dropdown::new().with_title(section.title.clone()); - for page in pages { - menu = menu.with_item(dropdown::Item::link(page.title.clone(), page.path.clone())); - } - nav = nav.with_item(nav::Item::dropdown(menu)); - } - - Navbar::simple().with_item(navbar::Item::nav(nav)) -} diff --git a/extensions/pagetop-admin/src/seed.rs b/extensions/pagetop-admin/src/seed.rs deleted file mode 100644 index b0fea446..00000000 --- a/extensions/pagetop-admin/src/seed.rs +++ /dev/null @@ -1,45 +0,0 @@ -use pagetop::prelude::*; - -use crate::ADMIN_BASE_PATH; -use crate::LOCALES_ADMIN; -use crate::action::SectionBag; -use crate::registry::AdminSection; - -/// Declara las secciones incorporadas del panel de administración. -/// -/// Se registra en `Admin::actions()` como `DeclareAdminSections::new(declare_default_sections)` -/// con peso negativo para ejecutarse antes que las extensiones de terceros. -pub(crate) fn declare_default_sections(bag: &mut SectionBag) { - let base = ADMIN_BASE_PATH; - - bag.add(AdminSection { - key: "people".to_owned(), - path: format!("{}/people", base), - title: Lc::t("section-people", &LOCALES_ADMIN), - weight: 10, - }); - bag.add(AdminSection { - key: "structure".to_owned(), - path: format!("{}/structure", base), - title: Lc::t("section-structure", &LOCALES_ADMIN), - weight: 20, - }); - bag.add(AdminSection { - key: "config".to_owned(), - path: format!("{}/config", base), - title: Lc::t("section-config", &LOCALES_ADMIN), - weight: 30, - }); - bag.add(AdminSection { - key: "reports".to_owned(), - path: format!("{}/reports", base), - title: Lc::t("section-reports", &LOCALES_ADMIN), - weight: 40, - }); - bag.add(AdminSection { - key: "help".to_owned(), - path: format!("{}/help", base), - title: Lc::t("section-help", &LOCALES_ADMIN), - weight: 50, - }); -} diff --git a/extensions/pagetop-admin/src/settings.rs b/extensions/pagetop-admin/src/settings.rs index d145709d..b7ee7f9a 100644 --- a/extensions/pagetop-admin/src/settings.rs +++ b/extensions/pagetop-admin/src/settings.rs @@ -25,32 +25,9 @@ pub async fn get_or(key: &str, default: T) -> T { /// Escribe un valor en la tabla `settings`. /// -/// Si la clave no existe se inserta; si existe, se actualiza. -pub async fn set(key: &str, value: &T, scope: &str, user_id: Option) { - set_async(key, value, scope, user_id).await.ok(); -} - -/// Elimina una entrada de `settings` por clave. -pub async fn delete(key: &str) { - delete_async(key).await.ok(); -} - -/// Devuelve todos los pares `(key, value_json)` de un `scope` dado. -pub async fn list_scope(scope: &str) -> Vec<(String, String)> { - list_scope_async(scope).await.unwrap_or_default() -} - -// **< Implementación asíncrona >******************************************************************* - -async fn get_async(key: &str) -> Result { - let model = Entity::find_by_id(key) - .one(dbconn()) - .await? - .ok_or_else(|| AdminError::NotFound(key.to_owned()))?; - Ok(serde_json::from_str(&model.value)?) -} - -async fn set_async( +/// Si la clave no existe se inserta; si existe, se actualiza. Devuelve el error si no se puede +/// guardar. +pub async fn set( key: &str, value: &T, scope: &str, @@ -82,11 +59,27 @@ async fn set_async( Ok(()) } -async fn delete_async(key: &str) -> Result<(), AdminError> { +/// Elimina una entrada de `settings` por clave. Devuelve el error si no se puede eliminar. +pub async fn delete(key: &str) -> Result<(), AdminError> { Entity::delete_by_id(key).exec(dbconn()).await?; Ok(()) } +/// Devuelve todos los pares `(key, value_json)` de un `scope` dado. +pub async fn list_scope(scope: &str) -> Vec<(String, String)> { + list_scope_async(scope).await.unwrap_or_default() +} + +// **< Implementación asíncrona >******************************************************************* + +async fn get_async(key: &str) -> Result { + let model = Entity::find_by_id(key) + .one(dbconn()) + .await? + .ok_or_else(|| AdminError::NotFound(key.to_owned()))?; + Ok(serde_json::from_str(&model.value)?) +} + async fn list_scope_async(scope: &str) -> Result, AdminError> { let rows = Entity::find() .filter(Column::Scope.eq(scope)) @@ -107,7 +100,7 @@ pub enum SettingFieldType { /// Casilla de verificación (booleano). Boolean, /// Lista de opciones `(valor, etiqueta)`. - Select { options: Vec<(String, String)> }, + Select { options: Vec<(String, Lc)> }, } /// Definición de un campo dentro de un [`SettingsSchema`]. @@ -116,70 +109,66 @@ pub struct SettingField { /// Devuelve el nombre del campo (clave dentro del scope, p. ej. `"site_name"`). name: String, /// Devuelve la etiqueta visible en el formulario. - label: String, + label: Lc, /// Devuelve el tipo de campo. field_type: SettingFieldType, /// Devuelve si el campo es obligatorio. required: bool, - /// Devuelve el texto de ayuda opcional bajo el campo. - help_text: Option, - /// Devuelve el valor por defecto como cadena JSON. + /// Devuelve el texto de ayuda bajo el campo, o [`Lc::none()`] si no tiene. + help_text: Lc, + /// Devuelve el valor por defecto, como texto, igual que guarda el formulario los valores. default_value: Option, } #[builder_impl] impl SettingField { /// Crea un campo de texto con nombre y etiqueta. - pub fn text(name: impl Into, label: impl Into) -> Self { + pub fn text(name: impl Into, label: Lc) -> Self { SettingField { name: name.into(), - label: label.into(), + label, field_type: SettingFieldType::Text { max_length: None }, required: false, - help_text: None, + help_text: Lc::none(), default_value: None, } } /// Crea un campo numérico con nombre y etiqueta. - pub fn number(name: impl Into, label: impl Into) -> Self { + pub fn number(name: impl Into, label: Lc) -> Self { SettingField { name: name.into(), - label: label.into(), + label, field_type: SettingFieldType::Number { min: None, max: None, }, required: false, - help_text: None, + help_text: Lc::none(), default_value: None, } } /// Crea un campo booleano con nombre y etiqueta. - pub fn boolean(name: impl Into, label: impl Into) -> Self { + pub fn boolean(name: impl Into, label: Lc) -> Self { SettingField { name: name.into(), - label: label.into(), + label, field_type: SettingFieldType::Boolean, required: false, - help_text: None, + help_text: Lc::none(), default_value: None, } } /// Crea un campo de selección con nombre, etiqueta y opciones. - pub fn select( - name: impl Into, - label: impl Into, - options: Vec<(String, String)>, - ) -> Self { + pub fn select(name: impl Into, label: Lc, options: Vec<(String, Lc)>) -> Self { SettingField { name: name.into(), - label: label.into(), + label, field_type: SettingFieldType::Select { options }, required: false, - help_text: None, + help_text: Lc::none(), default_value: None, } } @@ -191,14 +180,20 @@ impl SettingField { } /// Añade texto de ayuda bajo el campo. - pub fn with_help(mut self, text: impl Into) -> Self { - self.help_text = Some(text.into()); + pub fn with_help(mut self, text: Lc) -> Self { + self.help_text = text; self } - /// Establece el valor por defecto (como valor JSON serializado). + /// Establece el valor por defecto, el que muestra el formulario mientras no se guarde otro. + /// + /// Se guarda como texto, igual que los valores que envía el formulario: un número o un + /// booleano, con su forma habitual (`42`, `true`), y una cadena, tal cual, sin comillas. pub fn with_default(mut self, value: &T) -> Self { - self.default_value = serde_json::to_string(value).ok(); + self.default_value = serde_json::to_value(value).ok().map(|value| match value { + serde_json::Value::String(text) => text, + other => other.to_string(), + }); self } } diff --git a/extensions/pagetop-admin/tests/settings.rs b/extensions/pagetop-admin/tests/settings.rs new file mode 100644 index 00000000..6f034c15 --- /dev/null +++ b/extensions/pagetop-admin/tests/settings.rs @@ -0,0 +1,23 @@ +use pagetop::prelude::*; +use pagetop_admin::prelude::*; + +// The form saves every value as text, so the defaults are kept the same way. +#[pagetop::test] +async fn defaults_are_kept_as_the_form_saves_values() { + let default = |field: SettingField| field.default_value().cloned(); + let text = SettingField::text("notice", Lc::n("Notice")).with_default(&"Closed today"); + let number = SettingField::number("plots", Lc::n("Plots")).with_default(&42); + let boolean = SettingField::boolean("open", Lc::n("Open")).with_default(&true); + + assert_eq!(default(text).as_deref(), Some("Closed today")); + assert_eq!(default(number).as_deref(), Some("42")); + assert_eq!(default(boolean).as_deref(), Some("true")); +} + +#[pagetop::test] +async fn a_field_without_help_has_none() { + let field = SettingField::text("notice", Lc::n("Notice")); + assert!(field.help_text().is_none()); + let field = field.with_help(Lc::n("Shown on the home page.")); + assert!(!field.help_text().is_none()); +} diff --git a/extensions/pagetop-aliner/src/lib.rs b/extensions/pagetop-aliner/src/lib.rs index 9775a990..4f77e257 100644 --- a/extensions/pagetop-aliner/src/lib.rs +++ b/extensions/pagetop-aliner/src/lib.rs @@ -104,9 +104,9 @@ impl Extension for Aliner { Some(&Self) } - fn configure_static_files(&self, router: Router) -> Router { - serve_static_files!(router, [aliner] => "/aliner"); - router + fn configure_static_files(&self, files: StaticFiles) -> StaticFiles { + serve_static_files!(files, [aliner] => "/aliner"); + files } } diff --git a/extensions/pagetop-bootsier/README.md b/extensions/pagetop-bootsier/README.md index ec0a0fe8..ee55f903 100644 --- a/extensions/pagetop-bootsier/README.md +++ b/extensions/pagetop-bootsier/README.md @@ -77,10 +77,8 @@ async fn homepage(request: HttpRequest) -> Result { Bootsier maqueta las dos plantillas de PageTop (`CoreTemplates`) con las mismas regiones (cabecera, lateral, contenido y pie): `Standard`, la plantilla por defecto de cualquier página; y `Admin`, que -se activa creando la página con `Page::admin()` en lugar de `Page::new()`. Ambas se maquetan igual -hoy -- la distinción entre página "normal" y de administración no vive en el maquetado, sino en qué -extensión registra contenido en cada región y para qué plantilla se autolimita (por ejemplo, el menú -de `pagetop-admin`, ver más abajo). +se activa creando la página con `Page::admin()` en lugar de `Page::new()` y añade el panel de +administración (ver más abajo). ```rust,no_run use pagetop::prelude::*; @@ -95,12 +93,12 @@ async fn about(request: HttpRequest) -> Result { } ``` -## Menú de administración +## Panel de administración -`pagetop-admin` (si está presente en la aplicación) registra su propio menú de secciones y -páginas en `CoreRegions::Aside`, autolimitado a páginas con la plantilla `Admin` -- no requiere -ningún registro por parte de Bootsier. Se construye con `Navbar`/`Nav`/`Dropdown`, los mismos -componentes disponibles para cualquier página de la aplicación. +En la plantilla `Admin`, Bootsier sigue la composición del núcleo: tras la cabecera pinta la +navegación del panel (`AdminMenu`) y, en lugar del contenido, el marco de la página (`AdminFrame`: +migas, título, botones y pestañas). Los dos se construyen con componentes del núcleo +(`Navbar`/`Nav`/`Dropdown`, `Breadcrumb`), que Bootsier ya pinta con su aspecto. ## Selector de modo de color diff --git a/extensions/pagetop-bootsier/assets/_bootsier-custom.scss b/extensions/pagetop-bootsier/assets/_bootsier-custom.scss index 2884411e..7429effe 100644 --- a/extensions/pagetop-bootsier/assets/_bootsier-custom.scss +++ b/extensions/pagetop-bootsier/assets/_bootsier-custom.scss @@ -248,3 +248,51 @@ fieldset > legend { border-start-start-radius: 0; border-end-start-radius: 0; } + +// Frame of an administration page (`AdminFrame`): title with its action links, then the local +// tasks as tabs. +.admin-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.5rem 1rem; + margin: 1rem 0; +} + +.admin-page-title { + margin: 0; +} + +.admin-actions-list, +.admin-tasks-list { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + margin: 0; + padding: 0; + list-style: none; +} + +.admin-action-link { + @extend .btn; + @extend .btn-outline-primary; +} + +.admin-local-tasks { + margin-bottom: 1rem; + border-bottom: var(--bs-border-width) solid var(--bs-border-color); +} + +.admin-task a { + display: block; + padding: 0.5rem 0.75rem; + margin-bottom: calc(-1 * var(--bs-border-width)); + border-bottom: 2px solid transparent; + text-decoration: none; +} + +.admin-task-active a { + border-bottom-color: var(--bs-primary); + font-weight: 600; +} diff --git a/extensions/pagetop-bootsier/src/lib.rs b/extensions/pagetop-bootsier/src/lib.rs index 38bc9443..3bc0fa0e 100644 --- a/extensions/pagetop-bootsier/src/lib.rs +++ b/extensions/pagetop-bootsier/src/lib.rs @@ -78,10 +78,8 @@ async fn homepage(request: HttpRequest) -> Result { Bootsier maqueta las dos plantillas de PageTop (`CoreTemplates`) con las mismas regiones (cabecera, lateral, contenido y pie): `Standard`, la plantilla por defecto de cualquier página; y `Admin`, que -se activa creando la página con `Page::admin()` en lugar de `Page::new()`. Ambas se maquetan igual -hoy -- la distinción entre página "normal" y de administración no vive en el maquetado, sino en qué -extensión registra contenido en cada región y para qué plantilla se autolimita (por ejemplo, el menú -de `pagetop-admin`, ver más abajo). +se activa creando la página con `Page::admin()` en lugar de `Page::new()` y añade el panel de +administración (ver más abajo). ```rust,no_run use pagetop::prelude::*; @@ -96,12 +94,12 @@ async fn about(request: HttpRequest) -> Result { } ``` -## Menú de administración +## Panel de administración -`pagetop-admin` (si está presente en la aplicación) registra su propio menú de secciones y -páginas en `CoreRegions::Aside`, autolimitado a páginas con la plantilla `Admin` -- no requiere -ningún registro por parte de Bootsier. Se construye con `Navbar`/`Nav`/`Dropdown`, los mismos -componentes disponibles para cualquier página de la aplicación. +En la plantilla `Admin`, Bootsier sigue la composición del núcleo: tras la cabecera pinta la +navegación del panel (`AdminMenu`) y, en lugar del contenido, el marco de la página (`AdminFrame`: +migas, título, botones y pestañas). Los dos se construyen con componentes del núcleo +(`Navbar`/`Nav`/`Dropdown`, `Breadcrumb`), que Bootsier ya pinta con su aspecto. ## Selector de modo de color @@ -156,7 +154,7 @@ impl Extension for Bootsier { Some(&config::SETTINGS) } - fn configure_static_files(&self, router: Router) -> Router { + fn configure_static_files(&self, files: StaticFiles) -> StaticFiles { let base = &config::SETTINGS.static_dir; let subdir = |s: &str| { if base.is_empty() { @@ -165,10 +163,10 @@ impl Extension for Bootsier { format!("{base}/{s}") } }; - serve_static_files!(router, [subdir("css"), bootsier_css] => "/bootsier/css"); - serve_static_files!(router, [subdir("js"), bootsier_js] => "/bootsier/js"); - serve_static_files!(router, [subdir("fonts"), bootsier_fonts] => "/bootsier/fonts"); - router + serve_static_files!(files, [subdir("css"), bootsier_css] => "/bootsier/css"); + serve_static_files!(files, [subdir("js"), bootsier_js] => "/bootsier/js"); + serve_static_files!(files, [subdir("fonts"), bootsier_fonts] => "/bootsier/fonts"); + files } } @@ -234,12 +232,8 @@ impl Theme for Bootsier { // Etiquetas de los botones del modal de confirmación que sustituye al `confirm()` nativo // de htmx (ver `bootsier.confirm.js`); se leen aquí porque este es el único punto con // acceso al `Context` para resolverlas antes de escribirlas en el ``. - let confirm_ok = Lc::l("confirm_ok") - .lookup(page.context()) - .unwrap_or_default(); - let confirm_cancel = Lc::l("confirm_cancel") - .lookup(page.context()) - .unwrap_or_default(); + let confirm_ok = Lc::l("confirm_ok").lookup(page).unwrap_or_default(); + let confirm_cancel = Lc::l("confirm_cancel").lookup(page).unwrap_or_default(); // Las URLs de las fuentes deben coincidir exactamente con las declaradas en @font-face de // _bootsier-custom.scss; cualquier discrepancia hace que el navegador descargue dos veces. diff --git a/extensions/pagetop-bootsier/src/theme.rs b/extensions/pagetop-bootsier/src/theme.rs index 5dd22b90..a7552e24 100644 --- a/extensions/pagetop-bootsier/src/theme.rs +++ b/extensions/pagetop-bootsier/src/theme.rs @@ -13,10 +13,8 @@ //! //! Bootsier maqueta las dos plantillas de PageTop ([`CoreTemplates`]) con la misma cabecera, //! contenido y pie: `Standard`, la plantilla por defecto de cualquier página; y `Admin`, que se -//! activa creando la página con [`Page::admin()`] en lugar de [`Page::new()`]. Ambas se maquetan -//! igual hoy -- la distinción entre página "normal" y de administración no vive en el maquetado, -//! sino en qué extensión registra contenido en cada región y para qué plantilla se autolimita (ver -//! más abajo `pagetop-admin`). +//! activa creando la página con [`Page::admin()`] en lugar de [`Page::new()`] y añade el panel de +//! administración (ver más abajo). //! //! ```rust,no_run //! use pagetop::prelude::*; @@ -35,13 +33,12 @@ //! [`Page::admin()`]: pagetop::response::Page::admin //! [`Page::new()`]: pagetop::response::Page::new //! -//! # Menú de administración +//! # Panel de administración //! -//! `pagetop-admin` (si está presente en la aplicación) registra su propio menú de secciones y -//! páginas en [`CoreRegions::Aside`], autolimitado a -//! páginas con la plantilla `Admin` -- no requiere ningún registro por parte de Bootsier. Se -//! construye con [`Navbar`]/[`Nav`]/[`Dropdown`], los mismos -//! componentes disponibles para cualquier página de la aplicación. +//! En la plantilla `Admin`, Bootsier sigue la composición del núcleo: tras la cabecera pinta la +//! navegación del panel ([`AdminMenu`]) y, en lugar del contenido, el marco de la página +//! ([`AdminFrame`]: migas, título, botones y pestañas). Los dos se construyen con componentes del +//! núcleo ([`Navbar`]/[`Nav`]/[`Dropdown`], [`Breadcrumb`]), que Bootsier ya pinta con su aspecto. //! //! # Selector de modo de color //! diff --git a/extensions/pagetop-bootsier/src/theme/bs/layout/template.rs b/extensions/pagetop-bootsier/src/theme/bs/layout/template.rs index 8a4f7295..89a38358 100644 --- a/extensions/pagetop-bootsier/src/theme/bs/layout/template.rs +++ b/extensions/pagetop-bootsier/src/theme/bs/layout/template.rs @@ -8,28 +8,23 @@ use crate::theme::bs; // `CoreTemplates`, dejando que el resto de la cadena de temas (o el propio componente) resuelva el // renderizado por defecto. // -// `CoreTemplates::Admin` delega hoy en el mismo maquetado que `Standard`: la diferencia entre -// página "normal" y de administración no vive en la plantilla, sino en qué se registra en cada -// región -- p. ej. el menú de `pagetop-admin` en `CoreRegions::Aside`, que se autolimita a -// `CoreTemplates::Admin` (ver `pagetop_admin::component::AdminMenu`). Mantener la rama separada -// deja abierta la posibilidad de que un maquetado distinto lo necesite en el futuro sin tocar el -// núcleo. +// `CoreTemplates::Admin` sigue la composición del núcleo: tras la cabecera, la navegación del +// panel (`AdminMenu`) y, en lugar del contenido, el marco de la página (`AdminFrame`), que +// contiene la región `Content`. pub(crate) async fn render( component: &layout::Template, cx: &mut Context, ) -> Option> { match component.template().downcast_ref::()? { CoreTemplates::Standard => Some(Ok(render_standard(cx).await)), - CoreTemplates::Admin => Some(Ok(render_standard(cx).await)), + CoreTemplates::Admin => Some(Ok(render_admin(cx).await)), } } // `CoreRegions::Header`, `CoreRegions::Aside`, `CoreRegions::Content` y `CoreRegions::Footer` // envueltos en un contenedor de ancho configurable. async fn render_standard(cx: &mut Context) -> Markup { - bs::Container::new() - .with_prop(PropsOp::add_classes("container-wrapper")) - .with_width(bs::container::Width::FluidMax(config::SETTINGS.max_width)) + wrapper() .with_child(layout::Region::header()) .with_child(layout::Region::aside()) .with_child(layout::Region::default()) @@ -37,3 +32,23 @@ async fn render_standard(cx: &mut Context) -> Markup { .render(cx) .await } + +// Como `render_standard()`, con la navegación del panel tras la cabecera y el marco de la página +// en lugar de la región `Content`. +async fn render_admin(cx: &mut Context) -> Markup { + wrapper() + .with_prop(PropsOp::add_classes("container-wrapper-admin")) + .with_child(layout::Region::header()) + .with_child(AdminMenu::new()) + .with_child(layout::Region::aside()) + .with_child(AdminFrame::new()) + .with_child(layout::Region::footer()) + .render(cx) + .await +} + +fn wrapper() -> bs::Container { + bs::Container::new() + .with_prop(PropsOp::add_classes("container-wrapper")) + .with_width(bs::container::Width::FluidMax(config::SETTINGS.max_width)) +} diff --git a/extensions/pagetop-cron/src/lib.rs b/extensions/pagetop-cron/src/lib.rs index 2cb3ff9b..bf33960a 100644 --- a/extensions/pagetop-cron/src/lib.rs +++ b/extensions/pagetop-cron/src/lib.rs @@ -391,11 +391,11 @@ impl Extension for Cron { scheduler::shutdown().await; } - fn configure_router(&self, router: Router) -> Router { + fn configure_router(&self, routes: Routes) -> Routes { if config::SETTINGS.mode != config::CronMode::External { - return router; + return routes; } - router.route(TRIGGER_PATH, web::post(trigger_post).fallback(not_found)) + routes.public_route(TRIGGER_PATH, web::post(trigger_post).fallback(not_found)) } } diff --git a/extensions/pagetop-htmx/src/hx_table.rs b/extensions/pagetop-htmx/src/hx_table.rs index 4ae29ac0..1745fd10 100644 --- a/extensions/pagetop-htmx/src/hx_table.rs +++ b/extensions/pagetop-htmx/src/hx_table.rs @@ -70,7 +70,7 @@ use crate::hx; /// [`SortLink`]: pagetop::base::component::table::SortLink /// [`SortLink::with_prop()`]: pagetop::base::component::table::SortLink::with_prop /// [`SortLink::with_dir()`]: pagetop::base::component::table::SortLink::with_dir -/// [`Context::route()`]: pagetop::core::component::Context::route +/// [`Context::route()`]: pagetop::core::component::Contextual::route pub fn sort_link( href: impl Into, target: impl AsRef, diff --git a/extensions/pagetop-htmx/src/lib.rs b/extensions/pagetop-htmx/src/lib.rs index f4b46df6..edaf1c3f 100644 --- a/extensions/pagetop-htmx/src/lib.rs +++ b/extensions/pagetop-htmx/src/lib.rs @@ -147,9 +147,9 @@ impl Extension for Htmx { actions![action::page::BeforeRenderBody::new(add_htmx_script)] } - fn configure_static_files(&self, router: Router) -> Router { - serve_static_files!(router, [htmx] => "/htmx"); - router + fn configure_static_files(&self, files: StaticFiles) -> StaticFiles { + serve_static_files!(files, [htmx] => "/htmx"); + files } } diff --git a/extensions/pagetop-htmx/src/response.rs b/extensions/pagetop-htmx/src/response.rs index c44505e0..f31600e6 100644 --- a/extensions/pagetop-htmx/src/response.rs +++ b/extensions/pagetop-htmx/src/response.rs @@ -141,7 +141,7 @@ impl HtmxResponse { /// objetivo definido por el destino. Para personalizar `target`, `swap`, `select` o `values`, /// usa [`location_json()`](Self::location_json). /// - /// Usa [`Context::route()`](pagetop::core::component::Context::route) en lugar de un literal + /// Usa [`Context::route()`](pagetop::core::component::Contextual::route) en lugar de un literal /// para que la URL preserve el parámetro `lang` cuando corresponda: /// /// ```rust,no_run @@ -213,7 +213,7 @@ impl HtmxResponse { /// El usuario podrá navegar hacia atrás hasta esa URL. Usar `"false"` para desactivar el empuje /// aunque esté habilitado por el atributo `hx-push-url` del elemento. /// - /// Usa [`Context::route()`](pagetop::core::component::Context::route) en lugar de un literal + /// Usa [`Context::route()`](pagetop::core::component::Contextual::route) en lugar de un literal /// para que la URL preserve el parámetro `lang` cuando corresponda: /// /// ```rust,no_run @@ -231,7 +231,7 @@ impl HtmxResponse { /// Reemplaza la URL actual en el historial sin añadir una nueva entrada. /// /// Usar `"false"` para desactivar el reemplazo. Usa - /// [`Context::route()`](pagetop::core::component::Context::route) en lugar de un literal para + /// [`Context::route()`](pagetop::core::component::Contextual::route) en lugar de un literal para /// que la URL preserve el parámetro `lang` cuando corresponda. pub fn replace_url(self, url: impl Into) -> Self { self.set_header(hx::response::REPLACE_URL.as_bytes(), url.into().to_string()) @@ -242,7 +242,7 @@ impl HtmxResponse { /// A diferencia de [`location()`](Self::location), esta redirección recarga la página por /// completo, como un `window.location.href = url` en JavaScript. /// - /// Usa [`Context::route()`](pagetop::core::component::Context::route) en lugar de un literal + /// Usa [`Context::route()`](pagetop::core::component::Contextual::route) en lugar de un literal /// para que la URL preserve el parámetro `lang` cuando corresponda: /// /// ```rust,no_run diff --git a/extensions/pagetop-htmx/tests/extension.rs b/extensions/pagetop-htmx/tests/extension.rs index 36c21704..beccc761 100644 --- a/extensions/pagetop-htmx/tests/extension.rs +++ b/extensions/pagetop-htmx/tests/extension.rs @@ -9,8 +9,8 @@ impl Extension for TestApp { vec![&Htmx] } - fn configure_router(&self, router: Router) -> Router { - router.route("/page", web::get(render_page)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/page", web::get(render_page)) } } diff --git a/extensions/pagetop-htmx/tests/request.rs b/extensions/pagetop-htmx/tests/request.rs index 90995ec0..729b0c85 100644 --- a/extensions/pagetop-htmx/tests/request.rs +++ b/extensions/pagetop-htmx/tests/request.rs @@ -5,8 +5,8 @@ struct TestApp; #[async_trait] impl Extension for TestApp { - fn configure_router(&self, router: Router) -> Router { - router.route("/echo", web::get(echo_request)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/echo", web::get(echo_request)) } } diff --git a/extensions/pagetop-mail/README.md b/extensions/pagetop-mail/README.md index c9fd92f7..5a9119be 100644 --- a/extensions/pagetop-mail/README.md +++ b/extensions/pagetop-mail/README.md @@ -172,6 +172,16 @@ extensiones declaran con la acción `DeclareMailPreviews`, y muestra cada uno co cabeceras, HTML con el diseño común, texto plano y adjuntos, sin enviar nada. Ver el módulo `preview`. +## Correo de prueba desde el panel de administración + +`pagetop-mail` añade al panel de administración de PageTop la página **Configuración > Correo +electrónico** (`config/mail`, bajo la raíz del panel). Muestra el transporte, el remitente y el +servidor configurados, nunca las credenciales, y envía un correo de prueba a la dirección que se +indique, esperando al resultado: al volver a la página se ve si se ha enviado o el error del +transporte. Sirve para comprobar la configuración en producción sin enviar correos reales a nadie +más. Exige el permiso `mail:send_test` (`MailPermission::SendTest`), que concede la extensión de +autenticación (p. ej. asignándolo a un rol con `pagetop-user`). + ## Texto plano automático Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques diff --git a/extensions/pagetop-mail/src/admin.rs b/extensions/pagetop-mail/src/admin.rs new file mode 100644 index 00000000..367fe886 --- /dev/null +++ b/extensions/pagetop-mail/src/admin.rs @@ -0,0 +1,207 @@ +//! Página del panel de administración para comprobar la configuración del correo enviando un correo +//! de prueba. + +use pagetop::prelude::*; + +use serde::Deserialize; + +use crate::config::{self, MailTransport, SmtpSecurity}; +use crate::{Email, LOCALES_MAIL, Mailbox}; + +// Ruta de la página, relativa a la raíz del panel. +const TEST_MAIL: &str = "config/mail"; + +// **< Permiso >************************************************************************************ + +/// Permisos propios de `pagetop-mail`. +#[derive(Clone, Copy, Debug)] +pub enum MailPermission { + /// Ver la configuración del correo (sin credenciales) y enviar correos de prueba desde el panel + /// de administración. + SendTest, +} + +impl Permission for MailPermission { + fn key(&self) -> CowStr { + match self { + Self::SendTest => "mail:send_test".into(), + } + } + + fn label(&self) -> Lc { + match self { + Self::SendTest => Lc::t("perm_send_test", &LOCALES_MAIL), + } + } + + fn group(&self) -> &'static str { + "mail" + } + + fn group_label(&self) -> Lc { + Lc::t("extension_name", &LOCALES_MAIL) + } +} + +pub(crate) fn declare_permissions(registry: &mut PermissionRegistry) { + registry.register(&MailPermission::SendTest); +} + +// **< Página del panel >*************************************************************************** + +pub(crate) fn declare_pages(bag: &mut AdminPageBag) { + bag.add( + AdminPage::new( + TEST_MAIL, + "config", + Lc::t("test_title", &LOCALES_MAIL), + &MailPermission::SendTest, + ) + .with_description(Lc::t("test_description", &LOCALES_MAIL)), + ); +} + +pub(crate) fn configure_router(routes: Routes) -> Routes { + routes.admin_route(TEST_MAIL, web::get(test_mail_get).post(test_mail_post)) +} + +// Muestra la configuración del correo y el formulario para enviar un correo de prueba. +async fn test_mail_get(request: HttpRequest) -> Result { + let mut page = Page::admin(request).with_title(Lc::t("test_title", &LOCALES_MAIL)); + if let Some(warning) = not_delivered_warning() { + page.push_message(MessageLevel::Warning, warning); + } + page.with_child(settings_summary()) + .with_child(test_form()) + .render() + .await +} + +#[derive(Deserialize)] +struct TestMailForm { + to: String, +} + +// Envía el correo de prueba y vuelve a la página con el resultado. Espera a la entrega, sin pasar +// por la cola, para poder informar del error del transporte. +async fn test_mail_post( + request: HttpRequest, + web::Form(form): web::Form, +) -> Result { + let cx = Context::admin(request); + let to = form.to.trim().to_owned(); + let back = Redirect::see_other(cx.route(admin_path(TEST_MAIL))); + + if Mailbox::new(to.as_str()).validate().is_err() { + let text = Lc::t("test_invalid_address", &LOCALES_MAIL).with_arg("to", to); + return Ok(back.with_message(&cx, MessageLevel::Error, text)); + } + + let app = global::SETTINGS.app.name.clone(); + let subject = Lc::t("test_subject", &LOCALES_MAIL).with_arg("app", app.clone()); + let body = Lc::t("test_body", &LOCALES_MAIL).with_arg("app", app); + let result = Email::new() + .with_to(to.as_str()) + .with_subject(subject.lookup(&cx).unwrap_or_default()) + .with_html(html! { p { (body.using(&cx)) } }) + .send() + .await; + + Ok(match result { + Ok(()) => { + trace::info!("Test email sent to {to}"); + let text = Lc::t("test_sent", &LOCALES_MAIL).with_arg("to", to); + back.with_message(&cx, MessageLevel::Info, text) + } + Err(err) => { + trace::warn!("Test email to {to} failed: {err}"); + let text = Lc::t("test_failed", &LOCALES_MAIL).with_arg("error", err.to_string()); + back.with_message(&cx, MessageLevel::Error, text) + } + }) +} + +// Aviso si el transporte configurado no entrega los correos. +fn not_delivered_warning() -> Option { + let key = match config::SETTINGS.transport { + MailTransport::Log => "test_log_warning", + MailTransport::Memory => "test_memory_warning", + _ => return None, + }; + Some(Lc::t(key, &LOCALES_MAIL)) +} + +// Ajustes del correo que ayudan a interpretar el resultado de la prueba, nunca las credenciales. +fn settings_summary() -> Block { + let settings = &config::SETTINGS; + let none = || Lc::t("test_not_set", &LOCALES_MAIL); + let text = |value: &Option| value.clone().map_or_else(none, Lc::n); + + let transport = match settings.transport { + MailTransport::Smtp => "transport_smtp", + MailTransport::Sendmail => "transport_sendmail", + MailTransport::File => "transport_file", + MailTransport::Log => "transport_log", + MailTransport::Memory => "transport_memory", + }; + let mut rows = vec![ + ("test_transport", Lc::t(transport, &LOCALES_MAIL)), + ("test_from", text(&settings.from)), + ("test_reply_to", text(&settings.reply_to)), + ]; + if settings.redirect_to.is_some() { + rows.push(("test_redirect_to", text(&settings.redirect_to))); + } + match settings.transport { + MailTransport::Smtp => { + let smtp = &settings.smtp; + let (security, default_port) = match smtp.security { + SmtpSecurity::None => ("security_none", 25), + SmtpSecurity::Opportunistic => ("security_opportunistic", 25), + SmtpSecurity::StartTls => ("security_starttls", 587), + SmtpSecurity::Tls => ("security_tls", 465), + }; + let port = smtp.port.unwrap_or(default_port).to_string(); + rows.push(("test_smtp_server", Lc::n(util::join!(smtp.host, ":", port)))); + rows.push(("test_smtp_security", Lc::t(security, &LOCALES_MAIL))); + } + MailTransport::Sendmail => { + rows.push(("test_sendmail_command", text(&settings.sendmail.command))); + } + MailTransport::File => { + rows.push(("test_file_dir", Lc::n(settings.file.dir.clone()))); + } + MailTransport::Log | MailTransport::Memory => {} + } + + let mut table = Table::new(); + for (label, value) in rows { + table = table.with_row( + table::Row::new() + .with_cell(Lc::t(label, &LOCALES_MAIL)) + .with_cell(value), + ); + } + Block::new() + .with_title(Lc::t("test_settings", &LOCALES_MAIL)) + .with_child(table) +} + +fn test_form() -> Form { + Form::new() + .with_id("mail-test-form") + .with_action(admin_path(TEST_MAIL)) + .with_method(form::Method::Post) + .with_child( + form::input::Field::email() + .with_name("to") + .with_label(Lc::t("test_to", &LOCALES_MAIL)) + .with_autocomplete(Some(form::Autocomplete::email())) + .with_required(true) + .with_maxlength(254), + ) + .with_child( + Button::submit(Lc::t("test_send", &LOCALES_MAIL)) + .with_style(button::Style::Solid(Intent::Primary)), + ) +} diff --git a/extensions/pagetop-mail/src/lib.rs b/extensions/pagetop-mail/src/lib.rs index 440c9faf..d4d7fbaf 100644 --- a/extensions/pagetop-mail/src/lib.rs +++ b/extensions/pagetop-mail/src/lib.rs @@ -170,6 +170,16 @@ Con `previews = true` en `[mail]` (sólo en desarrollo), `/mail/preview` lista l extensiones declaran con la acción [`DeclareMailPreviews`], y muestra cada uno con datos de ejemplo: cabeceras, HTML con el diseño común, texto plano y adjuntos, sin enviar nada. Ver [`preview`]. +## Correo de prueba desde el panel de administración + +`pagetop-mail` añade al panel de administración de PageTop la página **Configuración > Correo +electrónico** (`config/mail`, bajo la raíz del panel). Muestra el transporte, el remitente y el +servidor configurados, nunca las credenciales, y envía un correo de prueba a la dirección que se +indique, esperando al resultado: al volver a la página se ve si se ha enviado o el error del +transporte. Sirve para comprobar la configuración en producción sin enviar correos reales a nadie +más. Exige el permiso `mail:send_test` ([`MailPermission::SendTest`]), que concede la extensión de +autenticación (p. ej. asignándolo a un rol con `pagetop-user`). + ## Texto plano automático Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques @@ -273,6 +283,9 @@ pub mod outbox; pub mod preview; pub use preview::{DeclareMailPreviews, MailPreviews}; +mod admin; +pub use admin::MailPermission; + mod text; mod transport; @@ -307,9 +320,21 @@ impl Extension for Mail { vec![&pagetop_seaorm::SeaORM, &pagetop_cron::Cron] } + #[cfg(not(feature = "queue"))] + fn actions(&self) -> Vec { + actions![ + action::auth::DeclarePermissions::new(admin::declare_permissions), + action::admin::DeclareAdminPages::new(admin::declare_pages), + ] + } + #[cfg(feature = "queue")] fn actions(&self) -> Vec { - actions![pagetop_cron::DeclareCronJobs::new(queue::declare_jobs)] + actions![ + action::auth::DeclarePermissions::new(admin::declare_permissions), + action::admin::DeclareAdminPages::new(admin::declare_pages), + pagetop_cron::DeclareCronJobs::new(queue::declare_jobs), + ] } fn settings(&self) -> Option<&'static dyn LoadSettings> { @@ -325,13 +350,16 @@ impl Extension for Mail { Ok(()) } - fn configure_router(&self, router: Router) -> Router { + fn configure_router(&self, routes: Routes) -> Routes { + let routes = admin::configure_router(routes); + // Las vistas previas son públicas: sólo se montan con `mail.previews`, pensado para el + // desarrollo y que avisa al arrancar, y muestran los correos con datos de ejemplo. if !config::SETTINGS.previews { - return router; + return routes; } - router - .route(preview::PREVIEW_PATH, web::get(preview::list_get)) - .route( + routes + .public_route(preview::PREVIEW_PATH, web::get(preview::list_get)) + .public_route( &util::join!(preview::PREVIEW_PATH, "/{key}"), web::get(preview::preview_get), ) diff --git a/extensions/pagetop-mail/src/locale/en-US/extension.ftl b/extensions/pagetop-mail/src/locale/en-US/extension.ftl index c64a8a39..408febfd 100644 --- a/extensions/pagetop-mail/src/locale/en-US/extension.ftl +++ b/extensions/pagetop-mail/src/locale/en-US/extension.ftl @@ -20,3 +20,37 @@ preview_attachments = Attachments preview_html = HTML preview_text = Plain text preview_none = None + +# **< Test email >** + +perm_send_test = Send test emails from the administration panel +test_title = Email +test_description = Delivery settings and test email. +test_settings = Current settings +test_transport = Transport +test_from = Sender +test_reply_to = Reply to +test_redirect_to = Every email is delivered to +test_smtp_server = SMTP server +test_smtp_security = Security +test_sendmail_command = Program +test_file_dir = Directory +test_not_set = Not set +test_to = Send a test email to +test_send = Send test email +test_subject = Test email from { $app } +test_body = This email confirms that { $app } can send messages with the current settings. +test_sent = Test email sent to { $to }. +test_failed = The test email could not be sent: { $error } +test_invalid_address = "{ $to }" is not a valid email address. +test_log_warning = With the current transport emails are not sent: they are written to the logs. +test_memory_warning = With the current transport emails are not sent: they are kept in memory. +transport_smtp = SMTP +transport_sendmail = sendmail program +transport_file = .eml files +transport_log = Logs (not sent) +transport_memory = Memory (not sent) +security_none = Unencrypted +security_opportunistic = STARTTLS if the server supports it +security_starttls = STARTTLS required +security_tls = TLS from the connection diff --git a/extensions/pagetop-mail/src/locale/es-ES/extension.ftl b/extensions/pagetop-mail/src/locale/es-ES/extension.ftl index 627f0dd0..78c89e26 100644 --- a/extensions/pagetop-mail/src/locale/es-ES/extension.ftl +++ b/extensions/pagetop-mail/src/locale/es-ES/extension.ftl @@ -20,3 +20,37 @@ preview_attachments = Adjuntos preview_html = HTML preview_text = Texto plano preview_none = Ninguno + +# **< Correo de prueba >** + +perm_send_test = Enviar correos de prueba desde el panel de administración +test_title = Correo electrónico +test_description = Configuración del envío y correo de prueba. +test_settings = Configuración actual +test_transport = Transporte +test_from = Remitente +test_reply_to = Responder a +test_redirect_to = Todos los correos se entregan a +test_smtp_server = Servidor SMTP +test_smtp_security = Seguridad +test_sendmail_command = Programa +test_file_dir = Directorio +test_not_set = Sin configurar +test_to = Enviar un correo de prueba a +test_send = Enviar correo de prueba +test_subject = Correo de prueba de { $app } +test_body = Este correo confirma que { $app } puede enviar mensajes con la configuración actual. +test_sent = Correo de prueba enviado a { $to }. +test_failed = No se pudo enviar el correo de prueba: { $error } +test_invalid_address = «{ $to }» no es una dirección de correo válida. +test_log_warning = Con el transporte actual los correos no se envían: se escriben en las trazas. +test_memory_warning = Con el transporte actual los correos no se envían: se guardan en memoria. +transport_smtp = SMTP +transport_sendmail = Programa sendmail +transport_file = Archivos .eml +transport_log = Trazas (no se envía) +transport_memory = Memoria (no se envía) +security_none = Sin cifrar +security_opportunistic = STARTTLS si el servidor lo admite +security_starttls = STARTTLS obligatorio +security_tls = TLS desde la conexión diff --git a/extensions/pagetop-mail/tests/admin.rs b/extensions/pagetop-mail/tests/admin.rs new file mode 100644 index 00000000..f767fd4c --- /dev/null +++ b/extensions/pagetop-mail/tests/admin.rs @@ -0,0 +1,124 @@ +// The test email page of the administration panel. `config/common.toml` keeps the emails in +// memory. Nothing in this binary manages permissions, so `grant()` plays the authentication +// extension: it grants every permission to the requests sent with the `x-grant` header. +// +// The scenarios run one after another in a single test: with the `queue` feature, starting the +// application installs the queue migrations, and starting it from parallel tests would install +// them at the same time on the same in-memory database. + +use pagetop::prelude::*; + +struct TestApp; + +#[async_trait] +impl Extension for TestApp { + fn dependencies(&self) -> Vec { + vec![&pagetop_mail::Mail] + } + + fn actions(&self) -> Vec { + actions![action::auth::CheckPermission::new(grant)] + } +} + +fn grant(request: &HttpRequest, _: PermissionRef, granted: &mut bool) { + if request.headers().contains_key("x-grant") { + *granted = true; + } +} + +async fn app() -> Router { + web::test::init_router(Application::prepare(&TestApp).await.test()) +} + +async fn send(app: &Router, request: web::test::TestRequest) -> (u16, String, String) { + let response = web::test::send_request(app, request.to_request()).await; + let status = response.status().as_u16(); + let header = |name| { + response + .headers() + .get(name) + .and_then(|value| value.to_str().ok()) + .unwrap_or_default() + .to_owned() + }; + let (location, cookie) = (header("location"), header("set-cookie")); + let _ = web::test::read_body_text(response).await; + (status, location, cookie) +} + +fn post(to: &str) -> web::test::TestRequest { + web::test::TestRequest::post() + .uri("/admin/config/mail") + .header("x-grant", "yes") + .form(format!("to={to}")) +} + +#[pagetop::test] +async fn test_email_page() { + let app = app().await; + the_page_and_its_permission_are_declared(); + the_page_shows_the_settings_without_credentials_and_the_form(&app).await; + without_the_permission_the_page_is_denied(&app).await; + a_test_email_is_sent_and_reported(&app).await; + an_invalid_address_sends_nothing(&app).await; +} + +fn the_page_and_its_permission_are_declared() { + let page = AdminRegistry::global().page("config/mail").unwrap(); + assert_eq!(page.section(), "config"); + assert_eq!(page.permission().key(), "mail:send_test"); + assert!(PermissionRegistry::global().has_key("mail:send_test")); +} + +async fn the_page_shows_the_settings_without_credentials_and_the_form(app: &Router) { + let request = web::test::TestRequest::get() + .uri("/admin/config/mail") + .header("x-grant", "yes") + .to_request(); + let response = web::test::send_request(app, request).await; + assert_eq!(response.status().as_u16(), 200); + let html = web::test::read_body_text(response).await; + assert!( + html.contains("PageTop Tests <tests@example.com>"), + "{html}" + ); + assert!(html.contains(r#"id="mail-test-form""#), "{html}"); + assert!(html.contains(r#"action="/admin/config/mail""#), "{html}"); + assert!(html.contains(r#"name="to""#), "{html}"); +} + +async fn without_the_permission_the_page_is_denied(app: &Router) { + let get = web::test::TestRequest::get().uri("/admin/config/mail"); + assert_eq!(send(app, get).await.0, 403); + let post = web::test::TestRequest::post() + .uri("/admin/config/mail") + .form("to=nobody@example.com"); + assert_eq!(send(app, post).await.0, 403); + assert!(pagetop_mail::outbox::take_to("nobody@example.com").is_empty()); +} + +async fn a_test_email_is_sent_and_reported(app: &Router) { + let (status, location, cookie) = send(app, post("admin@example.com")).await; + assert_eq!(status, 303); + assert_eq!(location, "/admin/config/mail"); + // An information message for the next page. + assert!( + cookie.starts_with("pagetop_flash=iTest%20email%20sent%20to%20admin%40example.com"), + "{cookie}" + ); + + let sent = pagetop_mail::outbox::take_to("admin@example.com"); + assert_eq!(sent.len(), 1); + let subject = sent[0].email().subject(); + assert!(subject.contains("PageTop"), "{subject}"); +} + +async fn an_invalid_address_sends_nothing(app: &Router) { + let (status, location, cookie) = send(app, post("not-an-address")).await; + assert_eq!(status, 303); + assert_eq!(location, "/admin/config/mail"); + // An error message for the next page. + assert!(cookie.starts_with("pagetop_flash=e"), "{cookie}"); + assert!(pagetop_mail::outbox::take_to("not-an-address").is_empty()); +} diff --git a/extensions/pagetop-user/Cargo.toml b/extensions/pagetop-user/Cargo.toml index 637b2db7..24201896 100644 --- a/extensions/pagetop-user/Cargo.toml +++ b/extensions/pagetop-user/Cargo.toml @@ -20,7 +20,6 @@ demo-data = [] [dependencies] pagetop.workspace = true -pagetop-admin.workspace = true pagetop-seaorm.workspace = true pagetop-htmx.workspace = true pagetop-mail.workspace = true diff --git a/extensions/pagetop-user/README.md b/extensions/pagetop-user/README.md index c3651445..5ccc6ef1 100644 --- a/extensions/pagetop-user/README.md +++ b/extensions/pagetop-user/README.md @@ -14,8 +14,8 @@ Añade cuentas de usuario a una aplicación PageTop: registro, inicio de sesión con sesiones en la base de datos, perfil propio, recuperación de contraseña y verificación del email por correo, y control de acceso con roles y permisos. Incluye las páginas de administración de usuarios, roles y -permisos sobre `pagetop-admin`, hechas sólo con componentes del núcleo para que funcionen con -cualquier tema. +permisos en el panel de administración del núcleo, hechas sólo con componentes del núcleo para que +funcionen con cualquier tema. ## Sobre PageTop @@ -47,9 +47,11 @@ admin_email = "admin@example.com" # Sin 'admin_password', se genera una aleatoria y se muestra una sola vez al crearlo. ``` -**Comprueba los permisos** en tus *handlers*. El usuario actual se inyecta automáticamente en el -contexto de cada `Page` al crearla con `Page::new()`, y las funciones del núcleo, como -`has_permission()`, lo consultan: +**Protege tus rutas** con su acceso (`Access`): PageTop lo comprueba antes de llegar al *handler* +con los permisos que concede esta extensión, y a un usuario anónimo sin acceso le ofrece el inicio +de sesión. Dentro del *handler*, el usuario actual está en el contexto de cada `Page` al crearla +con `Page::new()`, y funciones del núcleo como `has_permission()` lo consultan para las +comprobaciones más concretas: ```rust,no_run use pagetop::prelude::*; @@ -76,15 +78,16 @@ impl Extension for MyApp { vec![&pagetop_user::User] } - fn configure_router(&self, router: Router) -> Router { - router.route("/dashboard", web::get(dashboard)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.route( + "/dashboard", + Access::Permission(&MyPermission::SeeDashboard), + web::get(dashboard), + ) } } async fn dashboard(request: HttpRequest) -> Result { - if !has_permission(&request, &MyPermission::SeeDashboard) { - return Err(ErrorPage::NotFound(Some(request))); - } Page::new(request) .with_child(Html::with(|_| html! { h1 { "Panel" } })) .render().await diff --git a/extensions/pagetop-user/src/account.rs b/extensions/pagetop-user/src/account.rs index c511c8e5..44dc192f 100644 --- a/extensions/pagetop-user/src/account.rs +++ b/extensions/pagetop-user/src/account.rs @@ -58,6 +58,8 @@ impl PermissionSet { /// Se almacena en las extensiones de la petición HTTP durante la fase de middleware y se accede /// desde los handlers o desde handlers de [`CheckPermission`] mediante /// [`HttpRequest::extension::()`](pagetop::web::HttpRequest::extension). +/// +/// [`CheckPermission`]: pagetop::base::action::auth::CheckPermission #[derive(Clone, Debug, Getters)] pub struct Account { /// Identificador del usuario. diff --git a/extensions/pagetop-user/src/component/account_menu.rs b/extensions/pagetop-user/src/component/account_menu.rs index b2931274..247d0c94 100644 --- a/extensions/pagetop-user/src/component/account_menu.rs +++ b/extensions/pagetop-user/src/component/account_menu.rs @@ -1,7 +1,6 @@ //! Menú de cuenta (iniciar y cerrar sesión). use pagetop::prelude::*; -use pagetop_admin::registry::can_access_admin; use pagetop_htmx::prelude::*; use crate::config::SETTINGS; @@ -49,7 +48,7 @@ pub fn account_menu(cx: &Context) -> Nav { if can_access_admin(cx) { menu = menu.with_item(dropdown::Item::link( Lc::t("menu-admin", &LOCALES_USER), - cx.route(pagetop_admin::ADMIN_BASE_PATH), + cx.route(admin_path("")), )); } nav.with_item(nav::Item::dropdown( diff --git a/extensions/pagetop-user/src/component/admin/role_form.rs b/extensions/pagetop-user/src/component/admin/role_form.rs index 6393a7be..b195e496 100644 --- a/extensions/pagetop-user/src/component/admin/role_form.rs +++ b/extensions/pagetop-user/src/component/admin/role_form.rs @@ -37,7 +37,7 @@ impl Component for RoleForm { async fn prepare(&self, cx: &mut Context) -> Result { let action = match self.mode() { - RoleFormMode::New => util::join!(ADMIN_ROLES_PATH, "/new"), + 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)); diff --git a/extensions/pagetop-user/src/component/admin/role_table.rs b/extensions/pagetop-user/src/component/admin/role_table.rs index 52c7aa98..d03edcb1 100644 --- a/extensions/pagetop-user/src/component/admin/role_table.rs +++ b/extensions/pagetop-user/src/component/admin/role_table.rs @@ -40,7 +40,7 @@ impl Component for RoleTable { async fn prepare(&self, cx: &mut Context) -> Result { let pager = Pager::new() - .with_base_path(ADMIN_ROLES_PATH) + .with_base_path(ADMIN_ROLES_PATH.as_str()) .with_extra_query("sort", self.sort().as_str()) .with_extra_query("dir", *self.dir()) .with_current_page(self.page()) @@ -117,7 +117,7 @@ impl Component for RoleTable { ); } - let new_href = waypoint.append_to(cx.route(util::join!(ADMIN_ROLES_PATH, "/new"))); + let new_href = waypoint.append_to(cx.route(util::join!(ADMIN_ROLES_PATH.as_str(), "/new"))); Ok(html! { div (self.props().unpack(cx)) { @@ -181,7 +181,7 @@ impl RoleTable { // 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) + 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()) @@ -200,7 +200,7 @@ impl RoleTable { let is_active = *self.sort() == field; let active = is_active.then_some(*self.dir()); let next_dir = SortDir::next_for(active); - let mut route = cx.route(ADMIN_ROLES_PATH); + let mut route = cx.route(ADMIN_ROLES_PATH.as_str()); route .alter_param("sort", field.as_str()) .alter_param("dir", next_dir); @@ -229,8 +229,8 @@ fn label_cell(role: &RoleListItem, waypoint: &Waypoint) -> Html { } // Construye la celda de acciones: gestionar permisos si se tiene `user:admin_permissions`, y -// editar/borrar sólo si el rol no está bloqueado por el sistema. Devuelve un componente `Html` para que el marcado se genere cuando -// `Table` renderice la celda, no al construir la fila. +// editar/borrar sólo si el rol no está bloqueado por el sistema. Devuelve un componente `Html` para +// que el marcado se genere cuando `Table` renderice la celda, no al construir la fila. async fn actions_cell( role: &RoleListItem, waypoint: &Waypoint, diff --git a/extensions/pagetop-user/src/component/admin/user_form.rs b/extensions/pagetop-user/src/component/admin/user_form.rs index 98b297f9..bd7ee147 100644 --- a/extensions/pagetop-user/src/component/admin/user_form.rs +++ b/extensions/pagetop-user/src/component/admin/user_form.rs @@ -54,7 +54,7 @@ impl Component for UserForm { async fn prepare(&self, cx: &mut Context) -> Result { let action = match self.mode() { - UserFormMode::New => util::join!(ADMIN_USERS_PATH, "/new"), + UserFormMode::New => util::join!(ADMIN_USERS_PATH.as_str(), "/new"), UserFormMode::Edit => user_path(self.user_id().copied().unwrap_or_default(), "edit"), UserFormMode::Profile => PROFILE_EDIT_PATH.into(), }; diff --git a/extensions/pagetop-user/src/component/admin/user_table.rs b/extensions/pagetop-user/src/component/admin/user_table.rs index 6ce7f072..4fa659ee 100644 --- a/extensions/pagetop-user/src/component/admin/user_table.rs +++ b/extensions/pagetop-user/src/component/admin/user_table.rs @@ -39,7 +39,7 @@ impl Component for UserTable { async fn prepare(&self, cx: &mut Context) -> Result { let pager = Pager::new() - .with_base_path(ADMIN_USERS_PATH) + .with_base_path(ADMIN_USERS_PATH.as_str()) .with_extra_query("q", self.query().cloned().unwrap_or_default()) .with_extra_query("sort", self.sort().as_str()) .with_extra_query("dir", *self.dir()) @@ -83,7 +83,7 @@ impl Component for UserTable { ); } - let new_href = waypoint.append_to(cx.route(util::join!(ADMIN_USERS_PATH, "/new"))); + let new_href = waypoint.append_to(cx.route(util::join!(ADMIN_USERS_PATH.as_str(), "/new"))); Ok(html! { div (self.props().unpack(cx)) { @@ -143,7 +143,7 @@ impl UserTable { // `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); + 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); } @@ -167,7 +167,7 @@ impl UserTable { let active = is_active.then_some(*self.dir()); let next_dir = SortDir::next_for(active); - let mut route = cx.route(ADMIN_USERS_PATH); + 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); } @@ -228,7 +228,7 @@ async fn actions_cell( // Construye la celda de roles: sólo la insignia de administrador si lo es (tiene acceso sin // restricciones, así que sus roles no añaden nada), o las insignias de cada rol asignado, o "-" si // no tiene ninguno. Los badges se renderizan aquí mismo (con el `cx` del ciclo de renderizado de -// `Table`); el resto del marcado se difiere al `Html` que se devuelve, igual que el resto de celdas. +// `Table`); el resto del marcado se difiere al `Html` que se devuelve, como en las demás celdas. async fn roles_cell(user: &UserListItem, cx: &mut Context) -> Html { let mut badges = Vec::with_capacity(user.roles.len().max(1)); if user.is_admin { diff --git a/extensions/pagetop-user/src/handlers/account.rs b/extensions/pagetop-user/src/handlers/account.rs index 603e8a89..80ff6b76 100644 --- a/extensions/pagetop-user/src/handlers/account.rs +++ b/extensions/pagetop-user/src/handlers/account.rs @@ -4,6 +4,7 @@ use serde::Deserialize; use pagetop::prelude::*; +use pagetop_htmx::prelude::*; use crate::account::{Account, UserStatus}; use crate::auth; @@ -39,6 +40,33 @@ fn login_redirect(request: HttpRequest, next: &'static str) -> Response { Redirect::see_other(waypoint.append_to(cx.route(LOGIN_PATH))).into_response() } +// Respuesta a un usuario anónimo sin acceso a una ruta (acción `AnonymousDenied`): el formulario de +// inicio de sesión, que vuelve después a la ruta pedida. +// +// Una petición HTMX seguiría la redirección sin avisar y pintaría el formulario dentro del +// fragmento que esperaba, así que se le pide con `HX-Redirect` que cargue la página completa. +// Vuelve después a la página que tenía abierta el navegador (`HX-Current-URL`), no a la ruta del +// fragmento, que puede no admitir `GET`. +pub(crate) fn offer_login(request: &HttpRequest) -> Option { + let is_htmx = request.is_htmx(); + let waypoint = if is_htmx { + Waypoint::new( + request + .hx_current_url() + .and_then(|url| url.parse::().ok()) + .and_then(|uri| uri.path_and_query().map(|pq| pq.as_str().to_owned())), + ) + } else { + Waypoint::new(request.uri().to_owned()) + }; + let login = waypoint.append_to(Context::new(request.clone()).route(LOGIN_PATH)); + Some(if is_htmx { + HtmxResponse::empty().redirect(login).into_response() + } else { + Redirect::see_other(login).into_response() + }) +} + // **< profile_get >******************************************************************************** /// GET /user - Perfil del usuario autenticado. Redirige al formulario de inicio de sesión si no hay @@ -60,8 +88,8 @@ pub(crate) async fn profile_get(request: HttpRequest) -> Response { let can_change_password = has_permission(&request, &UserPermission::ChangeOwnPassword); let mut page = Page::new(request); - let details_block = user_details(&user, page.context()).await; - let roles_block = profile_roles(&roles, page.context()).await; + let details_block = user_details(&user, page.context_mut()).await; + let roles_block = profile_roles(&roles, page.context_mut()).await; let actions = profile_actions(can_edit, can_change_password, page.context()); page.with_title(Lc::t("title-profile", &LOCALES_USER)) @@ -159,9 +187,12 @@ pub(crate) async fn public_profile_get( request: HttpRequest, web::Path(id): web::Path, ) -> Result { - // El permiso se comprueba antes de buscar al usuario para no revelar qué ids existen. - if current_user_id(&request) != Some(id) { - require_permission(&request, &UserPermission::ViewProfiles)?; + // El permiso se comprueba antes de buscar al usuario para no revelar qué ids existen. Sin él, la + // misma respuesta que una ruta sin acceso: el inicio de sesión a un anónimo y 403 al resto. + if current_user_id(&request) != Some(id) + && !has_permission(&request, &UserPermission::ViewProfiles) + { + return Ok(deny_access(request)); } let Ok(user) = user_admin::find_user(id).await else { return Err(ErrorPage::NotFound(Some(request))); @@ -176,7 +207,7 @@ pub(crate) async fn public_profile_get( Some(name) => name.to_owned(), None => user.username.clone(), }; - let mut page = Page::new(request); + let page = Page::new(request); let details = public_profile_details(&user, page.context()); Ok(page @@ -228,7 +259,6 @@ pub(crate) async fn profile_edit_get(request: HttpRequest) -> Result Result Result Response { - let mut page = Page::new(request); - let cancel = Button::anchor( - Lc::t("btn-cancel", &LOCALES_USER), - page.context().route(PROFILE_PATH), - ); + 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() diff --git a/extensions/pagetop-user/src/handlers/admin.rs b/extensions/pagetop-user/src/handlers/admin.rs index 7b6f40da..32ef5d21 100644 --- a/extensions/pagetop-user/src/handlers/admin.rs +++ b/extensions/pagetop-user/src/handlers/admin.rs @@ -1,26 +1,20 @@ //! Handlers HTTP para el mantenimiento de usuarios, roles y permisos. //! -//! Las páginas de usuarios, roles y permisos se registran en el portal de `pagetop-admin` (ver -//! `declare_admin_pages()`). Cada handler comprueba el permiso correspondiente con -//! [`require_permission()`](pagetop::auth::require_permission) antes de construir la página. +//! Las páginas de usuarios, roles y permisos se declaran en el panel de administración (ver +//! `declare_admin_pages()`), y sus rutas exigen el permiso de su página, que PageTop comprueba +//! antes de llegar al handler. Los handlers sólo comprueban los permisos más concretos (bloquear +//! cuentas, asignar permisos a un rol). pub(crate) mod permissions; pub(crate) mod roles; pub(crate) mod users; use pagetop::prelude::*; -use pagetop_admin::component::AdminFrame; use crate::LOCALES_USER; use crate::error::AuthError; use crate::service::role_admin::ROLE_MACHINE_NAME_MAX_CHARS; -// Envuelve el contenido de una página de administración en el frame de `pagetop-admin`: -// breadcrumb, tareas y acciones locales registradas para la ruta actual en su `AdminRegistry`. -pub(crate) fn frame(title: Lc) -> AdminFrame { - AdminFrame::new().with_title(title) -} - // Traduce un `AuthError` a su clave Lc, para mostrarlo en el formulario que falló. Cubre tanto // los errores de autenticación existentes como los nuevos de administración. pub(crate) fn map_auth_error(err: &AuthError) -> Lc { diff --git a/extensions/pagetop-user/src/handlers/admin/permissions.rs b/extensions/pagetop-user/src/handlers/admin/permissions.rs index d4d6d0bb..62e39abf 100644 --- a/extensions/pagetop-user/src/handlers/admin/permissions.rs +++ b/extensions/pagetop-user/src/handlers/admin/permissions.rs @@ -7,20 +7,16 @@ use pagetop::prelude::*; use crate::LOCALES_USER; -use crate::handlers::admin::frame; -use crate::permission::{self, UserPermission}; /// GET /admin/user/permissions - Catálogo de permisos agrupado. pub(crate) async fn list_get(request: HttpRequest) -> Result { - require_permission(&request, &UserPermission::AdminPermissions)?; + let page = Page::admin(request); - let mut page = Page::admin(request); + let registry = PermissionRegistry::global(); + let groups = registry.groups_sorted(page.context()); + let mut page = page.with_title(Lc::t("title-admin-permissions", &LOCALES_USER)); - let registry = permission::registry(); - let title = Lc::t("title-admin-permissions", &LOCALES_USER); - let mut content = frame(title.clone()); - - for (group, group_label) in registry.groups_sorted(page.context()) { + for (group, group_label) in groups { let mut table = Table::new().with_prop(PropsOp::add_classes("user-admin-table")); for permission in registry.by_group(group) { table = table.with_row( @@ -29,17 +25,12 @@ pub(crate) async fn list_get(request: HttpRequest) -> Result, ) -> Result { - require_permission(&request, &UserPermission::AdminRoles)?; - let params = RolePageParams { sort: RoleSortField::from_query(query.sort.as_deref()), dir: SortDir::from_query(query.dir.as_deref()), @@ -62,8 +60,8 @@ pub(crate) async fn list_get( } else { let title = Lc::t("title-admin-roles", &LOCALES_USER); Ok(Page::admin(request) - .with_title(title.clone()) - .with_child(frame(title).with_child(table)) + .with_title(title) + .with_child(table) .render() .await .into_response()) @@ -77,21 +75,17 @@ pub(crate) async fn new_get( request: HttpRequest, web::Query(waypoint): web::Query, ) -> Result { - require_permission(&request, &UserPermission::AdminRoles)?; - let mut page = Page::admin(request); - let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH)); + 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.clone()) + .with_title(title) .with_child( - frame(title) - .with_child( - RoleForm::new() - .with_mode(RoleFormMode::New) - .with_waypoint(waypoint), - ) - .with_child(back_link(back_href)), + RoleForm::new() + .with_mode(RoleFormMode::New) + .with_waypoint(waypoint), ) + .with_child(back_link(back_href)) .render() .await .into_response()) @@ -113,8 +107,6 @@ pub(crate) async fn new_post( web::Query(waypoint): web::Query, web::Form(form): web::Form, ) -> Result { - require_permission(&request, &UserPermission::AdminRoles)?; - let weight: i32 = form.weight.trim().parse().unwrap_or(0); let result = role_admin::create_role(role_admin::NewRoleData { @@ -128,12 +120,12 @@ pub(crate) async fn new_post( match result { Ok(_) => { let cx = Context::admin(request); - let target = waypoint.or(cx.route(ADMIN_ROLES_PATH)); + let target = waypoint.or(cx.route(ADMIN_ROLES_PATH.as_str())); Ok(Redirect::see_other(target).into_response()) } Err(err) => { - let mut page = Page::admin(request); - let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH)); + 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) @@ -144,12 +136,9 @@ pub(crate) async fn new_post( .with_waypoint(waypoint); let title = Lc::t("title-admin-role-new", &LOCALES_USER); Ok(page - .with_title(title.clone()) - .with_child( - frame(title) - .with_child(form_component) - .with_child(back_link(back_href)), - ) + .with_title(title) + .with_child(form_component) + .with_child(back_link(back_href)) .render() .await .into_response()) @@ -165,8 +154,6 @@ pub(crate) async fn edit_get( web::Path(id): web::Path, web::Query(waypoint): web::Query, ) -> Result { - require_permission(&request, &UserPermission::AdminRoles)?; - let role = match role_admin::find_role(id).await { Ok(role) => role, Err(_) => return Err(ErrorPage::NotFound(Some(request))), @@ -175,26 +162,23 @@ pub(crate) async fn edit_get( return Err(ErrorPage::AccessDenied(Some(request))); } - let mut page = Page::admin(request); - let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH)); + 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 - .with_title(title.clone()) + .with_title(title) .with_child( - frame(title) - .with_child( - RoleForm::new() - .with_mode(RoleFormMode::Edit) - .with_role_id(Some(id)) - .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_child(back_link(back_href)), + RoleForm::new() + .with_mode(RoleFormMode::Edit) + .with_role_id(Some(id)) + .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_child(back_link(back_href)) .render() .await .into_response()) @@ -216,8 +200,6 @@ pub(crate) async fn edit_post( web::Query(waypoint): web::Query, web::Form(form): web::Form, ) -> Result { - require_permission(&request, &UserPermission::AdminRoles)?; - let weight: i32 = form.weight.trim().parse().unwrap_or(0); let result = role_admin::update_role( @@ -233,7 +215,7 @@ pub(crate) async fn edit_post( match result { Ok(()) => { let cx = Context::admin(request); - let target = waypoint.or(cx.route(ADMIN_ROLES_PATH)); + let target = waypoint.or(cx.route(ADMIN_ROLES_PATH.as_str())); Ok(Redirect::see_other(target).into_response()) } Err(err) => { @@ -241,8 +223,8 @@ pub(crate) async fn edit_post( .await .map(|role| role.machine_name) .unwrap_or_default(); - let mut page = Page::admin(request); - let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH)); + 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)) @@ -254,12 +236,9 @@ pub(crate) async fn edit_post( .with_waypoint(waypoint); let title = Lc::t("title-admin-role-edit", &LOCALES_USER); Ok(page - .with_title(title.clone()) - .with_child( - frame(title) - .with_child(form_component) - .with_child(back_link(back_href)), - ) + .with_title(title) + .with_child(form_component) + .with_child(back_link(back_href)) .render() .await .into_response()) @@ -276,8 +255,6 @@ pub(crate) async fn view_get( web::Path(id): web::Path, web::Query(waypoint): web::Query, ) -> Result { - require_permission(&request, &UserPermission::AdminRoles)?; - let role = match role_admin::find_role(id).await { Ok(role) => role, Err(_) => return Err(ErrorPage::NotFound(Some(request))), @@ -289,19 +266,17 @@ pub(crate) async fn view_get( let mut page = Page::admin(request); let groups = build_permission_groups(&selected, page.context()); - let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH)); - let details_block = role_view_details(&role, page.context()).await; + let back_href = waypoint.or(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); - let mut content = frame(title.clone()).with_child(details_block); + let mut page = page.with_title(title).with_child(details_block); for group_block in role_view_permissions(&groups) { - content = content.with_child(group_block); + page = page.with_child(group_block); } - content = content.with_child(back_link(back_href)); Ok(page - .with_title(title) - .with_child(content) + .with_child(back_link(back_href)) .render() .await .into_response()) @@ -389,8 +364,6 @@ pub(crate) async fn delete_post( web::Path(id): web::Path, web::Query(query): web::Query, ) -> Result { - require_permission(&request, &UserPermission::AdminRoles)?; - let result = role_admin::delete_role(id).await; if request.is_htmx() { @@ -419,7 +392,7 @@ pub(crate) async fn delete_post( match result { Ok(()) => { let target = cx - .route(ADMIN_ROLES_PATH) + .route(ADMIN_ROLES_PATH.as_str()) .alter_param( "sort", RoleSortField::from_query(query.sort.as_deref()).as_str(), @@ -448,8 +421,6 @@ pub(crate) async fn delete_confirm_get( web::Path(id): web::Path, web::Query(query): web::Query, ) -> Result { - require_permission(&request, &UserPermission::AdminRoles)?; - let mut cx = Context::admin(request); let delete_href = cx .route(role_path(id, "delete")) @@ -473,7 +444,7 @@ pub(crate) async fn delete_confirm_get( // **< permissions_get / permissions_post >********************************************************* fn build_permission_groups(selected: &[String], cx: &Context) -> PermissionGroups { - let registry = permission::registry(); + let registry = PermissionRegistry::global(); registry .groups_sorted(cx) .into_iter() @@ -498,7 +469,6 @@ pub(crate) async fn permissions_get( web::Path(id): web::Path, web::Query(waypoint): web::Query, ) -> Result { - require_permission(&request, &UserPermission::AdminRoles)?; require_permission(&request, &UserPermission::AdminPermissions)?; if role_admin::find_role(id).await.is_err() { @@ -508,24 +478,21 @@ pub(crate) async fn permissions_get( Ok(keys) => keys, Err(_) => return Err(ErrorPage::InternalError(Some(request))), }; - let mut page = Page::admin(request); + let page = Page::admin(request); let groups = build_permission_groups(&selected, page.context()); - let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH)); + let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str())); let title = Lc::t("title-admin-role-permissions", &LOCALES_USER); Ok(page - .with_title(title.clone()) + .with_title(title) .with_child( - frame(title) - .with_child( - RolePermissionsForm::new() - .with_role_id(id) - .with_groups(groups) - .with_waypoint(waypoint), - ) - .with_child(back_link(back_href)), + RolePermissionsForm::new() + .with_role_id(id) + .with_groups(groups) + .with_waypoint(waypoint), ) + .with_child(back_link(back_href)) .render() .await .into_response()) @@ -547,7 +514,6 @@ pub(crate) async fn permissions_post( web::Query(waypoint): web::Query, raw: web::RawForm, ) -> Result { - require_permission(&request, &UserPermission::AdminRoles)?; require_permission(&request, &UserPermission::AdminPermissions)?; let Ok(form) = serde_qs::from_bytes::(&raw.0) else { @@ -557,14 +523,14 @@ pub(crate) async fn permissions_post( 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)); + let target = waypoint.or(cx.route(ADMIN_ROLES_PATH.as_str())); Ok(Redirect::see_other(target).into_response()) } Err(err) => { - let mut page = Page::admin(request); + let page = Page::admin(request); let groups = build_permission_groups(&form.permission_keys, page.context()); - let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH)); + let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str())); let form_component = RolePermissionsForm::new() .with_role_id(id) .with_groups(groups) @@ -572,12 +538,9 @@ pub(crate) async fn permissions_post( .with_waypoint(waypoint); let title = Lc::t("title-admin-role-permissions", &LOCALES_USER); Ok(page - .with_title(title.clone()) - .with_child( - frame(title) - .with_child(form_component) - .with_child(back_link(back_href)), - ) + .with_title(title) + .with_child(form_component) + .with_child(back_link(back_href)) .render() .await .into_response()) diff --git a/extensions/pagetop-user/src/handlers/admin/users.rs b/extensions/pagetop-user/src/handlers/admin/users.rs index 5614e1e7..b26b1386 100644 --- a/extensions/pagetop-user/src/handlers/admin/users.rs +++ b/extensions/pagetop-user/src/handlers/admin/users.rs @@ -15,7 +15,7 @@ use crate::component::user_details; use crate::config::SETTINGS; use crate::entity::{role, user}; use crate::error::AuthError; -use crate::handlers::admin::{back_link, frame, map_auth_error}; +use crate::handlers::admin::{back_link, map_auth_error}; use crate::mail::{Notice, send_notice}; use crate::password; use crate::permission::UserPermission; @@ -43,8 +43,6 @@ pub(crate) async fn list_get( request: HttpRequest, web::Query(query): web::Query, ) -> Result { - require_permission(&request, &UserPermission::AdminUsers)?; - let params = UserListParams { query: query.q.clone(), sort: UserSortField::from_query(query.sort.as_deref()), @@ -73,12 +71,9 @@ pub(crate) async fn list_get( } else { let title = Lc::t("title-admin-users", &LOCALES_USER); Ok(Page::admin(request) - .with_title(title.clone()) - .with_child( - frame(title) - .with_child(search_bar(query.q)) - .with_child(table), - ) + .with_title(title) + .with_child(search_bar(query.q)) + .with_child(table) .render() .await .into_response()) @@ -98,7 +93,7 @@ fn search_bar(current_query: Option) -> Html { name="q" value=(value.as_str()) placeholder=[Lc::t("field-search-users", &LOCALES_USER).lookup(cx)] - hx-get=(cx.route(ADMIN_USERS_PATH).to_string()) + 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) @@ -155,7 +150,6 @@ pub(crate) async fn new_get( request: HttpRequest, web::Query(waypoint): web::Query, ) -> Result { - require_permission(&request, &UserPermission::AdminUsers)?; let roles = match available_roles(&[]).await { Ok(roles) => roles, Err(_) => return Err(ErrorPage::InternalError(Some(request))), @@ -163,22 +157,19 @@ pub(crate) async fn new_get( // 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::().is_some_and(|a| a.is_admin()); - let mut page = Page::admin(request); - let back_href = waypoint.or(page.context().route(ADMIN_USERS_PATH)); + 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.clone()) + .with_title(title) .with_child( - frame(title) - .with_child( - UserForm::new() - .with_mode(UserFormMode::New) - .with_roles(roles) - .with_allow_admin_field(allow_admin_field) - .with_waypoint(waypoint), - ) - .with_child(back_link(back_href)), + UserForm::new() + .with_mode(UserFormMode::New) + .with_roles(roles) + .with_allow_admin_field(allow_admin_field) + .with_waypoint(waypoint), ) + .with_child(back_link(back_href)) .render() .await .into_response()) @@ -213,7 +204,6 @@ pub(crate) async fn new_post( web::Query(waypoint): web::Query, raw: web::RawForm, ) -> Result { - require_permission(&request, &UserPermission::AdminUsers)?; let Ok(form) = serde_qs::from_bytes::(&raw.0) else { return Err(ErrorPage::BadRequest(Some(request))); }; @@ -240,13 +230,13 @@ pub(crate) async fn new_post( match result { Ok(_) => { let cx = Context::admin(request); - let target = waypoint.or(cx.route(ADMIN_USERS_PATH)); + let target = waypoint.or(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 mut page = Page::admin(request); - let back_href = waypoint.or(page.context().route(ADMIN_USERS_PATH)); + 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) @@ -262,12 +252,9 @@ pub(crate) async fn new_post( .with_waypoint(waypoint); let title = Lc::t("title-admin-user-new", &LOCALES_USER); Ok(page - .with_title(title.clone()) - .with_child( - frame(title) - .with_child(form_component) - .with_child(back_link(back_href)), - ) + .with_title(title) + .with_child(form_component) + .with_child(back_link(back_href)) .render() .await .into_response()) @@ -331,7 +318,7 @@ 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.context().route(ADMIN_USERS_PATH)); + 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, @@ -340,20 +327,17 @@ async fn render_edit_page( can_toggle_admin, can_change_status, &waypoint, - page.context(), + page.context_mut(), ); - page.with_title(title.clone()) + page.with_title(title) .with_child( - frame(title) - .with_child( - form.with_mode(UserFormMode::Edit) - .with_user_id(Some(id)) - .with_waypoint(waypoint.clone()), - ) - .with_child(actions) - .with_child(back_link(back_href)), + form.with_mode(UserFormMode::Edit) + .with_user_id(Some(id)) + .with_waypoint(waypoint.clone()), ) + .with_child(actions) + .with_child(back_link(back_href)) .render() .await .into_response() @@ -451,7 +435,6 @@ pub(crate) async fn edit_get( web::Path(id): web::Path, web::Query(waypoint): web::Query, ) -> Result { - require_permission(&request, &UserPermission::AdminUsers)?; require_manageable(&request, id).await?; Ok(render_user_edit(request, id, None, waypoint).await) } @@ -483,7 +466,6 @@ pub(crate) async fn edit_post( web::Query(waypoint): web::Query, raw: web::RawForm, ) -> Result { - require_permission(&request, &UserPermission::AdminUsers)?; let user = require_manageable(&request, id).await?; let Ok(form) = serde_qs::from_bytes::(&raw.0) else { return Err(ErrorPage::BadRequest(Some(request))); @@ -510,7 +492,7 @@ pub(crate) async fn edit_post( match result { Ok(()) => { let cx = Context::admin(request); - let target = waypoint.or(cx.route(ADMIN_USERS_PATH)); + let target = waypoint.or(cx.route(ADMIN_USERS_PATH.as_str())); Ok(Redirect::see_other(target).into_response()) } Err(err) => { @@ -540,8 +522,6 @@ pub(crate) async fn view_get( web::Path(id): web::Path, web::Query(waypoint): web::Query, ) -> Result { - require_permission(&request, &UserPermission::AdminUsers)?; - let user = match user_admin::find_user(id).await { Ok(user) => user, Err(_) => return Err(ErrorPage::NotFound(Some(request))), @@ -552,19 +532,16 @@ pub(crate) async fn view_get( }; let mut page = Page::admin(request); - let back_href = waypoint.or(page.context().route(ADMIN_USERS_PATH)); - let details_block = user_details(&user, page.context()).await; - let roles_block = user_view_roles(&roles, user.is_admin, page.context()).await; + let back_href = waypoint.or(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; let title = Lc::t("title-admin-user-view", &LOCALES_USER); Ok(page - .with_title(title.clone()) - .with_child( - frame(title) - .with_child(details_block) - .with_child(roles_block) - .with_child(back_link(back_href)), - ) + .with_title(title) + .with_child(details_block) + .with_child(roles_block) + .with_child(back_link(back_href)) .render() .await .into_response()) @@ -645,7 +622,6 @@ pub(crate) async fn status_post( web::Query(waypoint): web::Query, web::Form(form): web::Form, ) -> Result { - require_permission(&request, &UserPermission::AdminUsers)?; require_permission(&request, &UserPermission::BlockAccounts)?; require_manageable(&request, id).await?; let Some(account) = request.extension::().cloned() else { @@ -731,23 +707,19 @@ pub(crate) async fn password_get( web::Path(id): web::Path, web::Query(waypoint): web::Query, ) -> Result { - require_permission(&request, &UserPermission::AdminUsers)?; let user = require_manageable(&request, id).await?; - let mut page = Page::admin(request); - let edit_href = waypoint.append_to(page.context().route(user_path(id, "edit"))); + 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.clone()) + .with_title(title) + .with_child(user_summary(&user)) .with_child( - frame(title) - .with_child(user_summary(&user)) - .with_child( - AdminPasswordForm::new() - .with_user_id(id) - .with_waypoint(waypoint), - ) - .with_child(back_link(edit_href)), + AdminPasswordForm::new() + .with_user_id(id) + .with_waypoint(waypoint), ) + .with_child(back_link(edit_href)) .render() .await .into_response()) @@ -767,7 +739,6 @@ pub(crate) async fn password_post( web::Query(waypoint): web::Query, web::Form(form): web::Form, ) -> Result { - require_permission(&request, &UserPermission::AdminUsers)?; let user = require_manageable(&request, id).await?; let result = match password::passwords_match(&form.password, &form.confirm_password) { @@ -783,22 +754,19 @@ pub(crate) async fn password_post( Ok(Redirect::see_other(edit_href).into_response()) } Err(err) => { - let mut page = Page::admin(request); - let edit_href = waypoint.append_to(page.context().route(user_path(id, "edit"))); + 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.clone()) + .with_title(title) + .with_child(user_summary(&user)) .with_child( - frame(title) - .with_child(user_summary(&user)) - .with_child( - AdminPasswordForm::new() - .with_user_id(id) - .with_error(map_auth_error(&err)) - .with_waypoint(waypoint), - ) - .with_child(back_link(edit_href)), + AdminPasswordForm::new() + .with_user_id(id) + .with_error(map_auth_error(&err)) + .with_waypoint(waypoint), ) + .with_child(back_link(edit_href)) .render() .await .into_response()) diff --git a/extensions/pagetop-user/src/lib.rs b/extensions/pagetop-user/src/lib.rs index 1cc080f4..6a4025f4 100644 --- a/extensions/pagetop-user/src/lib.rs +++ b/extensions/pagetop-user/src/lib.rs @@ -15,8 +15,8 @@ Añade cuentas de usuario a una aplicación PageTop: registro, inicio de sesión con sesiones en la base de datos, perfil propio, recuperación de contraseña y verificación del email por correo, y control de acceso con roles y permisos. Incluye las páginas de administración de usuarios, roles y -permisos sobre `pagetop-admin`, hechas sólo con componentes del núcleo para que funcionen con -cualquier tema. +permisos en el panel de administración del núcleo, hechas sólo con componentes del núcleo para que +funcionen con cualquier tema. ## Sobre PageTop @@ -48,9 +48,11 @@ admin_email = "admin@example.com" # Sin 'admin_password', se genera una aleatoria y se muestra una sola vez al crearlo. ``` -**Comprueba los permisos** en tus *handlers*. El usuario actual se inyecta automáticamente en el -contexto de cada [`Page`] al crearla con [`Page::new()`], y las funciones del núcleo, como -[`has_permission()`], lo consultan: +**Protege tus rutas** con su acceso (`Access`): PageTop lo comprueba antes de llegar al *handler* +con los permisos que concede esta extensión, y a un usuario anónimo sin acceso le ofrece el inicio +de sesión. Dentro del *handler*, el usuario actual está en el contexto de cada [`Page`] al crearla +con [`Page::new()`], y funciones del núcleo como [`has_permission()`] lo consultan para las +comprobaciones más concretas: ```rust,no_run use pagetop::prelude::*; @@ -77,15 +79,16 @@ impl Extension for MyApp { vec![&pagetop_user::User] } - fn configure_router(&self, router: Router) -> Router { - router.route("/dashboard", web::get(dashboard)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.route( + "/dashboard", + Access::Permission(&MyPermission::SeeDashboard), + web::get(dashboard), + ) } } async fn dashboard(request: HttpRequest) -> Result { - if !has_permission(&request, &MyPermission::SeeDashboard) { - return Err(ErrorPage::NotFound(Some(request))); - } Page::new(request) .with_child(Html::with(|_| html! { h1 { "Panel" } })) .render().await @@ -159,9 +162,10 @@ ninguna. Detrás de un *proxy* inverso, los límites por IP requieren configurar */ use pagetop::prelude::*; -use pagetop_admin::prelude::*; use pagetop_seaorm::install_migrations; +use std::sync::LazyLock; + pub mod account; pub mod config; pub mod error; @@ -187,7 +191,6 @@ pub mod component; include_locales!(LOCALES_USER); pub use account::{Account, UserStatus}; -pub use permission::{DeclarePermissions, PermissionRegistry}; /// Prelude de `pagetop-user`. pub mod prelude { @@ -195,7 +198,7 @@ pub mod prelude { pub use crate::component::UserName; pub use crate::component::{AccountMenu, account_menu}; pub use crate::error::AuthError; - pub use crate::{Account, DeclarePermissions, UserStatus}; + pub use crate::{Account, UserStatus}; } // **< Rutas HTTP (fijas) >************************************************************************* @@ -236,15 +239,20 @@ const PASSWORD_RESET_PATH: &str = "/user/password/reset"; // POST - la confirma. const VERIFY_PATH: &str = "/user/verify"; -// **< Rutas de administración (fijas) >************************************************************ +// **< Rutas de administración >******************************************************************** + +// Relativas a la raíz del panel de administración, como se declaran sus páginas, y completas (ver +// `admin_path()`), para montar las rutas y enlazar. // Listado, alta, edición, asignación de roles, bloqueo/activación y restablecimiento de contraseña // de usuarios. -const ADMIN_USERS_PATH: &str = "/admin/user/users"; +const ADMIN_USERS: &str = "user/users"; +static ADMIN_USERS_PATH: LazyLock = LazyLock::new(|| admin_path(ADMIN_USERS)); // Listado, alta, edición, eliminación y asignación de permisos de roles. -const ADMIN_ROLES_PATH: &str = "/admin/user/roles"; +const ADMIN_ROLES: &str = "user/roles"; +static ADMIN_ROLES_PATH: LazyLock = LazyLock::new(|| admin_path(ADMIN_ROLES)); // Catálogo de permisos registrados, agrupado por extensión (solo lectura). -const ADMIN_PERMISSIONS_PATH: &str = "/admin/user/permissions"; +const ADMIN_PERMISSIONS: &str = "user/permissions"; // Ruta del perfil público del usuario `id`: `{PROFILE_PATH}/{id}`. fn profile_path(id: i32) -> String { @@ -253,48 +261,49 @@ fn profile_path(id: i32) -> String { // Ruta de una acción sobre el usuario `id`: `{ADMIN_USERS_PATH}/{id}/{tail}`. fn user_path(id: i32, tail: &str) -> String { - util::join!(ADMIN_USERS_PATH, "/", id.to_string(), "/", tail) + util::join!(ADMIN_USERS_PATH.as_str(), "/", id.to_string(), "/", tail) } // Ruta de una acción sobre el rol `id`: `{ADMIN_ROLES_PATH}/{id}/{tail}`. fn role_path(id: i32, tail: &str) -> String { - util::join!(ADMIN_ROLES_PATH, "/", id.to_string(), "/", tail) + util::join!(ADMIN_ROLES_PATH.as_str(), "/", id.to_string(), "/", tail) } -// **< Registro en pagetop-admin (fijo) >*********************************************************** +// **< Páginas del panel de administración >******************************************************** -// Registra las páginas de usuarios, roles y permisos en el portal de `pagetop-admin`, bajo la -// sección integrada "people". Las rutas y sus handlers ya están registrados en -// `configure_router()`; este registro sólo aporta el metadato (título, sección, permiso) para que -// aparezcan en la portada `/admin`. -fn declare_admin_pages(bag: &mut PageBag) { - bag.add(AdminPage { - path: ADMIN_USERS_PATH.to_owned(), - section: "people".to_owned(), - title: Lc::t("title-admin-users", &LOCALES_USER), - description: Some(Lc::t("description-admin-users", &LOCALES_USER)), - weight: 0, - permission: &permission::UserPermission::AdminUsers, - kind: AdminPageKind::View, - }); - bag.add(AdminPage { - path: ADMIN_ROLES_PATH.to_owned(), - section: "people".to_owned(), - title: Lc::t("title-admin-roles", &LOCALES_USER), - description: Some(Lc::t("description-admin-roles", &LOCALES_USER)), - weight: 10, - permission: &permission::UserPermission::AdminRoles, - kind: AdminPageKind::View, - }); - bag.add(AdminPage { - path: ADMIN_PERMISSIONS_PATH.to_owned(), - section: "people".to_owned(), - title: Lc::t("title-admin-permissions", &LOCALES_USER), - description: Some(Lc::t("description-admin-permissions", &LOCALES_USER)), - weight: 20, - permission: &permission::UserPermission::AdminPermissions, - kind: AdminPageKind::View, - }); +// Declara las páginas de usuarios, roles y permisos en el panel de administración, bajo la sección +// integrada "people". Las rutas y sus handlers ya están registrados en `configure_router()`; esta +// declaración sólo aporta el metadato (título, sección, permiso) para que aparezcan en el panel. +fn declare_admin_pages(bag: &mut AdminPageBag) { + bag.add( + AdminPage::new( + ADMIN_USERS, + "people", + Lc::t("title-admin-users", &LOCALES_USER), + &permission::UserPermission::AdminUsers, + ) + .with_description(Lc::t("description-admin-users", &LOCALES_USER)), + ); + bag.add( + AdminPage::new( + ADMIN_ROLES, + "people", + Lc::t("title-admin-roles", &LOCALES_USER), + &permission::UserPermission::AdminRoles, + ) + .with_description(Lc::t("description-admin-roles", &LOCALES_USER)) + .with_weight(10), + ); + bag.add( + AdminPage::new( + ADMIN_PERMISSIONS, + "people", + Lc::t("title-admin-permissions", &LOCALES_USER), + &permission::UserPermission::AdminPermissions, + ) + .with_description(Lc::t("description-admin-permissions", &LOCALES_USER)) + .with_weight(20), + ); } // **< Roles de sistema (fijos) >******************************************************************* @@ -344,7 +353,6 @@ impl Extension for User { fn dependencies(&self) -> Vec { vec![ - &pagetop_admin::Admin, &pagetop_seaorm::SeaORM, &pagetop_htmx::Htmx, &pagetop_mail::Mail, @@ -354,11 +362,13 @@ impl Extension for User { fn actions(&self) -> Vec { actions![ // Comprueba permisos mediante el modelo RBAC almacenado en BD. - CheckPermission::new(middleware::check_rbac_permission), + action::auth::CheckPermission::new(middleware::check_rbac_permission), + // Ofrece el inicio de sesión a un usuario anónimo sin acceso a una ruta. + action::auth::AnonymousDenied::new(handlers::account::offer_login), // Registra los permisos propios de pagetop-user. - DeclarePermissions::new(permission::declare_builtin_permissions), - // Registra las páginas de usuarios, roles y permisos en el portal de pagetop-admin. - DeclareAdminPages::new(declare_admin_pages), + action::auth::DeclarePermissions::new(permission::declare_builtin_permissions), + // Declara las páginas de usuarios, roles y permisos en el panel de administración. + action::admin::DeclareAdminPages::new(declare_admin_pages), // Declara las vistas previas de los correos de recuperación y verificación. pagetop_mail::DeclareMailPreviews::new(mail::declare_previews), ] @@ -373,7 +383,6 @@ impl Extension for User { m20260629_000005_create_sessions, m20260629_000006_create_user_tokens, )?; - permission::build_registry(); // Los permisos de "anonymous" en memoria sobreviven a una nueva preparación en el mismo // proceso (las pruebas lo hacen), que puede usar otra base de datos. session::invalidate_anonymous_permissions(); @@ -383,113 +392,123 @@ impl Extension for User { Ok(()) } - fn configure_router(&self, router: Router) -> Router { - router - .route( + fn configure_router(&self, routes: Routes) -> Routes { + let edit_own_profile = Access::Permission(&permission::UserPermission::EditOwnProfile); + let change_own_password = + Access::Permission(&permission::UserPermission::ChangeOwnPassword); + routes + .public_route( LOGIN_PATH, web::get(handlers::auth::login_get).post(handlers::auth::login_post), ) - .route(LOGOUT_PATH, web::post(handlers::auth::logout_post)) - .route( + .public_route(LOGOUT_PATH, web::post(handlers::auth::logout_post)) + .public_route( REGISTER_PATH, web::get(handlers::auth::register_get).post(handlers::auth::register_post), ) - .route(PROFILE_PATH, web::get(handlers::account::profile_get)) .route( + PROFILE_PATH, + Access::Authenticated, + web::get(handlers::account::profile_get), + ) + .public_route( &format!("{}/{{id}}", PROFILE_PATH), web::get(handlers::account::public_profile_get), ) .route( PROFILE_EDIT_PATH, + edit_own_profile, web::get(handlers::account::profile_edit_get) .post(handlers::account::profile_edit_post), ) .route( PROFILE_PASSWORD_PATH, + change_own_password, web::get(handlers::account::password_get).post(handlers::account::password_post), ) .route( EMAIL_PATH, + edit_own_profile, web::get(handlers::account::email_get).post(handlers::account::email_post), ) - .route( + .public_route( &format!("{}/{{uid}}/{{token}}", EMAIL_PATH), web::get(handlers::account::email_confirm_get) .post(handlers::account::email_confirm_post), ) - .route( + .public_route( PASSWORD_RESET_PATH, web::get(handlers::auth::password_reset_get) .post(handlers::auth::password_reset_post), ) - .route( + .public_route( &format!("{}/{{uid}}/{{token}}", PASSWORD_RESET_PATH), web::get(handlers::auth::password_reset_confirm_get) .post(handlers::auth::password_reset_confirm_post), ) - .route( + .public_route( &format!("{}/{{uid}}/{{token}}", VERIFY_PATH), web::get(handlers::auth::verify_email_get).post(handlers::auth::verify_email_post), ) - .route(ADMIN_USERS_PATH, web::get(handlers::admin::users::list_get)) - .route( - &format!("{}/new", ADMIN_USERS_PATH), + .admin_route(ADMIN_USERS, 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), ) - .route( - &format!("{}/{{id}}/edit", ADMIN_USERS_PATH), + .admin_route( + &format!("{ADMIN_USERS}/{{id}}/edit"), web::get(handlers::admin::users::edit_get).post(handlers::admin::users::edit_post), ) - .route( - &format!("{}/{{id}}/view", ADMIN_USERS_PATH), + .admin_route( + &format!("{ADMIN_USERS}/{{id}}/view"), web::get(handlers::admin::users::view_get), ) - .route( - &format!("{}/{{id}}/status", ADMIN_USERS_PATH), + .admin_route( + &format!("{ADMIN_USERS}/{{id}}/status"), web::post(handlers::admin::users::status_post), ) - .route( - &format!("{}/{{id}}/admin", ADMIN_USERS_PATH), + .admin_route( + &format!("{ADMIN_USERS}/{{id}}/admin"), web::post(handlers::admin::users::admin_post), ) - .route( - &format!("{}/{{id}}/password", ADMIN_USERS_PATH), + .admin_route( + &format!("{ADMIN_USERS}/{{id}}/password"), web::get(handlers::admin::users::password_get) .post(handlers::admin::users::password_post), ) - .route(ADMIN_ROLES_PATH, web::get(handlers::admin::roles::list_get)) - .route( - &format!("{}/new", ADMIN_ROLES_PATH), + .admin_route(ADMIN_ROLES, 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), ) - .route( - &format!("{}/{{id}}/edit", ADMIN_ROLES_PATH), + .admin_route( + &format!("{ADMIN_ROLES}/{{id}}/edit"), web::get(handlers::admin::roles::edit_get).post(handlers::admin::roles::edit_post), ) - .route( - &format!("{}/{{id}}/view", ADMIN_ROLES_PATH), + .admin_route( + &format!("{ADMIN_ROLES}/{{id}}/view"), web::get(handlers::admin::roles::view_get), ) - .route( - &format!("{}/{{id}}/delete", ADMIN_ROLES_PATH), + .admin_route( + &format!("{ADMIN_ROLES}/{{id}}/delete"), web::post(handlers::admin::roles::delete_post), ) - .route( - &format!("{}/{{id}}/delete/confirm", ADMIN_ROLES_PATH), + .admin_route( + &format!("{ADMIN_ROLES}/{{id}}/delete/confirm"), web::get(handlers::admin::roles::delete_confirm_get), ) - .route( - &format!("{}/{{id}}/permissions", ADMIN_ROLES_PATH), + .admin_route( + &format!("{ADMIN_ROLES}/{{id}}/permissions"), web::get(handlers::admin::roles::permissions_get) .post(handlers::admin::roles::permissions_post), ) - .route( - ADMIN_PERMISSIONS_PATH, + .admin_route( + ADMIN_PERMISSIONS, web::get(handlers::admin::permissions::list_get), ) } - fn configure_middleware(&self, router: Router) -> Router { - router.layer(web::middleware::from_fn(middleware::session_middleware)) + fn configure_middleware(&self, layers: Layers) -> Layers { + layers.layer(web::middleware::from_fn(middleware::session_middleware)) } } diff --git a/extensions/pagetop-user/src/middleware.rs b/extensions/pagetop-user/src/middleware.rs index 20c4672f..778d9e88 100644 --- a/extensions/pagetop-user/src/middleware.rs +++ b/extensions/pagetop-user/src/middleware.rs @@ -67,7 +67,8 @@ pub(crate) async fn session_middleware( // **< check_rbac_permission >********************************************************************** -/// Handler de la acción [`pagetop::auth::CheckPermission`] para el modelo RBAC de `pagetop-user`. +/// Handler de la acción [`CheckPermission`](pagetop::base::action::auth::CheckPermission) para el +/// modelo RBAC de `pagetop-user`. /// /// Lee el [`Account`] inyectado por el middleware de sesión desde las extensiones de la petición /// HTTP y concede el permiso si el account lo tiene (un administrador lo tiene concedido siempre, diff --git a/extensions/pagetop-user/src/permission.rs b/extensions/pagetop-user/src/permission.rs index 8dc7f444..644433e5 100644 --- a/extensions/pagetop-user/src/permission.rs +++ b/extensions/pagetop-user/src/permission.rs @@ -1,161 +1,12 @@ -//! Catálogo de permisos en memoria y acción `DeclarePermissions`. +//! Permisos propios de `pagetop-user`. //! -//! El catálogo se construye una sola vez durante `Extension::initialize()` a partir de -//! las acciones `DeclarePermissions` registradas por todas las extensiones. Los permisos -//! otorgados a cada rol se persisten en la tabla `role_permissions`; la definición -//! de qué permisos existen vive únicamente en memoria. - -use std::sync::OnceLock; +//! Se declaran en el catálogo de permisos de PageTop ([`PermissionRegistry`]) como los de cualquier +//! otra extensión. Los permisos concedidos a cada rol se guardan en la tabla `role_permissions`. use pagetop::prelude::*; use crate::LOCALES_USER; -// **< DeclarePermissions >************************************************************************* - -/// Acción que las extensiones dispatcean para registrar sus permisos en el catálogo. -/// -/// Cada extensión añade una instancia `DeclarePermissions::new(fn)` en `Extension::actions()`. -/// Durante `initialize()`, [`build_registry()`] despacha todas las instancias registradas -/// y construye el catálogo global. -/// -/// `label()`, `group()` y `group_label()` los aporta el propio [`Permission`] registrado -/// (con implementación por defecto si la extensión no los sobrecarga). -/// -/// # Ejemplo -/// -/// ```rust,no_run -/// # use pagetop::prelude::*; -/// # use pagetop_user::permission::{DeclarePermissions, PermissionRegistry}; -/// #[derive(Clone, Copy, Debug)] -/// enum MyPermission { -/// DoSomething, -/// } -/// -/// impl Permission for MyPermission { -/// fn key(&self) -> CowStr { -/// match self { -/// Self::DoSomething => "myext:do_something".into(), -/// } -/// } -/// } -/// -/// fn my_permissions(registry: &mut PermissionRegistry) { -/// registry.register(&MyPermission::DoSomething); -/// } -/// // En Extension::actions(): -/// // DeclarePermissions::new(my_permissions) -/// ``` -pub struct DeclarePermissions { - pub(crate) handler: fn(&mut PermissionRegistry), -} - -impl DeclarePermissions { - pub fn new(handler: fn(&mut PermissionRegistry)) -> Self { - DeclarePermissions { handler } - } - - /// Despacha todas las acciones `DeclarePermissions` registradas construyendo el catálogo. - pub(crate) fn dispatch(registry: &mut PermissionRegistry) { - dispatch_actions(|action: &Self| (action.handler)(registry)); - } -} - -impl ActionDispatcher for DeclarePermissions {} - -// **< PermissionRegistry >************************************************************************* - -/// Catálogo mutable de permisos, construido durante la fase de inicialización. -/// -/// Se construye una sola vez con un conjunto de entradas que conserva el orden de registro sin -/// estructuras adicionales. La UI de administración no usa ese orden de registro. Llama a -/// [`groups_sorted()`](Self::groups_sorted), que lo reordena alfabéticamente para cada petición -/// según el idioma activo. -#[derive(AutoDefault)] -pub struct PermissionRegistry { - permissions: Vec, - /// `(identificador de grupo, título traducible)`, en orden de primer registro. - groups: Vec<(&'static str, Lc)>, -} - -impl PermissionRegistry { - /// Registra un permiso. Se ignora si ya está registrado. - pub fn register(&mut self, perm: PermissionRef) { - let group = perm.group(); - if !self.groups.iter().any(|(g, _)| *g == group) { - self.groups.push((group, perm.group_label())); - } - if !self.has(perm) { - self.permissions.push(perm); - } - } - - /// Comprueba si un permiso está en el catálogo. - pub fn has(&self, perm: PermissionRef) -> bool { - self.permissions.iter().any(|p| p.key() == perm.key()) - } - - /// Comprueba si una clave textual (p. ej. procedente de un formulario) corresponde a un - /// permiso del catálogo. - pub fn has_key(&self, key: &str) -> bool { - self.permissions.iter().any(|p| p.key().as_ref() == key) - } - - pub fn all(&self) -> impl Iterator + '_ { - self.permissions.iter().copied() - } - - /// Grupos en orden de primer registro, sin traducir ni ordenar alfabéticamente. - /// - /// Listado de bajo nivel sobre el que se apoya [`groups_sorted()`](Self::groups_sorted); úsalo - /// en su lugar sólo cuando el orden de registro sea justo lo que se necesita (por ejemplo, para - /// inspeccionar el catálogo en pruebas). - pub fn groups(&self) -> &[(&'static str, Lc)] { - &self.groups - } - - /// Grupos ordenados alfabéticamente por su título traducido al idioma del contexto, no sensible - /// a mayúsculas y, en general, a los acentos (ver [`Lc::collation_key()`] para el criterio - /// exacto y sus límites). - pub fn groups_sorted(&self, cx: &Context) -> Vec<&(&'static str, Lc)> { - let mut groups: Vec<_> = self - .groups - .iter() - .map(|g| (g.1.collation_key(cx), g)) - .collect(); - groups.sort_by(|a, b| a.0.cmp(&b.0)); - groups.into_iter().map(|(_, g)| g).collect() - } - - pub fn by_group<'a>(&'a self, group: &'a str) -> impl Iterator + 'a { - self.permissions - .iter() - .copied() - .filter(move |p| p.group() == group) - } -} - -// **< Catálogo global >**************************************************************************** - -static PERMISSIONS: OnceLock = OnceLock::new(); - -/// Construye y almacena el catálogo global de permisos ejecutando todas las acciones -/// `DeclarePermissions` registradas. Se llama exactamente una vez desde `initialize()`. -pub fn build_registry() { - let mut registry = PermissionRegistry::default(); - DeclarePermissions::dispatch(&mut registry); - let _ = PERMISSIONS.set(registry); -} - -/// Devuelve el catálogo global ya construido. -/// -/// Entra en pánico si se llama antes de `build_registry()`. -pub fn registry() -> &'static PermissionRegistry { - PERMISSIONS - .get() - .expect("permission registry not initialized") -} - // **< Permisos integrados de pagetop-user >******************************************************** /// Permisos propios de `pagetop-user`. diff --git a/extensions/pagetop-user/src/service/role_admin.rs b/extensions/pagetop-user/src/service/role_admin.rs index 13966f5e..33581b56 100644 --- a/extensions/pagetop-user/src/service/role_admin.rs +++ b/extensions/pagetop-user/src/service/role_admin.rs @@ -10,7 +10,6 @@ use pagetop_seaorm::db::{ use crate::entity::{role, role_permission, user_role}; use crate::error::AuthError; -use crate::permission; use crate::session; // **< listado >************************************************************************************ @@ -283,7 +282,7 @@ pub(crate) async fn set_role_permissions( ) -> Result<(), AuthError> { find_role(role_id).await?; - let registry = permission::registry(); + let registry = PermissionRegistry::global(); for key in permission_keys { if !registry.has_key(key) { return Err(AuthError::UnknownPermission(key.clone())); diff --git a/extensions/pagetop-user/tests/flows.rs b/extensions/pagetop-user/tests/flows.rs index e71c8630..fb75a76d 100644 --- a/extensions/pagetop-user/tests/flows.rs +++ b/extensions/pagetop-user/tests/flows.rs @@ -197,6 +197,7 @@ async fn account_flows() { password_resets_are_limited_by_account(&client).await; requests_are_limited_by_address(&client).await; failed_logins_are_limited_by_address(&client).await; + anonymous_visitors_are_offered_to_sign_in(&client).await; } async fn registration_requires_confirming_the_address(client: &Client) { @@ -797,3 +798,34 @@ async fn failed_logins_are_limited_by_address(client: &Client) { .await; assert_eq!(reply.status, Status::SEE_OTHER); } + +// A route that needs a session or a permission sends an anonymous visitor to the login form, which +// returns to that route afterwards. An HTMX request gets the same login as a full-page redirect, +// returning to the page open in the browser, instead of the form inside the fragment it expected. +async fn anonymous_visitors_are_offered_to_sign_in(client: &Client) { + let reply = client.get("/user/edit?tab=1", None).await; + assert_eq!(reply.status, Status::SEE_OTHER); + assert_eq!( + reply.location(), + "/user/login?waypoint=%2Fuser%2Fedit%3Ftab%3D1" + ); + // A public profile checks its permission in the handler, with the same answer. + let reply = client.get("/user/1", None).await; + assert_eq!(reply.status, Status::SEE_OTHER); + assert_eq!(reply.location(), "/user/login?waypoint=%2Fuser%2F1"); + + let request = web::test::TestRequest::get() + .uri("/admin/user/users?page=2") + .header("hx-request", "true") + .header( + "hx-current-url", + "http://localhost:8080/admin/user/users?sort=name", + ); + let reply = client.send(request).await; + assert_eq!(reply.status, Status::OK); + assert!(reply.body.is_empty(), "{}", reply.body); + assert_eq!( + reply.header("hx-redirect"), + "/user/login?waypoint=%2Fadmin%2Fuser%2Fusers%3Fsort%3Dname" + ); +} diff --git a/helpers/pagetop-build/README.md b/helpers/pagetop-build/README.md index ddae072a..ac12fd6c 100644 --- a/helpers/pagetop-build/README.md +++ b/helpers/pagetop-build/README.md @@ -98,9 +98,9 @@ pub struct MyExtension; #[async_trait] impl Extension for MyExtension { - fn configure_static_files(&self, router: Router) -> Router { - serve_static_files!(router, ["./static/css", app_css] => "/public/css"); - router + fn configure_static_files(&self, files: StaticFiles) -> StaticFiles { + serve_static_files!(files, ["./static/css", app_css] => "/public/css"); + files } } ``` diff --git a/helpers/pagetop-build/src/lib.rs b/helpers/pagetop-build/src/lib.rs index dd4a3b21..0a6b1415 100644 --- a/helpers/pagetop-build/src/lib.rs +++ b/helpers/pagetop-build/src/lib.rs @@ -99,9 +99,9 @@ pub struct MyExtension; #[async_trait] impl Extension for MyExtension { - fn configure_static_files(&self, router: Router) -> Router { - serve_static_files!(router, ["./static/css", app_css] => "/public/css"); - router + fn configure_static_files(&self, files: StaticFiles) -> StaticFiles { + serve_static_files!(files, ["./static/css", app_css] => "/public/css"); + files } } ``` diff --git a/src/admin.rs b/src/admin.rs new file mode 100644 index 00000000..625ff7d7 --- /dev/null +++ b/src/admin.rs @@ -0,0 +1,138 @@ +//! Panel de administración: secciones, páginas, pestañas y botones para las extensiones. +//! +//! Cada extensión aporta sus piezas con las acciones de [`action::admin`] +//! ([`DeclareAdminSections`], [`DeclareAdminPages`], [`DeclareAdminTasks`] y +//! [`DeclareAdminActions`]), sin depender de ninguna otra extensión. PageTop las reúne al arrancar +//! en un registro ([`AdminRegistry`]), que no cambia después. +//! +//! Todas las rutas se declaran **relativas** a la raíz del panel, el ajuste +//! [`admin_path`](crate::global::AppSettings::admin_path) (*"/admin"* por defecto): +//! `"config/site"` es la página `/admin/config/site`. [`admin_path()`] devuelve la ruta completa, +//! para enlazar; los *handlers* se montan en [`Extension::configure_router()`] con +//! [`Routes::admin_route()`], que también recibe la ruta relativa. +//! +//! Si hay alguna página declarada, PageTop monta en la raíz del panel su página de inicio +//! (*dashboard*), con todas las secciones y sus páginas, y en la ruta de cada sección con páginas, +//! una página con las suyas (salvo que una página declarada ocupe esa misma ruta). Las páginas de +//! administración se crean con [`Page::admin()`], cuya plantilla añade la navegación del panel, +//! las migas de pan, el título y las pestañas y botones declarados para cada ruta. +//! +//! Cada página declara un permiso ([`Permission`]), el único sitio donde se indica: decide si se +//! muestra en la navegación y protege sus rutas. Éstas se montan con [`Routes::admin_route()`], que +//! exige el permiso de la página de la que cuelgan (`"config/export/{id}/edit"` cuelga de +//! `"config/export"`) antes de llegar al *handler*; una ruta del panel montada de otra forma, o que +//! no cuelgue de ninguna página, impide arrancar la aplicación. Un permiso más concreto lo +//! comprueba el *handler*. Sin una extensión de autenticación que conceda los permisos (ver +//! [`CheckPermission`]), nadie puede acceder a ninguna. +//! +//! # Ejemplo +//! +//! ```rust,no_run +//! use pagetop::prelude::*; +//! +//! #[derive(Clone, Copy, Debug)] +//! enum ToolsPermission { +//! Export, +//! } +//! +//! impl Permission for ToolsPermission { +//! fn key(&self) -> CowStr { +//! match self { +//! Self::Export => "tools:export".into(), +//! } +//! } +//! } +//! +//! fn declare_pages(bag: &mut AdminPageBag) { +//! bag.add( +//! AdminPage::new("config/export", "config", Lc::n("Export"), &ToolsPermission::Export) +//! .with_description(Lc::n("Export site data.")), +//! ); +//! } +//! +//! // PageTop ya ha comprobado el permiso de la página antes de llegar aquí. +//! async fn export(request: HttpRequest) -> Result { +//! Page::admin(request) +//! .with_title(Lc::n("Export")) +//! .render() +//! .await +//! } +//! +//! pub struct Tools; +//! +//! #[async_trait] +//! impl Extension for Tools { +//! fn actions(&self) -> Vec { +//! actions![action::admin::DeclareAdminPages::new(declare_pages)] +//! } +//! +//! fn configure_router(&self, routes: Routes) -> Routes { +//! routes.admin_route("config/export", web::get(export)) +//! } +//! } +//! ``` +//! +//! [`Extension::configure_router()`]: crate::core::extension::Extension::configure_router +//! [`Page::admin()`]: crate::response::Page::admin +//! [`Permission`]: crate::auth::Permission +//! [`CheckPermission`]: crate::base::action::auth::CheckPermission +//! [`Routes::admin_route()`]: crate::web::Routes::admin_route +//! [`action::admin`]: crate::base::action::admin +//! [`DeclareAdminSections`]: crate::base::action::admin::DeclareAdminSections +//! [`DeclareAdminPages`]: crate::base::action::admin::DeclareAdminPages +//! [`DeclareAdminTasks`]: crate::base::action::admin::DeclareAdminTasks +//! [`DeclareAdminActions`]: crate::base::action::admin::DeclareAdminActions + +use crate::core::component::Context; +use crate::{global, util}; + +mod bag; +pub use bag::{AdminActionBag, AdminPageBag, AdminSectionBag, AdminTaskBag}; + +mod registry; +pub use registry::{AdminAction, AdminPage, AdminRegistry, AdminSection, AdminTask}; +pub(crate) use registry::{build_admin_registry, undeclared_permission}; + +mod pages; +pub(crate) use pages::configure_routes; + +/// Devuelve la ruta completa de una ruta relativa a la raíz del panel de administración. +/// +/// Con la raíz por defecto, `admin_path("config/site")` devuelve `"/admin/config/site"` y +/// `admin_path("")`, la propia raíz (`"/admin"`). Se ignoran las `/` del principio y del final. +pub fn admin_path(path: &str) -> String { + let root = &global::SETTINGS.app.admin_path; + let path = path.trim_matches('/'); + if path.is_empty() { + root.clone() + } else { + util::join!(root, "/", path) + } +} + +/// Devuelve la ruta relativa a la raíz del panel de administración de una ruta completa. +/// +/// Devuelve `None` si no está dentro del panel. Es la inversa de [`admin_path()`]: con la raíz por +/// defecto, `"/admin/config/site"` devuelve `Some("config/site")`, `"/admin"` devuelve `Some("")` y +/// `"/administrator"`, `None`. +pub fn strip_admin_path(path: &str) -> Option<&str> { + let rest = path.strip_prefix(global::SETTINGS.app.admin_path.as_str())?; + if rest.is_empty() { + Some(rest) + } else { + rest.strip_prefix('/') + .map(|rest| rest.trim_end_matches('/')) + } +} + +/// Devuelve `true` si el usuario de la petición puede acceder a alguna página del panel. +/// +/// Permite a una extensión (p. ej. un menú de cuenta) ofrecer el enlace al panel sólo cuando +/// procede. +pub fn can_access_admin(cx: &Context) -> bool { + let registry = AdminRegistry::global(); + registry + .pages() + .iter() + .any(|page| registry.section(page.section()).is_some() && page.is_accessible(cx)) +} diff --git a/src/admin/bag.rs b/src/admin/bag.rs new file mode 100644 index 00000000..014176dc --- /dev/null +++ b/src/admin/bag.rs @@ -0,0 +1,57 @@ +use super::{AdminAction, AdminPage, AdminSection, AdminTask}; + +/// Bolsa de secciones para [`DeclareAdminSections`]. +/// +/// [`DeclareAdminSections`]: crate::base::action::admin::DeclareAdminSections +pub struct AdminSectionBag { + pub(super) sections: Vec, +} + +impl AdminSectionBag { + /// Añade una sección al registro. + pub fn add(&mut self, section: AdminSection) { + self.sections.push(section); + } +} + +/// Bolsa de páginas para [`DeclareAdminPages`]. +/// +/// [`DeclareAdminPages`]: crate::base::action::admin::DeclareAdminPages +pub struct AdminPageBag { + pub(super) pages: Vec, +} + +impl AdminPageBag { + /// Añade una página al registro. + pub fn add(&mut self, page: AdminPage) { + self.pages.push(page); + } +} + +/// Bolsa de tareas para [`DeclareAdminTasks`]. +/// +/// [`DeclareAdminTasks`]: crate::base::action::admin::DeclareAdminTasks +pub struct AdminTaskBag { + pub(super) tasks: Vec, +} + +impl AdminTaskBag { + /// Añade una tarea local al registro. + pub fn add(&mut self, task: AdminTask) { + self.tasks.push(task); + } +} + +/// Bolsa de acciones locales para [`DeclareAdminActions`]. +/// +/// [`DeclareAdminActions`]: crate::base::action::admin::DeclareAdminActions +pub struct AdminActionBag { + pub(super) actions: Vec, +} + +impl AdminActionBag { + /// Añade una acción local al registro. + pub fn add(&mut self, action: AdminAction) { + self.actions.push(action); + } +} diff --git a/src/admin/pages.rs b/src/admin/pages.rs new file mode 100644 index 00000000..2deee864 --- /dev/null +++ b/src/admin/pages.rs @@ -0,0 +1,119 @@ +use crate::prelude::*; + +// **< Rutas >************************************************************************************** + +// Monta el inicio del panel (*dashboard*) y la página de cada sección con páginas declaradas, sólo +// si hay alguna. Una sección cuya ruta reclama una página declarada no se monta: esa página la +// monta su extensión y gana. Una ruta se monta una sola vez (montarla dos veces detendría el +// arranque): si dos secciones la comparten, sirve la primera por peso. +pub(crate) fn configure_routes(router: Router) -> Router { + let registry = AdminRegistry::global(); + if registry.pages().is_empty() { + return router; + } + let mut router = router.route(&admin_path(""), web::get(dashboard)); + let mut mounted = std::collections::BTreeSet::new(); + for section in registry.sections() { + if section.path().is_empty() + || registry.page(section.path()).is_some() + || registry.pages_for_section(section.key()).is_empty() + || !mounted.insert(section.path()) + { + continue; + } + router = router.route(&admin_path(section.path()), web::get(section_page)); + } + router +} + +// **< Dashboard >********************************************************************************** + +// Inicio del panel: todas las secciones con las páginas a las que puede acceder el usuario. Si no +// puede acceder a ninguna, se le deniega el acceso como en cualquier otra ruta. +async fn dashboard(request: HttpRequest) -> Response { + let page = Page::admin(request.clone()); + let sections = AdminRegistry::global().sections(); + let Some(content) = sections_with_pages(page.context(), sections) else { + return deny_access(request); + }; + page.with_title(Lc::l("admin_dashboard")) + .with_child(content) + .render() + .await + .into_response() +} + +// **< Sección >************************************************************************************ + +// Página de una sección: sus páginas a las que puede acceder el usuario. Si no puede acceder a +// ninguna, se le deniega el acceso como en cualquier otra ruta. +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(); + }; + + let page = Page::admin(request.clone()); + let Some(content) = sections_with_pages(page.context(), std::slice::from_ref(section)) else { + return deny_access(request); + }; + page.with_title(section.title().clone()) + .with_child(content) + .render() + .await + .into_response() +} + +// **< Listado de secciones >*********************************************************************** + +// Secciones con sus páginas (título y descripción) a las que puede acceder el usuario, o `None` si +// no queda ninguna. +fn sections_with_pages(cx: &Context, candidates: &'static [AdminSection]) -> Option { + let registry = AdminRegistry::global(); + let visible: Vec<_> = candidates + .iter() + .map(|section| { + let pages: Vec<_> = registry + .pages_for_section(section.key()) + .iter() + .filter(|p| p.is_accessible(cx)) + .collect(); + (section, pages) + }) + .filter(|(_, pages)| !pages.is_empty()) + .collect(); + if visible.is_empty() { + return None; + } + let mut sections = Container::new().with_prop(PropsOp::add_classes("admin-dashboard-sections")); + for (section, pages) in visible { + sections = sections.with_child( + Container::new() + .with_prop(PropsOp::add_classes("admin-dashboard-section")) + .with_child(Html::with(move |cx| { + html! { + h2 class="admin-dashboard-section-title" { + a href=(cx.route(admin_path(section.path()))) { + (section.title().using(cx)) + } + } + ul class="admin-dashboard-section-links" { + @for page in &pages { + li class="admin-dashboard-link" { + a href=(cx.route(admin_path(page.path()))) { + (page.title().using(cx)) + } + @if !page.description().is_none() { + span class="admin-dashboard-link-desc" { + " - " (page.description().using(cx)) + } + } + } + } + } + } + })), + ); + } + Some(sections) +} diff --git a/src/admin/registry.rs b/src/admin/registry.rs new file mode 100644 index 00000000..37f64093 --- /dev/null +++ b/src/admin/registry.rs @@ -0,0 +1,755 @@ +use crate::auth::{PermissionRef, PermissionRegistry, has_permission}; +use crate::base::action::admin::{ + DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks, +}; +use crate::core::component::{Context, Contextual}; +use crate::locale::Lc; +use crate::{Getters, Weight, builder_impl, trace, util}; + +use super::bag::{AdminActionBag, AdminPageBag, AdminSectionBag, AdminTaskBag}; + +use std::collections::BTreeMap; +use std::ops::Range; +use std::sync::OnceLock; + +// **< AdminSection >******************************************************************************* + +/// Sección del panel de administración (agrupa páginas en la navegación y en el *dashboard*). +/// +/// Una sección no tiene permiso propio: se muestra a quien pueda acceder a alguna de sus páginas, y +/// se oculta si no le queda ninguna. Una sección declarada con la misma clave que otra anterior la +/// sustituye. +/// +/// ```rust +/// # use pagetop::prelude::*; +/// let section = AdminSection::new("tools", Lc::n("Tools")).with_weight(35); +/// assert_eq!(section.path(), "tools"); +/// ``` +#[derive(Clone, Getters)] +pub struct AdminSection { + /// Devuelve el identificador único de la sección (p. ej. `"config"`). + key: String, + /// Devuelve la ruta de la sección, relativa a la raíz del panel (p. ej. `"config"`). + path: String, + /// Devuelve el título visible en la navegación. + title: Lc, + /// Devuelve el peso para ordenar las secciones (menor = antes). + #[getters(copy)] + weight: Weight, +} + +#[builder_impl] +impl AdminSection { + /// Crea una sección con su clave y su título. Su ruta es la propia clave y su peso, 0. + pub fn new(key: impl Into, title: Lc) -> Self { + let key = key.into(); + AdminSection { + path: relative(key.clone()), + key, + title, + weight: 0, + } + } + + // **< AdminSection BUILDER >******************************************************************* + + /// Establece la ruta de la sección, relativa a la raíz del panel, si no es la propia clave. + pub fn with_path(mut self, path: impl Into) -> Self { + self.path = relative(path.into()); + self + } + + /// Establece el título de la sección. + pub fn with_title(mut self, title: Lc) -> Self { + self.title = title; + self + } + + /// Establece el peso de la sección. + pub fn with_weight(mut self, weight: Weight) -> Self { + self.weight = weight; + self + } +} + +// **< AdminPage >********************************************************************************** + +/// Página del panel de administración. +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// # struct ToolsPermission; +/// # impl Permission for ToolsPermission { +/// # fn key(&self) -> CowStr { "tools:export".into() } +/// # } +/// let page = AdminPage::new("config/export", "config", Lc::n("Export"), &ToolsPermission) +/// .with_description(Lc::n("Export site data.")); +/// ``` +#[derive(Clone, Getters)] +pub struct AdminPage { + /// Devuelve la ruta de la página, relativa a la raíz del panel (p. ej. `"config/site"`). + path: String, + /// Devuelve la clave de la sección a la que pertenece. + section: String, + /// Devuelve el título visible en la navegación y en el encabezado de la página. + title: Lc, + /// Devuelve la descripción breve para el *dashboard* y las páginas de sección, o + /// [`Lc::none()`] si no tiene. + description: Lc, + /// Devuelve el peso dentro de la sección (menor = antes). + #[getters(copy)] + weight: Weight, + /// Devuelve el permiso requerido para acceder a la página: decide si se muestra en la + /// navegación, y si se muestra su sección, y lo exigen su ruta y las que cuelgan de ella + /// ([`Routes::admin_route()`](crate::web::Routes::admin_route)). + #[getters(copy)] + permission: PermissionRef, +} + +#[builder_impl] +impl AdminPage { + /// Crea una página con su ruta relativa a la raíz del panel, la clave de su sección, su título + /// y el permiso para acceder a ella. No tiene descripción y su peso es 0. + /// + /// La ruta no puede quedar vacía, porque la raíz del panel es el *dashboard*: una página sin + /// ruta no se registra y se avisa al arrancar. + pub fn new( + path: impl Into, + section: impl Into, + title: Lc, + permission: PermissionRef, + ) -> Self { + AdminPage { + path: relative(path.into()), + section: section.into(), + title, + description: Lc::none(), + weight: 0, + permission, + } + } + + // **< AdminPage BUILDER >********************************************************************** + + /// Establece el título de la página. + pub fn with_title(mut self, title: Lc) -> Self { + self.title = title; + self + } + + /// Establece la descripción breve de la página. + pub fn with_description(mut self, description: Lc) -> Self { + self.description = description; + self + } + + /// Establece el peso de la página dentro de su sección. + pub fn with_weight(mut self, weight: Weight) -> Self { + self.weight = weight; + self + } + + // **< AdminPage GETTERS >********************************************************************** + + /// Devuelve `true` si el usuario actual puede acceder a esta página. + /// + /// Sirve para decidir qué se muestra; las rutas de la página ya exigen su permiso (ver el + /// [módulo](crate::admin)). + pub fn is_accessible(&self, cx: &Context) -> bool { + cx.request() + .is_some_and(|request| has_permission(request, self.permission)) + } +} + +// **< AdminTask >********************************************************************************** + +/// Tarea (pestaña) local dentro de una página de administración. +/// +/// Las pestañas de una página se muestran en ella y en la ruta de cada una, con la de la ruta +/// actual activa. La pestaña cuya ruta es la de la propia página es la activa al entrar en ella. +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// let all = AdminTask::new("config/export", "config/export", Lc::n("All")); +/// let csv = AdminTask::new("config/export/csv", "config/export", Lc::n("CSV")).with_weight(1); +/// ``` +#[derive(Clone, Getters)] +pub struct AdminTask { + /// Devuelve la ruta de la tarea, relativa a la raíz del panel. + path: String, + /// Devuelve la ruta de la página padre, relativa a la raíz del panel. + parent_path: String, + /// Devuelve la etiqueta de la pestaña. + title: Lc, + /// Devuelve el peso de la pestaña (menor = antes). + #[getters(copy)] + weight: Weight, + /// Devuelve el permiso requerido para mostrar la pestaña (`None` = se muestra a quien vea la + /// página padre). Su ruta sólo exige el permiso de la página de la que cuelga; si la pestaña + /// pide otro, lo comprueba su *handler*. + #[getters(copy)] + permission: Option, +} + +#[builder_impl] +impl AdminTask { + /// Crea una pestaña con su ruta y la de su página padre, ambas relativas a la raíz del panel, + /// y su etiqueta. Su peso es 0 y se muestra a quien vea la página padre. + pub fn new(path: impl Into, parent_path: impl Into, title: Lc) -> Self { + AdminTask { + path: relative(path.into()), + parent_path: relative(parent_path.into()), + title, + weight: 0, + permission: None, + } + } + + // **< AdminTask BUILDER >********************************************************************** + + /// Establece la etiqueta de la pestaña. + pub fn with_title(mut self, title: Lc) -> Self { + self.title = title; + self + } + + /// Establece el peso de la pestaña. + pub fn with_weight(mut self, weight: Weight) -> Self { + self.weight = weight; + self + } + + /// Establece el permiso requerido para mostrar la pestaña. + pub fn with_permission(mut self, permission: PermissionRef) -> Self { + self.permission = Some(permission); + self + } +} + +// **< AdminAction >******************************************************************************** + +/// Acción local (botón de acción) en una página de administración. +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// let add = AdminAction::new("config/export/new", "config/export", Lc::n("Add export")); +/// ``` +#[derive(Clone, Getters)] +pub struct AdminAction { + /// Devuelve la ruta de destino de la acción, relativa a la raíz del panel. + url: String, + /// Devuelve la ruta de la página en la que aparece el botón, relativa a la raíz del panel. + for_path: String, + /// Devuelve la etiqueta del botón. + title: Lc, + /// Devuelve el peso del botón (menor = antes). + #[getters(copy)] + weight: Weight, + /// Devuelve el permiso requerido para mostrar el botón (`None` = se muestra a quien vea la + /// página). Su ruta de destino sólo exige el permiso de la página de la que cuelga; si el botón + /// pide otro, lo comprueba su *handler*. + #[getters(copy)] + permission: Option, +} + +#[builder_impl] +impl AdminAction { + /// Crea un botón con su ruta de destino y la de la página en la que aparece, ambas relativas a + /// la raíz del panel, y su etiqueta. Su peso es 0 y se muestra a quien vea la página. + pub fn new(url: impl Into, for_path: impl Into, title: Lc) -> Self { + AdminAction { + url: relative(url.into()), + for_path: relative(for_path.into()), + title, + weight: 0, + permission: None, + } + } + + // **< AdminAction BUILDER >******************************************************************** + + /// Establece la etiqueta del botón. + pub fn with_title(mut self, title: Lc) -> Self { + self.title = title; + self + } + + /// Establece el peso del botón. + pub fn with_weight(mut self, weight: Weight) -> Self { + self.weight = weight; + self + } + + /// Establece el permiso requerido para mostrar el botón. + pub fn with_permission(mut self, permission: PermissionRef) -> Self { + self.permission = Some(permission); + self + } +} + +// **< AdminRegistry >****************************************************************************** + +/// Registro del panel de administración, construido una sola vez al arrancar. +/// +/// Reúne lo que declaran las extensiones con las acciones de +/// [`action::admin`](crate::base::action::admin), con todas las rutas relativas a la raíz del +/// panel. Las listas se ordenan por peso al construirlo. +pub struct AdminRegistry { + // Por peso. + sections: Vec, + // Agrupadas por clave de sección y, en cada una, por peso. + pages: Vec, + // Posición en `pages` de cada página, por su ruta. + page_index: BTreeMap, + // Páginas de cada sección en `pages`, por clave de sección. + section_pages: BTreeMap>, + // Por ruta de la página padre y, en cada una, por peso. + tasks: BTreeMap>, + // Por ruta de la página y, en cada una, por peso. + actions: BTreeMap>, +} + +static REGISTRY: OnceLock = OnceLock::new(); + +static EMPTY_REGISTRY: AdminRegistry = AdminRegistry { + sections: Vec::new(), + pages: Vec::new(), + page_index: BTreeMap::new(), + section_pages: BTreeMap::new(), + tasks: BTreeMap::new(), + actions: BTreeMap::new(), +}; + +impl AdminRegistry { + /// Devuelve el registro global del panel de administración. + /// + /// Fuera de una aplicación, o antes de que ésta registre las acciones de sus extensiones, + /// devuelve un registro vacío. + pub fn global() -> &'static AdminRegistry { + REGISTRY.get().unwrap_or(&EMPTY_REGISTRY) + } + + /// Devuelve las secciones ordenadas por peso. + pub fn sections(&self) -> &[AdminSection] { + &self.sections + } + + /// Devuelve la sección con la clave indicada. + pub fn section(&self, key: &str) -> Option<&AdminSection> { + self.sections.iter().find(|s| s.key == key) + } + + // Sección con la ruta indicada; si varias la comparten, la primera por peso. + pub(crate) fn section_by_path(&self, path: &str) -> Option<&AdminSection> { + self.sections.iter().find(|s| s.path == path) + } + + /// Devuelve todas las páginas, agrupadas por la clave de su sección y, en cada grupo, ordenadas + /// por peso. + pub fn pages(&self) -> &[AdminPage] { + &self.pages + } + + /// Devuelve la página declarada con la ruta indicada, relativa a la raíz del panel. + pub fn page(&self, path: &str) -> Option<&AdminPage> { + self.page_index.get(path).map(|&i| &self.pages[i]) + } + + /// Devuelve las páginas de una sección ordenadas por peso. + pub fn pages_for_section(&self, section_key: &str) -> &[AdminPage] { + self.section_pages + .get(section_key) + .map_or(&[], |range| &self.pages[range.clone()]) + } + + /// Devuelve las tareas de una página ordenadas por peso. + pub fn tasks_for(&self, path: &str) -> &[AdminTask] { + self.tasks.get(path).map_or(&[], Vec::as_slice) + } + + /// Devuelve las acciones de una página ordenadas por peso. + pub fn actions_for(&self, path: &str) -> &[AdminAction] { + self.actions.get(path).map_or(&[], Vec::as_slice) + } + + // Página declarada que corresponde a la ruta, o la más cercana que la contiene (`"user/users"` + // para `"user/users/5/edit"`). + pub(crate) fn nearest_page(&self, path: &str) -> Option<&AdminPage> { + let mut candidate = path; + loop { + if let Some(page) = self.page(candidate) { + return Some(page); + } + candidate = candidate.rsplit_once('/')?.0; + } + } + + // Pestaña declarada con la ruta indicada. + pub(crate) fn task(&self, path: &str) -> Option<&AdminTask> { + self.tasks.values().flatten().find(|t| t.path == path) + } + + // Construye el registro con lo declarado, en orden de declaración, y devuelve también los + // avisos de las páginas que no se registran tal cual. Una sección con la clave de otra anterior + // la sustituye, y una página con la ruta de otra anterior, también. Una página sin ruta se + // descarta: la raíz del panel es el *dashboard*, y montar ahí su ruta impediría arrancar. + fn new( + sections: Vec, + pages: Vec, + tasks: Vec, + actions: Vec, + ) -> (Self, Vec) { + let mut warnings = Vec::new(); + + let mut by_key = BTreeMap::new(); + for s in sections { + by_key.insert(s.key.clone(), s); + } + let mut sections: Vec<_> = by_key.into_values().collect(); + sections.sort_by_key(|s| s.weight); + + let mut by_path = BTreeMap::new(); + for p in pages { + if p.path.is_empty() { + warnings.push(format!( + "An admin page of the section \"{}\" has an empty path, ignored: the root of \ + the panel is the dashboard", + p.section + )); + continue; + } + if let Some(previous) = by_path.insert(p.path.clone(), p) { + warnings.push(format!( + "Admin page \"{}\" is declared more than once; the last declaration wins", + previous.path + )); + } + } + let mut pages: Vec<_> = by_path.into_values().collect(); + pages.sort_by(|a, b| a.section.cmp(&b.section).then(a.weight.cmp(&b.weight))); + let mut page_index = BTreeMap::new(); + let mut section_pages: BTreeMap> = BTreeMap::new(); + for (i, p) in pages.iter().enumerate() { + page_index.insert(p.path.clone(), i); + section_pages + .entry(p.section.clone()) + .and_modify(|range| range.end = i + 1) + .or_insert(i..i + 1); + } + + let registry = AdminRegistry { + sections, + pages, + page_index, + section_pages, + tasks: grouped(tasks, |t| &t.parent_path, |t| t.weight), + actions: grouped(actions, |a| &a.for_path, |a| a.weight), + }; + (registry, warnings) + } +} + +// Agrupa por la clave y ordena cada grupo por peso, conservando el orden de declaración entre los +// del mismo peso. +fn grouped( + items: Vec, + key: impl Fn(&T) -> &String, + weight: impl Fn(&T) -> Weight, +) -> BTreeMap> { + let mut groups: BTreeMap> = BTreeMap::new(); + for item in items { + groups.entry(key(&item).clone()).or_default().push(item); + } + for group in groups.values_mut() { + group.sort_by_key(&weight); + } + groups +} + +// **< Construcción del registro >****************************************************************** + +// Construye el registro despachando las acciones de declaración, después de las secciones +// habituales para que una extensión pueda sustituirlas con la misma clave. Se llama al arrancar, +// justo después de registrar las acciones de las extensiones; si ya está construido (p. ej. por +// otra llamada a `Application::prepare()` en el mismo proceso, como hacen las pruebas), no hace +// nada. +pub(crate) fn build_admin_registry() { + REGISTRY.get_or_init(|| { + let mut section_bag = AdminSectionBag { + sections: default_sections(), + }; + DeclareAdminSections::dispatch(&mut section_bag); + let mut page_bag = AdminPageBag { pages: Vec::new() }; + DeclareAdminPages::dispatch(&mut page_bag); + let mut task_bag = AdminTaskBag { tasks: Vec::new() }; + DeclareAdminTasks::dispatch(&mut task_bag); + let mut action_bag = AdminActionBag { + actions: Vec::new(), + }; + DeclareAdminActions::dispatch(&mut action_bag); + + let (registry, mut warnings) = AdminRegistry::new( + section_bag.sections, + page_bag.pages, + task_bag.tasks, + action_bag.actions, + ); + warnings.extend(check_references(®istry)); + warnings.extend(check_permissions(®istry, PermissionRegistry::global())); + for warning in warnings { + trace::warn!("{warning}"); + } + registry + }); +} + +// Avisos de las referencias por texto que no llevan a nada: la pieza no se mostraría y nada lo +// indicaría. Una sección declarada dos veces no se avisa, porque sustituir una es lo previsto; sí +// dos secciones con la misma ruta, porque sólo la primera por peso tendría página. +fn check_references(registry: &AdminRegistry) -> Vec { + let mut warnings = Vec::new(); + let mut section_paths: BTreeMap<&str, &str> = BTreeMap::new(); + for section in ®istry.sections { + let first = *section_paths.entry(§ion.path).or_insert(§ion.key); + if first != section.key { + warnings.push(format!( + "Admin sections \"{first}\" and \"{}\" share the path \"{}\", only the first is \ + shown on it", + section.key, section.path + )); + } + } + for page in ®istry.pages { + if registry.section(&page.section).is_none() { + warnings.push(format!( + "Admin page \"{}\" belongs to the unknown section \"{}\", not shown", + page.path, page.section + )); + } + } + for (parent, tasks) in ®istry.tasks { + if registry.page(parent).is_none() { + for task in tasks { + warnings.push(format!( + "Admin task \"{}\" belongs to the undeclared page \"{parent}\", not shown", + task.path + )); + } + } + } + for (for_path, actions) in ®istry.actions { + if registry.page(for_path).is_none() && registry.task(for_path).is_none() { + for action in actions { + warnings.push(format!( + "Admin action \"{}\" is for the undeclared page \"{for_path}\", not shown", + action.url + )); + } + } + } + warnings +} + +// Avisos de los permisos que exigen las páginas, pestañas y botones del panel sin estar en el +// catálogo: ninguna extensión de autenticación podría ofrecerlos para concederlos, y la pieza sólo +// la vería quien tenga todos los permisos. Uno por permiso, con todo lo que lo exige. +fn check_permissions(registry: &AdminRegistry, catalog: &PermissionRegistry) -> Vec { + let mut missing: BTreeMap> = BTreeMap::new(); + let mut check = |perm: PermissionRef, piece: String| { + if !catalog.has(perm) { + missing + .entry(perm.key().into_owned()) + .or_default() + .push(piece); + } + }; + let mut pages: Vec<_> = registry.pages.iter().collect(); + pages.sort_by_key(|p| &p.path); + for page in pages { + check(page.permission, util::join!("page \"", &page.path, "\"")); + } + for task in registry.tasks.values().flatten() { + if let Some(perm) = task.permission { + check(perm, util::join!("task \"", &task.path, "\"")); + } + } + for action in registry.actions.values().flatten() { + if let Some(perm) = action.permission { + check(perm, util::join!("action \"", &action.url, "\"")); + } + } + missing + .into_iter() + .map(|(key, pieces)| undeclared_permission(&key, &pieces)) + .collect() +} + +// Aviso de un permiso que no está en el catálogo, compartido con las rutas de `Routes`. +pub(crate) fn undeclared_permission(key: &str, required_by: &[String]) -> String { + format!( + "Permission \"{key}\" is not declared with DeclarePermissions, so no authentication \ + extension can offer it to be granted (required by {})", + required_by.join(", ") + ) +} + +// Ruta relativa sin `/` al principio ni al final, la forma en que se guardan y se buscan. +fn relative(path: String) -> String { + let trimmed = path.trim_matches('/'); + if trimmed.len() == path.len() { + path + } else { + trimmed.to_owned() + } +} + +// Secciones habituales del panel, declaradas antes que las de las extensiones. +fn default_sections() -> Vec { + [ + ("people", "admin_section_people", 10), + ("structure", "admin_section_structure", 20), + ("config", "admin_section_config", 30), + ("reports", "admin_section_reports", 40), + ("help", "admin_section_help", 50), + ] + .into_iter() + .map(|(key, title, weight)| AdminSection::new(key, Lc::l(title)).with_weight(weight)) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::CowStr; + use crate::auth::Permission; + + struct AnyPermission; + + impl Permission for AnyPermission { + fn key(&self) -> CowStr { + "test:any".into() + } + } + + struct OtherPermission; + + impl Permission for OtherPermission { + fn key(&self) -> CowStr { + "test:other".into() + } + } + + fn page(path: &str, section: &str) -> AdminPage { + AdminPage::new(path, section, Lc::n("Page"), &AnyPermission) + } + + fn task(path: &str, parent_path: &str) -> AdminTask { + AdminTask::new(path, parent_path, Lc::n("Task")) + } + + fn action(url: &str, for_path: &str) -> AdminAction { + AdminAction::new(url, for_path, Lc::n("Action")) + } + + #[test] + fn duplicated_pages_and_pages_without_path_are_reported() { + let (registry, warnings) = AdminRegistry::new( + default_sections(), + vec![ + page("config/site", "config"), + page("config/site", "config").with_weight(5), + page("/", "config"), + ], + vec![], + vec![], + ); + assert_eq!(warnings.len(), 2, "{warnings:?}"); + assert!(warnings[0].contains("\"config/site\" is declared more than once")); + assert!(warnings[1].contains("\"config\" has an empty path, ignored")); + assert_eq!(registry.page("config/site").unwrap().weight(), 5); + assert!(registry.page("").is_none()); + } + + #[test] + fn lists_are_sorted_by_weight_once() { + let (registry, _) = AdminRegistry::new( + default_sections(), + vec![ + page("config/b", "config").with_weight(2), + page("people/a", "people"), + page("config/a", "config").with_weight(1), + page("config/c", "config").with_weight(1), + ], + vec![ + task("config/a/y", "config/a").with_weight(1), + task("config/a/x", "config/a"), + ], + vec![], + ); + let paths = |pages: &[AdminPage]| pages.iter().map(|p| p.path.clone()).collect::>(); + assert_eq!( + paths(registry.pages_for_section("config")), + ["config/a", "config/c", "config/b"] + ); + assert_eq!(paths(registry.pages_for_section("people")), ["people/a"]); + assert!(registry.pages_for_section("help").is_empty()); + assert_eq!(registry.page("config/b").unwrap().weight(), 2); + let tasks: Vec<_> = registry + .tasks_for("config/a") + .iter() + .map(|t| t.path()) + .collect(); + assert_eq!(tasks, ["config/a/x", "config/a/y"]); + } + + #[test] + fn references_to_undeclared_pieces_are_reported() { + let mut sections = default_sections(); + sections.push(AdminSection::new("settings", Lc::n("Settings")).with_path("config")); + let (registry, _) = AdminRegistry::new( + sections, + vec![page("config/site", "config"), page("tools/x", "tools")], + vec![ + task("config/site/advanced", "config/site"), + task("config/sit/typo", "config/sit"), + ], + vec![ + action("config/site/new", "config/site"), + action("config/site/advanced/new", "config/site/advanced"), + action("config/other/new", "config/other"), + ], + ); + + let warnings = check_references(®istry); + assert_eq!(warnings.len(), 4, "{warnings:?}"); + assert!(warnings[0].contains("\"settings\" and \"config\" share the path \"config\"")); + assert!(warnings[1].contains("\"tools/x\" belongs to the unknown section \"tools\"")); + assert!(warnings[2].contains("\"config/sit/typo\" belongs to the undeclared page")); + assert!(warnings[3].contains("\"config/other/new\" is for the undeclared page")); + } + + #[test] + fn permissions_missing_from_the_catalog_are_reported_once_each() { + let (registry, _) = AdminRegistry::new( + vec![], + vec![ + page("config/site", "config"), + page("config/other", "config"), + ], + vec![task("config/site/advanced", "config/site").with_permission(&OtherPermission)], + vec![], + ); + + let mut catalog = PermissionRegistry::default(); + catalog.register(&AnyPermission); + catalog.register(&OtherPermission); + assert!(check_permissions(®istry, &catalog).is_empty()); + + let warnings = check_permissions(®istry, &PermissionRegistry::default()); + assert_eq!(warnings.len(), 2, "{warnings:?}"); + assert!(warnings[0].contains("\"test:any\" is not declared with DeclarePermissions")); + assert!(warnings[0].contains("page \"config/other\", page \"config/site\"")); + assert!(warnings[1].contains("\"test:other\"")); + assert!(warnings[1].contains("task \"config/site/advanced\"")); + } +} diff --git a/src/app.rs b/src/app.rs index ac356c6a..1dd9eeda 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2,6 +2,7 @@ mod figfont; +use crate::admin; use crate::core::extension; use crate::core::extension::ExtensionRef; use crate::core::extension::all::StartupError; @@ -221,7 +222,10 @@ impl Application { let std_listener = std::net::TcpListener::bind(&addr)?; std_listener.set_nonblocking(true)?; - let router = Self::build_router(); + let router = match Self::build_router() { + Ok(router) => router, + Err(err) => Self::abort_startup(self.tracing.take(), err), + }; // Con el puerto ya enlazado, arranca los servicios en segundo plano de las extensiones. if let Err(err) = extension::all::start_extensions().await { @@ -242,8 +246,13 @@ impl Application { } /// Devuelve el servidor web configurado para usarlo en pruebas de integración. + /// + /// # Panics + /// + /// Si alguna ruta del panel de administración está mal montada (ver + /// [`Routes`](crate::web::Routes)), que con [`run()`](Self::run) detendría el arranque. pub fn test(self) -> Router { - Self::build_router() + Self::build_router().unwrap_or_else(|err| panic!("{err}")) } // Construye el router con las rutas, el middleware y los archivos estáticos de todas las @@ -256,6 +265,10 @@ impl Application { // cambio, se registra antes: la página 404 debe ver lo que el middleware añade a la petición // (p. ej. el usuario actual). // + // Cada ruta comprueba su acceso (`web::Routes`) después de pasar por el middleware de las + // extensiones, cuando éste ya ha resuelto el usuario actual. Si alguna ruta del panel de + // administración está mal montada, se devuelve un error y la aplicación no arranca. + // // Los mensajes *flash* (`keep_flash_messages()`) se registran junto al middleware de las // extensiones, también antes de los archivos estáticos, que no los muestran. // @@ -268,16 +281,17 @@ impl Application { // Las capas de páginas de error y `CatchPanicLayer` cubren todo, porque se añaden al final. Con // `CatchPanicLayer` en la última capa se capturan incluso los `panic!` que se produzcan dentro // del propio renderizado de una página de error. - fn build_router() -> Router { - let router = extension::all::configure_routes(Router::new()).fallback(route_not_found); + fn build_router() -> Result { + let router = extension::all::configure_routes(Router::new())?; + let router = admin::configure_routes(router).fallback(route_not_found); let router = extension::all::configure_middleware(router) .layer(axum::middleware::from_fn(keep_flash_messages)); let router = extension::all::configure_static_files(router); - router + Ok(router .layer(axum::middleware::from_fn(reject_cross_origin)) .layer(axum::middleware::from_fn(limit_body)) .layer(axum::middleware::from_fn(render_error_pages)) - .layer(CatchPanicLayer::custom(response_for_panic)) + .layer(CatchPanicLayer::custom(response_for_panic))) } } diff --git a/src/auth.rs b/src/auth.rs index 6a9fdc67..43e49cd2 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -3,10 +3,19 @@ //! Define el tipo [`CurrentUser`] que PageTop inyecta en el [`Context`] con la información mínima //! sobre el usuario que ejecuta la petición actual ([`HttpRequest`]). //! -//! Incluye la acción [`CheckPermission`] para que las extensiones puedan implementar sus propios -//! modelos de permisos. Y también las funciones auxiliares [`has_permission()`] y -//! [`require_permission()`] para validar en el comienzo de cada handler, antes de construir ni -//! ejecutar nada, si la petición está autorizada. +//! Las extensiones se conectan con este sistema mediante las acciones de [`action::auth`]: con +//! [`CheckPermission`] implementan su propio modelo de permisos. Define también [`Access`], el +//! acceso con el que se monta cada ruta: PageTop lo comprueba antes de llegar al *handler* y +//! responde a quien no lo cumple con [`deny_access()`], la página de acceso denegado (403). A un +//! usuario anónimo le ofrece en su lugar el inicio de sesión sólo si una extensión de autenticación +//! lo prepara con [`AnonymousDenied`]. Dentro del *handler*, [`has_permission()`] y +//! [`require_permission()`] sirven para lo que el acceso de la ruta no expresa: mostrar u ocultar +//! partes de la página, o exigir un permiso más concreto. +//! +//! Las extensiones declaran además sus permisos con la acción [`DeclarePermissions`], y PageTop los +//! reúne al arrancar en un catálogo ([`PermissionRegistry`]) para que una extensión de +//! autenticación pueda mostrarlos, por ejemplo, en una pantalla de asignación de permisos a roles. +//! El catálogo sólo dice qué permisos existen; a quién se conceden lo decide la extensión. //! //! La resolución concreta del usuario (sesión en BD, LDAP, OAuth, ...) y la lógica de permisos //! (RBAC, grupos LDAP, ...) son responsabilidad de las extensiones de autenticación. Un concepto @@ -15,16 +24,18 @@ //! [`CheckPermission`]. //! //! [`Context`]: crate::core::component::Context +//! [`action::auth`]: crate::base::action::auth -use crate::core::action::{ActionDispatcher, try_dispatch_actions}; +use crate::base::action::auth::{AnonymousDenied, CheckPermission, DeclarePermissions}; +use crate::core::component::Context; use crate::core::theme::{ThemeRef, theme_by_short_name}; use crate::datetime::{Timezone, Tz}; use crate::locale::{LanguageIdentifier, Lc, Locale}; use crate::response::ErrorPage; -use crate::web::HttpRequest; -use crate::{AutoDefault, CowStr, Getters, Weight, builder_impl, global}; +use crate::web::{HttpRequest, IntoResponse, Response}; +use crate::{AutoDefault, CowStr, Getters, builder_impl, global}; -use std::ops::ControlFlow; +use std::sync::OnceLock; // **< CurrentUser >******************************************************************************** @@ -202,8 +213,8 @@ pub trait Permission: Send + Sync { /// Descripción breve para humanos (p. ej. en una pantalla de asignación de permisos a roles). /// - /// Por defecto devuelve la propia clave; una extensión que registre sus permisos en un catálogo - /// visible debería sobrescribirlo con un texto traducible. + /// Por defecto devuelve la propia clave; una extensión que declare sus permisos en el catálogo + /// ([`DeclarePermissions`]) debería sobrescribirlo con un texto traducible. fn label(&self) -> Lc { Lc::n(self.key()) } @@ -228,68 +239,6 @@ pub trait Permission: Send + Sync { /// [`require_permission()`] o [`CheckPermission`]). pub type PermissionRef = &'static dyn Permission; -// **< CheckPermission >**************************************************************************** - -/// Tipo de función para comprobar si el usuario actual tiene un permiso concreto. -/// -/// Se invoca con: -/// -/// - `request`: petición HTTP desde la que se accede a los datos inyectados por el middleware de -/// autenticación. -/// - `perm`: permiso a comprobar; el handler usará [`Permission::key()`] para identificarlo contra -/// su propio modelo de permisos. -/// - `granted`: referencia mutable; el handler debe asignarla a `true` si concede el permiso. -pub type FnActionCheckPerm = fn(request: &HttpRequest, perm: PermissionRef, granted: &mut bool); - -/// Acción para comprobar si el usuario actual tiene un permiso concreto. -/// -/// Las extensiones de autenticación pueden registrar su handler sobre esta acción para implementar -/// su modelo de permisos. Los handlers son aditivos de tal forma que si cualquiera de ellos asigna -/// `granted = true`, el permiso se concede. -/// -/// # Ejemplo -/// -/// ```rust,no_run -/// # use pagetop::prelude::*; -/// fn check_my_permissions(request: &HttpRequest, perm: PermissionRef, granted: &mut bool) { -/// // Leer los datos extendidos de autenticación inyectados en la petición. -/// // Comparar `perm.key()` contra el modelo propio. -/// // Si concede el permiso, asignar `*granted = true`. -/// } -/// -/// pub struct MyAuth; -/// -/// #[async_trait] -/// impl Extension for MyAuth { -/// fn actions(&self) -> Vec { -/// actions![CheckPermission::new(check_my_permissions)] -/// } -/// } -/// ``` -pub struct CheckPermission { - f: FnActionCheckPerm, - weight: Weight, -} - -impl ActionDispatcher for CheckPermission { - fn weight(&self) -> Weight { - self.weight - } -} - -impl CheckPermission { - /// Registra una nueva acción para la comprobación de permisos. - pub fn new(f: FnActionCheckPerm) -> Self { - CheckPermission { f, weight: 0 } - } - - /// Opcional. Acciones con pesos más bajos se aplican antes. Se pueden usar valores negativos. - pub fn with_weight(mut self, value: Weight) -> Self { - self.weight = value; - self - } -} - // **< has_permission >***************************************************************************** /// Comprueba si el usuario actual tiene el permiso indicado. @@ -318,26 +267,18 @@ impl CheckPermission { /// } /// ``` pub fn has_permission(request: &HttpRequest, perm: PermissionRef) -> bool { - // Despacha las acciones registradas con salida anticipada en cuanto una concede el permiso. - let mut granted = false; - try_dispatch_actions(|action: &CheckPermission| { - (action.f)(request, perm, &mut granted); - if granted { - ControlFlow::Break(()) - } else { - ControlFlow::Continue(()) - } - }); - granted + CheckPermission::dispatch(request, perm) } // **< require_permission >************************************************************************* /// Comprueba un permiso y devuelve `Err(ErrorPage::AccessDenied)` si se deniega. /// -/// Ejecuta [`has_permission()`] para el caso más habitual: detener un handler con una respuesta 403 -/// en cuanto falta el permiso, sin repetir el `if`/`return` en cada punto de comprobación. Se hace -/// directamente sobre la petición, antes de construir ni ejecutar nada (`Context`, `Page`, +/// Ejecuta [`has_permission()`] para detener un *handler* con una respuesta 403 en cuanto falta el +/// permiso, sin repetir el `if`/`return` en cada punto de comprobación. El acceso de la ruta +/// ([`Access`]) ya se ha comprobado antes de llegar al *handler*; esta función es para un permiso +/// más concreto que ése (p. ej. una acción que no todos los que ven la página pueden hacer). Se +/// llama directamente sobre la petición, antes de construir ni ejecutar nada (`Context`, `Page`, /// consultas a datos, etc.), para no hacer ningún trabajo si la petición no está autorizada. /// /// Si la aplicación necesita ocultar la existencia del recurso a quien no tiene permiso (devolver @@ -354,7 +295,7 @@ pub fn has_permission(request: &HttpRequest, perm: PermissionRef) -> bool { /// # fn key(&self) -> CowStr { "myapp:edit".into() } /// # } /// async fn my_handler(request: HttpRequest) -> Result { -/// // Comprueba si la petición está autorizada. +/// // La ruta ya exige su acceso; este permiso es más concreto. /// require_permission(&request, &MyPermission::Edit)?; /// /// // Ejecuta las instrucciones propias de la petición. @@ -371,3 +312,163 @@ pub fn require_permission(request: &HttpRequest, perm: PermissionRef) -> Result< Err(ErrorPage::AccessDenied(Some(request.clone()))) } } + +// **< Access >************************************************************************************* + +/// Quién puede acceder a una ruta. +/// +/// Toda ruta se monta con el suyo ([`Routes::route()`](crate::web::Routes::route)), y PageTop lo +/// comprueba antes de llegar al *handler*, que sólo comprueba permisos más concretos, si los hay +/// (p. ej. que el usuario sea el autor de lo que edita). A quien no tiene acceso se le responde +/// con [`deny_access()`]. +#[derive(Clone, Copy)] +pub enum Access { + /// Cualquiera, también un usuario anónimo. + /// + /// Es el acceso de las páginas públicas y de las rutas que se protegen por otra vía, que su + /// *handler* comprueba (p. ej. un enlace con un *token* de un solo uso). + Public, + /// Cualquier usuario autenticado, sin exigir ningún permiso. + Authenticated, + /// Quien tenga el permiso indicado (ver [`has_permission()`]). + Permission(PermissionRef), +} + +impl Access { + /// Devuelve `true` si la petición cumple este acceso. + pub fn allows(&self, request: &HttpRequest) -> bool { + match self { + Self::Public => true, + Self::Authenticated => is_authenticated(request), + Self::Permission(perm) => has_permission(request, *perm), + } + } +} + +// Sin una extensión de autenticación, la petición no lleva `CurrentUser` y el usuario es anónimo. +fn is_authenticated(request: &HttpRequest) -> bool { + request + .extension::() + .is_some_and(CurrentUser::is_authenticated) +} + +// **< deny_access >******************************************************************************** + +/// Responde a una petición sin acceso a la ruta pedida. +/// +/// A un usuario anónimo le responde la primera acción [`AnonymousDenied`] que lo haga (p. ej. con +/// el inicio de sesión); a uno autenticado, o si ninguna acción responde, la página de acceso +/// denegado (403). Es lo que hace PageTop con una ruta cuyo [`Access`] no se cumple, y lo puede +/// usar un *handler* que compruebe el acceso por su cuenta. +pub fn deny_access(request: HttpRequest) -> Response { + if !is_authenticated(&request) + && let Some(response) = AnonymousDenied::dispatch(&request) + { + return response; + } + ErrorPage::AccessDenied(Some(request)).into_response() +} + +// **< PermissionRegistry >************************************************************************* + +/// Catálogo de los permisos declarados por las extensiones. +/// +/// Se construye una sola vez al arrancar con las acciones [`DeclarePermissions`] y se consulta con +/// [`PermissionRegistry::global()`]. Vive sólo en memoria: a quién se concede cada permiso lo +/// guarda, si hace falta, la extensión de autenticación. +/// +/// Conserva el orden de registro. Para mostrar los grupos en pantalla, +/// [`groups_sorted()`](Self::groups_sorted) los ordena alfabéticamente según el idioma activo. +#[derive(AutoDefault)] +pub struct PermissionRegistry { + permissions: Vec, + // `(identificador de grupo, título traducible)`, en orden de primer registro. + groups: Vec<(&'static str, Lc)>, +} + +static PERMISSIONS: OnceLock = OnceLock::new(); + +static EMPTY_PERMISSIONS: PermissionRegistry = PermissionRegistry { + permissions: Vec::new(), + groups: Vec::new(), +}; + +impl PermissionRegistry { + /// Devuelve el catálogo global de permisos. + /// + /// Fuera de una aplicación, o antes de que ésta registre las acciones de sus extensiones, + /// devuelve un catálogo vacío. + pub fn global() -> &'static PermissionRegistry { + PERMISSIONS.get().unwrap_or(&EMPTY_PERMISSIONS) + } + + /// Registra un permiso. Se ignora si ya hay uno con la misma clave. + pub fn register(&mut self, perm: PermissionRef) { + if self.has(perm) { + return; + } + let group = perm.group(); + if !self.groups.iter().any(|(g, _)| *g == group) { + self.groups.push((group, perm.group_label())); + } + self.permissions.push(perm); + } + + /// Comprueba si un permiso está en el catálogo. + pub fn has(&self, perm: PermissionRef) -> bool { + self.has_key(&perm.key()) + } + + /// Comprueba si una clave textual (p. ej. procedente de un formulario) corresponde a un + /// permiso del catálogo. + pub fn has_key(&self, key: &str) -> bool { + self.permissions.iter().any(|p| p.key() == key) + } + + /// Todos los permisos, en orden de registro. + pub fn all(&self) -> impl Iterator + '_ { + self.permissions.iter().copied() + } + + /// Grupos en orden de primer registro, sin traducir ni ordenar alfabéticamente. + /// + /// Listado de bajo nivel sobre el que se apoya [`groups_sorted()`](Self::groups_sorted); úsalo + /// en su lugar sólo cuando el orden de registro sea justo lo que se necesita (por ejemplo, para + /// inspeccionar el catálogo en pruebas). + pub fn groups(&self) -> &[(&'static str, Lc)] { + &self.groups + } + + /// Grupos ordenados alfabéticamente por su título traducido al idioma del contexto, no sensible + /// a mayúsculas y, en general, a los acentos (ver [`Lc::collation_key()`] para el criterio + /// exacto y sus límites). + pub fn groups_sorted(&self, cx: &Context) -> Vec<&(&'static str, Lc)> { + let mut groups: Vec<_> = self + .groups + .iter() + .map(|g| (g.1.collation_key(cx), g)) + .collect(); + groups.sort_by(|a, b| a.0.cmp(&b.0)); + groups.into_iter().map(|(_, g)| g).collect() + } + + /// Permisos de un grupo, en orden de registro. + pub fn by_group<'a>(&'a self, group: &'a str) -> impl Iterator + 'a { + self.permissions + .iter() + .copied() + .filter(move |p| p.group() == group) + } +} + +// Construye el catálogo global despachando las acciones `DeclarePermissions`. Se llama al +// arrancar, justo después de registrar las acciones de las extensiones; si ya está construido (p. +// ej. por otra llamada a `Application::prepare()` en el mismo proceso, como hacen las pruebas), no +// hace nada. +pub(crate) fn build_permission_registry() { + PERMISSIONS.get_or_init(|| { + let mut registry = PermissionRegistry::default(); + DeclarePermissions::dispatch(&mut registry); + registry + }); +} diff --git a/src/base/action.rs b/src/base/action.rs index 1e4debca..95a816ae 100644 --- a/src/base/action.rs +++ b/src/base/action.rs @@ -1,5 +1,15 @@ -//! Acciones predefinidas para alterar el funcionamiento interno de PageTop. +//! Acciones predefinidas para intervenir en el funcionamiento de PageTop. +//! +//! Se agrupan por ámbito, para el renderizado de páginas ([`page`]) y componentes ([`component`]), +//! para extender el tratamiento de usuarios y permisos ([`auth`]) y mantener el panel de +//! administración ([`admin`]). Todas se declaran igual, con su constructor `new()` en +//! [`Extension::actions()`](crate::core::extension::Extension::actions), y se escriben con la ruta +//! de su ámbito, por ejemplo `action::page::BeforeRenderBody` o `action::auth::CheckPermission`. pub mod component; pub mod page; + +pub mod auth; + +pub mod admin; diff --git a/src/base/action/admin.rs b/src/base/action/admin.rs new file mode 100644 index 00000000..a24d0c34 --- /dev/null +++ b/src/base/action/admin.rs @@ -0,0 +1,32 @@ +//! Acciones para declarar las piezas que componen el panel de administración. +//! +//! Cada extensión aporta sus secciones, páginas, pestañas y botones al panel de administración con +//! estas acciones, sin depender de ninguna otra extensión, y PageTop las reúne al arrancar en el +//! registro del panel ([`AdminRegistry`](crate::admin::AdminRegistry)). El resto del panel está en +//! el módulo [`admin`](crate::admin). + +use crate::admin::{AdminActionBag, AdminPageBag, AdminSectionBag, AdminTaskBag}; + +/// Tipo de función para declarar secciones del panel de administración. +pub type FnActionDeclareAdminSections = fn(bag: &mut AdminSectionBag); + +/// Tipo de función para declarar páginas del panel de administración. +pub type FnActionDeclareAdminPages = fn(bag: &mut AdminPageBag); + +/// Tipo de función para declarar tareas (pestañas) locales de las páginas del panel. +pub type FnActionDeclareAdminTasks = fn(bag: &mut AdminTaskBag); + +/// Tipo de función para declarar acciones locales (botones) de las páginas del panel. +pub type FnActionDeclareAdminActions = fn(bag: &mut AdminActionBag); + +mod declare_admin_sections; +pub use declare_admin_sections::*; + +mod declare_admin_pages; +pub use declare_admin_pages::*; + +mod declare_admin_tasks; +pub use declare_admin_tasks::*; + +mod declare_admin_actions; +pub use declare_admin_actions::*; diff --git a/src/base/action/admin/declare_admin_actions.rs b/src/base/action/admin/declare_admin_actions.rs new file mode 100644 index 00000000..8978bbaf --- /dev/null +++ b/src/base/action/admin/declare_admin_actions.rs @@ -0,0 +1,47 @@ +use crate::prelude::*; + +use super::FnActionDeclareAdminActions; + +/// Acción para declarar acciones locales (botones de acción) en páginas del panel. +/// +/// Cada [`AdminAction`] indica la página en la que aparece el botón. +/// +/// # Ejemplo +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// fn declare_actions(bag: &mut AdminActionBag) { +/// bag.add(AdminAction::new("config/export/new", "config/export", Lc::n("Add export"))); +/// } +/// // En Extension::actions(): +/// // action::admin::DeclareAdminActions::new(declare_actions) +/// ``` +pub struct DeclareAdminActions { + f: FnActionDeclareAdminActions, + weight: Weight, +} + +impl ActionDispatcher for DeclareAdminActions { + fn weight(&self) -> Weight { + self.weight + } +} + +impl DeclareAdminActions { + /// Permite [registrar](Extension::actions) una nueva acción [`FnActionDeclareAdminActions`]. + pub fn new(f: FnActionDeclareAdminActions) -> Self { + DeclareAdminActions { f, weight: 0 } + } + + /// Opcional. Acciones con pesos más bajos se aplican antes. Se pueden usar valores negativos. + pub fn with_weight(mut self, value: Weight) -> Self { + self.weight = value; + self + } + + /// Despacha las acciones sobre la bolsa de acciones locales. + #[inline] + pub(crate) fn dispatch(bag: &mut AdminActionBag) { + dispatch_actions(|action: &Self| (action.f)(bag)); + } +} diff --git a/src/base/action/admin/declare_admin_pages.rs b/src/base/action/admin/declare_admin_pages.rs new file mode 100644 index 00000000..7e45dd2f --- /dev/null +++ b/src/base/action/admin/declare_admin_pages.rs @@ -0,0 +1,38 @@ +use crate::prelude::*; + +use super::FnActionDeclareAdminPages; + +/// Acción para declarar páginas del panel de administración. +/// +/// Declarar una página la incluye en la navegación del panel; su *handler* lo monta la propia +/// extensión en [`Extension::configure_router()`] con [`Routes::admin_route()`], que exige el +/// permiso de la página. Ver el ejemplo del módulo [`admin`](crate::admin). +pub struct DeclareAdminPages { + f: FnActionDeclareAdminPages, + weight: Weight, +} + +impl ActionDispatcher for DeclareAdminPages { + fn weight(&self) -> Weight { + self.weight + } +} + +impl DeclareAdminPages { + /// Permite [registrar](Extension::actions) una nueva acción [`FnActionDeclareAdminPages`]. + pub fn new(f: FnActionDeclareAdminPages) -> Self { + DeclareAdminPages { f, weight: 0 } + } + + /// Opcional. Acciones con pesos más bajos se aplican antes. Se pueden usar valores negativos. + pub fn with_weight(mut self, value: Weight) -> Self { + self.weight = value; + self + } + + /// Despacha las acciones sobre la bolsa de páginas. + #[inline] + pub(crate) fn dispatch(bag: &mut AdminPageBag) { + dispatch_actions(|action: &Self| (action.f)(bag)); + } +} diff --git a/src/base/action/admin/declare_admin_sections.rs b/src/base/action/admin/declare_admin_sections.rs new file mode 100644 index 00000000..335a47b6 --- /dev/null +++ b/src/base/action/admin/declare_admin_sections.rs @@ -0,0 +1,48 @@ +use crate::prelude::*; + +use super::FnActionDeclareAdminSections; + +/// Acción para declarar secciones del panel de administración. +/// +/// PageTop ya declara las secciones habituales: `"people"`, `"structure"`, `"config"`, +/// `"reports"` y `"help"`. Una sección declarada con la misma clave que otra la sustituye. +/// +/// # Ejemplo +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// fn declare_sections(bag: &mut AdminSectionBag) { +/// bag.add(AdminSection::new("tools", Lc::n("Tools")).with_weight(60)); +/// } +/// // En Extension::actions(): +/// // action::admin::DeclareAdminSections::new(declare_sections) +/// ``` +pub struct DeclareAdminSections { + f: FnActionDeclareAdminSections, + weight: Weight, +} + +impl ActionDispatcher for DeclareAdminSections { + fn weight(&self) -> Weight { + self.weight + } +} + +impl DeclareAdminSections { + /// Permite [registrar](Extension::actions) una nueva acción [`FnActionDeclareAdminSections`]. + pub fn new(f: FnActionDeclareAdminSections) -> Self { + DeclareAdminSections { f, weight: 0 } + } + + /// Opcional. Acciones con pesos más bajos se aplican antes. Se pueden usar valores negativos. + pub fn with_weight(mut self, value: Weight) -> Self { + self.weight = value; + self + } + + /// Despacha las acciones sobre la bolsa de secciones. + #[inline] + pub(crate) fn dispatch(bag: &mut AdminSectionBag) { + dispatch_actions(|action: &Self| (action.f)(bag)); + } +} diff --git a/src/base/action/admin/declare_admin_tasks.rs b/src/base/action/admin/declare_admin_tasks.rs new file mode 100644 index 00000000..0971b256 --- /dev/null +++ b/src/base/action/admin/declare_admin_tasks.rs @@ -0,0 +1,49 @@ +use crate::prelude::*; + +use super::FnActionDeclareAdminTasks; + +/// Acción para declarar tareas (pestañas) locales en páginas del panel. +/// +/// Cada [`AdminTask`] indica la página a la que pertenece; la pestaña con la ruta de la propia +/// página es la activa al entrar en ella. +/// +/// # Ejemplo +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// fn declare_tasks(bag: &mut AdminTaskBag) { +/// bag.add(AdminTask::new("config/export", "config/export", Lc::n("All"))); +/// bag.add(AdminTask::new("config/export/csv", "config/export", Lc::n("CSV")).with_weight(1)); +/// } +/// // En Extension::actions(): +/// // action::admin::DeclareAdminTasks::new(declare_tasks) +/// ``` +pub struct DeclareAdminTasks { + f: FnActionDeclareAdminTasks, + weight: Weight, +} + +impl ActionDispatcher for DeclareAdminTasks { + fn weight(&self) -> Weight { + self.weight + } +} + +impl DeclareAdminTasks { + /// Permite [registrar](Extension::actions) una nueva acción [`FnActionDeclareAdminTasks`]. + pub fn new(f: FnActionDeclareAdminTasks) -> Self { + DeclareAdminTasks { f, weight: 0 } + } + + /// Opcional. Acciones con pesos más bajos se aplican antes. Se pueden usar valores negativos. + pub fn with_weight(mut self, value: Weight) -> Self { + self.weight = value; + self + } + + /// Despacha las acciones sobre la bolsa de tareas. + #[inline] + pub(crate) fn dispatch(bag: &mut AdminTaskBag) { + dispatch_actions(|action: &Self| (action.f)(bag)); + } +} diff --git a/src/base/action/auth.rs b/src/base/action/auth.rs new file mode 100644 index 00000000..154521fb --- /dev/null +++ b/src/base/action/auth.rs @@ -0,0 +1,39 @@ +//! Acciones para conectar las extensiones de autenticación y declarar permisos. +//! +//! Con ellas una extensión concede los permisos al usuario actual ([`CheckPermission`]), da a +//! conocer los suyos en el catálogo ([`DeclarePermissions`]) o decide qué responder a un usuario +//! anónimo sin acceso a una ruta ([`AnonymousDenied`]). El resto del sistema de autorización está +//! en el módulo [`auth`](crate::auth). + +use crate::auth::{PermissionRef, PermissionRegistry}; +use crate::web::{HttpRequest, Response}; + +/// Tipo de función para comprobar si el usuario actual tiene un permiso concreto. +/// +/// Se invoca con: +/// +/// - `request`: petición HTTP desde la que se accede a los datos inyectados por el middleware de +/// autenticación. +/// - `perm`: permiso a comprobar; el handler usará +/// [`Permission::key()`](crate::auth::Permission::key) para identificarlo contra su propio +/// modelo de permisos. +/// - `granted`: referencia mutable; el handler debe asignarla a `true` si concede el permiso. +pub type FnActionCheckPerm = fn(request: &HttpRequest, perm: PermissionRef, granted: &mut bool); + +/// Tipo de función para declarar permisos en el catálogo. +pub type FnActionDeclarePermissions = fn(registry: &mut PermissionRegistry); + +/// Tipo de función para responder a un usuario anónimo sin acceso a una ruta. +/// +/// Devuelve la respuesta (p. ej. una redirección al formulario de inicio de sesión), o `None` para +/// dejar que responda otra acción o, si ninguna lo hace, la página de acceso denegado. +pub type FnActionAnonymousDenied = fn(request: &HttpRequest) -> Option; + +mod check_permission; +pub use check_permission::*; + +mod declare_permissions; +pub use declare_permissions::*; + +mod anonymous_denied; +pub use anonymous_denied::*; diff --git a/src/base/action/auth/anonymous_denied.rs b/src/base/action/auth/anonymous_denied.rs new file mode 100644 index 00000000..e5523522 --- /dev/null +++ b/src/base/action/auth/anonymous_denied.rs @@ -0,0 +1,69 @@ +use crate::prelude::*; + +use super::FnActionAnonymousDenied; + +use std::ops::ControlFlow; + +/// Acción para responder a un usuario anónimo sin acceso a una ruta. +/// +/// La registra una extensión de autenticación para ofrecer el inicio de sesión en lugar de la +/// página de acceso denegado, y volver después a la ruta pedida. Responde la primera acción, por +/// orden de peso, que devuelva una respuesta. Ver [`deny_access()`]. +/// +/// # Ejemplo +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// fn offer_login(request: &HttpRequest) -> Option { +/// // Vuelve a la ruta pedida tras iniciar sesión. +/// let waypoint = Waypoint::new(request.uri().to_owned()); +/// Some(Redirect::see_other(waypoint.append_to("/login"))) +/// } +/// +/// pub struct MyAuth; +/// +/// #[async_trait] +/// impl Extension for MyAuth { +/// fn actions(&self) -> Vec { +/// actions![action::auth::AnonymousDenied::new(offer_login)] +/// } +/// } +/// ``` +pub struct AnonymousDenied { + f: FnActionAnonymousDenied, + weight: Weight, +} + +impl ActionDispatcher for AnonymousDenied { + fn weight(&self) -> Weight { + self.weight + } +} + +impl AnonymousDenied { + /// Permite [registrar](Extension::actions) una nueva acción [`FnActionAnonymousDenied`]. + pub fn new(f: FnActionAnonymousDenied) -> Self { + AnonymousDenied { f, weight: 0 } + } + + /// Opcional. Acciones con pesos más bajos se aplican antes. Se pueden usar valores negativos. + pub fn with_weight(mut self, value: Weight) -> Self { + self.weight = value; + self + } + + /// Despacha las acciones hasta que una responde, y devuelve su respuesta. + #[inline] + pub(crate) fn dispatch(request: &HttpRequest) -> Option { + let mut response = None; + try_dispatch_actions(|action: &Self| { + response = (action.f)(request); + if response.is_some() { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }); + response + } +} diff --git a/src/base/action/auth/check_permission.rs b/src/base/action/auth/check_permission.rs new file mode 100644 index 00000000..4ca5969c --- /dev/null +++ b/src/base/action/auth/check_permission.rs @@ -0,0 +1,70 @@ +use crate::prelude::*; + +use super::FnActionCheckPerm; + +use std::ops::ControlFlow; + +/// Acción para comprobar si el usuario actual tiene un permiso concreto. +/// +/// Las extensiones de autenticación pueden registrar su handler sobre esta acción para implementar +/// su modelo de permisos. Los handlers son aditivos de tal forma que si cualquiera de ellos asigna +/// `granted = true`, el permiso se concede. La consultan [`has_permission()`] y el acceso de las +/// rutas ([`Access::Permission`]). +/// +/// # Ejemplo +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// fn check_my_permissions(request: &HttpRequest, perm: PermissionRef, granted: &mut bool) { +/// // Leer los datos extendidos de autenticación inyectados en la petición. +/// // Comparar `perm.key()` contra el modelo propio. +/// // Si concede el permiso, asignar `*granted = true`. +/// } +/// +/// pub struct MyAuth; +/// +/// #[async_trait] +/// impl Extension for MyAuth { +/// fn actions(&self) -> Vec { +/// actions![action::auth::CheckPermission::new(check_my_permissions)] +/// } +/// } +/// ``` +pub struct CheckPermission { + f: FnActionCheckPerm, + weight: Weight, +} + +impl ActionDispatcher for CheckPermission { + fn weight(&self) -> Weight { + self.weight + } +} + +impl CheckPermission { + /// Permite [registrar](Extension::actions) una nueva acción [`FnActionCheckPerm`]. + pub fn new(f: FnActionCheckPerm) -> Self { + CheckPermission { f, weight: 0 } + } + + /// Opcional. Acciones con pesos más bajos se aplican antes. Se pueden usar valores negativos. + pub fn with_weight(mut self, value: Weight) -> Self { + self.weight = value; + self + } + + /// Despacha las acciones hasta que una concede el permiso, y devuelve si alguna lo ha hecho. + #[inline] + pub(crate) fn dispatch(request: &HttpRequest, perm: PermissionRef) -> bool { + let mut granted = false; + try_dispatch_actions(|action: &Self| { + (action.f)(request, perm, &mut granted); + if granted { + ControlFlow::Break(()) + } else { + ControlFlow::Continue(()) + } + }); + granted + } +} diff --git a/src/base/action/auth/declare_permissions.rs b/src/base/action/auth/declare_permissions.rs new file mode 100644 index 00000000..a938b379 --- /dev/null +++ b/src/base/action/auth/declare_permissions.rs @@ -0,0 +1,85 @@ +use crate::prelude::*; + +use super::FnActionDeclarePermissions; + +/// Acción para declarar los permisos de una extensión en el catálogo de permisos. +/// +/// Cada extensión añade una instancia en [`Extension::actions()`]. PageTop despacha todas al +/// arrancar, después de registrar las acciones y antes de inicializar las extensiones, y construye +/// el catálogo global ([`PermissionRegistry::global()`]). El texto y el grupo de cada permiso los +/// aporta el propio [`Permission`] ([`label()`], [`group()`] y [`group_label()`]). +/// +/// Declarar un permiso no lo concede a nadie: sólo lo da a conocer, para que una extensión de +/// autenticación pueda ofrecerlo (p. ej. en una pantalla de asignación de permisos a roles). Sin +/// ninguna, el permiso existe en el catálogo pero [`has_permission()`] lo deniega siempre. +/// +/// Un permiso que exige una ruta ([`Access::Permission`]) o una pieza del panel de administración +/// sin estar declarado se avisa en las trazas al arrancar: nadie podría concederlo desde una +/// pantalla así. +/// +/// # Ejemplo +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// #[derive(Clone, Copy, Debug)] +/// enum MyPermission { +/// DoSomething, +/// } +/// +/// impl Permission for MyPermission { +/// fn key(&self) -> CowStr { +/// match self { +/// Self::DoSomething => "myext:do_something".into(), +/// } +/// } +/// } +/// +/// fn declare_permissions(registry: &mut PermissionRegistry) { +/// registry.register(&MyPermission::DoSomething); +/// } +/// +/// pub struct MyExtension; +/// +/// #[async_trait] +/// impl Extension for MyExtension { +/// fn actions(&self) -> Vec { +/// actions![action::auth::DeclarePermissions::new(declare_permissions)] +/// } +/// } +/// ``` +/// +/// [`label()`]: Permission::label +/// [`group()`]: Permission::group +/// [`group_label()`]: Permission::group_label +pub struct DeclarePermissions { + f: FnActionDeclarePermissions, + weight: Weight, +} + +impl ActionDispatcher for DeclarePermissions { + fn weight(&self) -> Weight { + self.weight + } +} + +impl DeclarePermissions { + /// Permite [registrar](Extension::actions) una nueva acción [`FnActionDeclarePermissions`]. + pub fn new(f: FnActionDeclarePermissions) -> Self { + DeclarePermissions { f, weight: 0 } + } + + /// Opcional. Acciones con pesos más bajos se aplican antes. Se pueden usar valores negativos. + /// + /// Determina el orden de registro en el catálogo y, con él, el de los permisos de un mismo + /// grupo en [`PermissionRegistry::by_group()`]. + pub fn with_weight(mut self, value: Weight) -> Self { + self.weight = value; + self + } + + /// Despacha las acciones sobre el catálogo que se está construyendo. + #[inline] + pub(crate) fn dispatch(registry: &mut PermissionRegistry) { + dispatch_actions(|action: &Self| (action.f)(registry)); + } +} diff --git a/src/base/component.rs b/src/base/component.rs index 1365c704..9132fff0 100644 --- a/src/base/component.rs +++ b/src/base/component.rs @@ -2,6 +2,12 @@ pub mod layout; +mod admin_frame; +pub use admin_frame::AdminFrame; + +mod admin_menu; +pub use admin_menu::AdminMenu; + mod badge; pub use badge::Badge; diff --git a/src/base/component/admin_frame.rs b/src/base/component/admin_frame.rs new file mode 100644 index 00000000..e77c66f1 --- /dev/null +++ b/src/base/component/admin_frame.rs @@ -0,0 +1,170 @@ +use crate::prelude::*; + +/// Marco de una página del panel de administración, alrededor de la región +/// [`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 +/// página ([`AdminTask`]) y, después, el contenido. Si la página no tiene título, usa el de la +/// página declarada para esa ruta, también en el `` del documento: +/// +/// ```html +/// <nav class="breadcrumb">...</nav> +/// <header class="admin-header"> +/// <h1 class="admin-page-title">Title</h1> +/// <ul class="admin-actions-list">...</ul> +/// </header> +/// <nav class="admin-local-tasks">...</nav> +/// <div class="admin-content">...</div> +/// ``` +/// +/// La plantilla [`CoreTemplates::Admin`] lo pinta en lugar de la región `Content`, así que un +/// *handler* sólo tiene que crear la página con [`Page::admin()`], darle título y añadir su +/// contenido. Un tema puede capturarlo en [`Theme::render_component()`] para darle otro aspecto, +/// pero entonces le corresponde pintar también la región `Content` +/// ([`layout::Region::content()`](crate::base::component::layout::Region::content)). +/// +/// Para una ruta que no es una página declarada (p. ej. la edición de un elemento de un listado), +/// las migas enlazan con la página declarada más cercana que la contiene. +/// +/// [`Page::admin()`]: crate::response::Page::admin +/// [`Theme::render_component()`]: crate::core::theme::Theme::render_component +#[derive(AutoDefault, Clone, Debug)] +pub struct AdminFrame; + +#[async_trait] +impl Component for AdminFrame { + fn new() -> Self { + Self + } + + async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> { + // Ruta de la petición relativa a la raíz del panel, como se guarda en el registro. + let path = cx + .request() + .and_then(|r| strip_admin_path(r.path())) + .unwrap_or_default() + .to_owned(); + + // Sin título propio, la página declarada aporta el suyo, también al `<head>` (que se + // renderiza después del `<body>`). + if cx.title().is_none() + && let Some(page) = AdminRegistry::global().page(&path) + { + cx.alter_title(page.title().clone()); + } + + let breadcrumbs = breadcrumbs(cx, &path).render(cx).await; + let actions = local_actions(cx, &path); + let tasks = local_tasks(cx, &path); + let content = layout::Region::content().render(cx).await; + let title = cx.title().using(cx); + + Ok(html! { + (breadcrumbs) + header class="admin-header" { + @if !title.is_empty() { + h1 class="admin-page-title" { (title) } + } + (actions) + } + @if !tasks.is_empty() { + nav class="admin-local-tasks" { (tasks) } + } + div class="admin-content" { + (content) + } + }) + } +} + +// Inicio del panel, sección y página de la ruta. La última miga es la página actual, sin enlace. +fn breadcrumbs(cx: &Context, path: &str) -> Breadcrumb { + if path.is_empty() { + return Breadcrumb::new().with_crumb(breadcrumb::Crumb::current(Lc::l("admin_dashboard"))); + } + let registry = AdminRegistry::global(); + let mut bc = Breadcrumb::new().with_crumb(breadcrumb::Crumb::new( + Lc::l("admin_dashboard"), + admin_path(""), + )); + if let Some(page) = registry.nearest_page(path) { + if let Some(section) = registry.section(page.section()) { + bc = bc.with_crumb(breadcrumb::Crumb::new( + section.title().clone(), + admin_path(section.path()), + )); + } + if page.path() == path { + bc = bc.with_crumb(breadcrumb::Crumb::current(page.title().clone())); + } else { + bc = bc.with_crumb(breadcrumb::Crumb::new( + page.title().clone(), + admin_path(page.path()), + )); + if !cx.title().is_none() { + bc = bc.with_crumb(breadcrumb::Crumb::current(cx.title().clone())); + } + } + } else if let Some(section) = registry.section_by_path(path) { + // La ruta es la propia sección (su página de aterrizaje), no una página declarada en ella. + bc = bc.with_crumb(breadcrumb::Crumb::current(section.title().clone())); + } + bc +} + +// Pestañas de la página de la ruta, también cuando la ruta es una de ellas. Las que exigen un +// permiso que el usuario no tiene no se muestran. +fn local_tasks(cx: &Context, path: &str) -> Markup { + let registry = AdminRegistry::global(); + let parent = registry.task(path).map_or(path, |task| task.parent_path()); + let tasks: Vec<_> = registry + .tasks_for(parent) + .iter() + .filter(|task| is_granted(cx, task.permission())) + .collect(); + if tasks.is_empty() { + return html! {}; + } + html! { + ul class="admin-tasks-list" { + @for task in tasks { + li class="admin-task" .admin-task-active[task.path() == path] { + a href=(cx.route(admin_path(task.path()))) { (task.title().using(cx)) } + } + } + } + } +} + +// Botones de acción de la página de la ruta. Los que exigen un permiso que el usuario no tiene no +// se muestran. +fn local_actions(cx: &Context, path: &str) -> Markup { + let actions: Vec<_> = AdminRegistry::global() + .actions_for(path) + .iter() + .filter(|action| is_granted(cx, action.permission())) + .collect(); + if actions.is_empty() { + return html! {}; + } + html! { + ul class="admin-actions-list" { + @for action in actions { + li class="admin-action" { + a class="admin-action-link" href=(cx.route(admin_path(action.url()))) { + (action.title().using(cx)) + } + } + } + } + } +} + +// Sin permiso propio (`None`) basta con ver la página, cuyo permiso ya ha exigido su ruta. +fn is_granted(cx: &Context, permission: Option<PermissionRef>) -> bool { + permission.is_none_or(|permission| { + cx.request() + .is_some_and(|request| has_permission(request, permission)) + }) +} diff --git a/src/base/component/admin_menu.rs b/src/base/component/admin_menu.rs new file mode 100644 index 00000000..80929429 --- /dev/null +++ b/src/base/component/admin_menu.rs @@ -0,0 +1,60 @@ +use crate::prelude::*; + +/// Navegación del panel de administración para el usuario de la petición actual. +/// +/// Es una [`Navbar`] con un enlace al inicio del panel (*dashboard*) seguido de un desplegable por +/// sección, con las páginas de cada una a las que el usuario puede acceder; las secciones sin +/// ninguna no se muestran. Lo construye en cada petición a partir de [`AdminRegistry`]. +/// +/// La plantilla [`CoreTemplates::Admin`] lo pinta tras la región [`CoreRegions::Header`]. Se +/// construye sólo con componentes del núcleo (`Navbar`, `Nav` y `Dropdown`), así que un tema le da +/// su aspecto capturando esos componentes o éste mismo en [`Theme::render_component()`]. +/// +/// Sin acceso a ninguna página del panel ([`can_access_admin()`]) no se renderiza: no se despachan +/// sus acciones ni intervienen los temas. +/// +/// [`Theme::render_component()`]: crate::core::theme::Theme::render_component +#[derive(AutoDefault, Clone, Debug)] +pub struct AdminMenu; + +#[async_trait] +impl Component for AdminMenu { + fn new() -> Self { + Self + } + + fn is_renderable(&self, cx: &Context) -> bool { + can_access_admin(cx) + } + + async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> { + let registry = AdminRegistry::global(); + + let mut nav = + Nav::new().with_item(nav::Item::link(Lc::l("admin_dashboard"), admin_path(""))); + for section in registry.sections() { + let pages: Vec<_> = registry + .pages_for_section(section.key()) + .iter() + .filter(|p| p.is_accessible(cx)) + .collect(); + if pages.is_empty() { + continue; + } + let mut menu = Dropdown::new().with_title(section.title().clone()); + for page in pages { + menu = menu.with_item(dropdown::Item::link( + page.title().clone(), + admin_path(page.path()), + )); + } + nav = nav.with_item(nav::Item::dropdown(menu)); + } + + Ok(Navbar::simple() + .with_prop(PropsOp::add_classes("admin-menu")) + .with_item(navbar::Item::nav(nav)) + .render(cx) + .await) + } +} diff --git a/src/base/component/layout/template.rs b/src/base/component/layout/template.rs index a3c9bfeb..a1a23ae7 100644 --- a/src/base/component/layout/template.rs +++ b/src/base/component/layout/template.rs @@ -10,6 +10,10 @@ use std::fmt; /// su gusto (por ejemplo, usando CSS Grid, para que `Aside` se muestre como columna lateral junto a /// `Content`). Si `Aside`, o cualquier otra región, no tiene contenido, no se renderiza. /// +/// [`CoreTemplates::Admin`] añade el panel de administración: tras `Header` pinta la navegación +/// del panel ([`AdminMenu`]) y, en lugar de `Content`, el marco de la página ([`AdminFrame`]), que +/// contiene la región; el contenedor lleva además la clase `wrapper-admin`. +/// /// No incluye las regiones reservadas ([`ReservedRegions::PageTop`] y /// [`ReservedRegions::PageBottom`]) porque el propio [`Page::render()`] las añade antes y después /// del resultado de [`Theme::render_page_body()`] para que se rendericen siempre, @@ -65,11 +69,25 @@ impl Component for Template { } async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> { - let body = html! { - (layout::Region::header().render(cx).await) - (layout::Region::aside().render(cx).await) - (layout::Region::content().render(cx).await) - (layout::Region::footer().render(cx).await) + let admin = matches!( + self.template().downcast_ref::<CoreTemplates>(), + Some(CoreTemplates::Admin) + ); + let body = if admin { + html! { + (layout::Region::header().render(cx).await) + (AdminMenu::new().render(cx).await) + (layout::Region::aside().render(cx).await) + (AdminFrame::new().render(cx).await) + (layout::Region::footer().render(cx).await) + } + } else { + html! { + (layout::Region::header().render(cx).await) + (layout::Region::aside().render(cx).await) + (layout::Region::content().render(cx).await) + (layout::Region::footer().render(cx).await) + } }; if body.is_empty() { @@ -77,7 +95,7 @@ impl Component for Template { } Ok(html! { - div class="wrapper" { + div class="wrapper" .wrapper-admin[admin] { (body) } }) diff --git a/src/base/component/messages.rs b/src/base/component/messages.rs index 0b7e292c..fd980035 100644 --- a/src/base/component/messages.rs +++ b/src/base/component/messages.rs @@ -3,7 +3,7 @@ use crate::prelude::*; /// Componente que muestra los **mensajes de usuario** acumulados en el contexto. /// /// No recibe ningún contenido de quien lo construye. Lo obtiene directamente del [`Context`] (ver -/// [`Context::push_message()`](Context::push_message)) en el momento de renderizarse, y retira los +/// [`push_message()`](Contextual::push_message)) en el momento de renderizarse, y retira los /// mensajes que muestra para que no se repitan. Si no hay ninguno acumulado, no renderiza nada. /// /// [`Region`] añade uno al inicio de la región [`CoreRegions::Content`], así que no hace falta @@ -36,8 +36,7 @@ use crate::prelude::*; /// /// async fn homepage(request: HttpRequest) -> Result<Markup, ErrorPage> { /// let mut page = Page::new(request); -/// page.context() -/// .push_message(MessageLevel::Info, Lc::n("Settings saved.")); +/// page.push_message(MessageLevel::Info, Lc::n("Settings saved.")); /// page.with_child(Html::with(|_| html! { p { "..." } })) /// .render() /// .await diff --git a/src/base/extension/welcome.rs b/src/base/extension/welcome.rs index 2c7032d7..520f6935 100644 --- a/src/base/extension/welcome.rs +++ b/src/base/extension/welcome.rs @@ -21,8 +21,8 @@ impl Extension for Welcome { Lc::l("welcome_extension_description") } - fn configure_router(&self, router: Router) -> Router { - router.route("/", web::get(home)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/", web::get(home)) } } diff --git a/src/core/component/context.rs b/src/core/component/context.rs index 6e5a41cc..654f2655 100644 --- a/src/core/component/context.rs +++ b/src/core/component/context.rs @@ -1,16 +1,15 @@ use crate::auth::CurrentUser; -use crate::core::TypeInfo; -use crate::core::component::{ChildOp, Component, MessageLevel, StatusMessage}; -use crate::core::theme::{ChildrenInRegions, CoreRegions, CoreTemplates, default_theme}; +use crate::core::component::{Component, StatusMessage}; +use crate::core::theme::{ChildrenInRegions, CoreTemplates, default_theme}; use crate::core::theme::{RegionRef, TemplateRef, ThemeRef}; use crate::datetime::Tz; use crate::html::{Assets, Favicon, JavaScript, Preload, ResponsiveStyles, StyleSheet}; -use crate::html::{Markup, PreEscaped, Props, PropsOp, RoutePath, html}; +use crate::html::{Markup, PreEscaped, Props, html}; use crate::locale::Lc; -use crate::locale::{LangId, LanguageIdentifier, RequestLocale}; +use crate::locale::RequestLocale; use crate::response::read_flash_messages; use crate::web::HttpRequest; -use crate::{builder_impl, util}; +use crate::{CowStr, util}; use parking_lot::Mutex; @@ -29,25 +28,18 @@ pub use contextual::Contextual; /// Implementa un **contexto de renderizado** para un documento HTML. /// /// Se crea una sola vez por petición usando [`Context::new()`] (típicamente a través de -/// [`Page::new()`](crate::response::Page::new) o [`Page::admin()`](crate::response::Page::admin)), -/// y es la única vía por la que un componente, una acción o el tema activo conocen: la petición -/// HTTP de origen, el idioma negociado y la zona horaria efectiva, el usuario autenticado -/// ([`current_user()`](Contextual::current_user)), el tema y la plantilla en uso, y los recursos -/// (favicon, hojas de estilo, scripts) acumulados hasta ese momento. Otros datos que los +/// [`Page::new()`] o [`Page::admin()`]), y es la única vía por la que un componente, una acción o +/// el tema activo conocen la petición HTTP de origen, el idioma negociado y la zona horaria +/// efectiva, el usuario autenticado ([`current_user()`]), el tema y la plantilla en uso, y los +/// recursos (favicon, hojas de estilo, scripts) acumulados hasta ese momento. Otros datos que los /// componentes necesiten durante el renderizado pueden ser parámetros dinámicos tipados con -/// [`with_param()`](Contextual::with_param)/[`param()`](Contextual::param). +/// [`with_param()`]/[`param()`]. /// -/// La implementación extiende [`Contextual`], que aporta los métodos *builder* (`with_*`) y los -/// *getters* comunes a cualquier estructura que gestione un contexto de renderizado (también los -/// implementa [`Page`](crate::response::Page)). Además, `Context` añade: -/// -/// - [`route()`](Self::route) para construir URLs que preserven `?lang=...` cuando corresponda. -/// - [`build_id()`](Self::build_id)/[`required_id()`](Self::required_id) para generar -/// identificadores HTML únicos por tipo de componente. -/// - [`push_message()`](Self::push_message)/[`messages()`](Self::messages) para acumular -/// [`StatusMessage`] que mostrar en algún momento del renderizado. -/// - [`render_assets()`](Self::render_assets)/[`render_region()`](Self::render_region), usados -/// internamente por [`Page`](crate::response::Page) para producir el HTML final del documento. +/// Su interfaz la aporta [`Contextual`]: los métodos *builder* (`with_*`), los *getters* y las +/// utilidades como [`route()`], [`build_id()`] o [`push_message()`]. Como también lo implementa +/// [`Page`], sobre el contexto que contiene, ambos se usan exactamente igual. Además de sus +/// constructores, `Context` sólo añade [`render_assets()`] y [`render_region()`], con los que los +/// temas y la página producen el HTML final del documento. /// /// # Ejemplos /// @@ -93,6 +85,18 @@ pub use contextual::Contextual; /// let _unique_id = cx.build_id::<Menu>(1); // => "menu-1" si es el primero /// } /// ``` +/// +/// [`Page`]: crate::response::Page +/// [`Page::new()`]: crate::response::Page::new +/// [`Page::admin()`]: crate::response::Page::admin +/// [`current_user()`]: Contextual::current_user +/// [`with_param()`]: Contextual::with_param +/// [`param()`]: Contextual::param +/// [`route()`]: Contextual::route +/// [`build_id()`]: Contextual::build_id +/// [`push_message()`]: Contextual::push_message +/// [`render_assets()`]: Self::render_assets +/// [`render_region()`]: Self::render_region #[rustfmt::skip] pub struct Context { request : Option<HttpRequest>, // Petición HTTP de origen. @@ -106,6 +110,10 @@ pub struct Context { stylesheets : Assets<StyleSheet>, // Hojas de estilo CSS. javascripts : Assets<JavaScript>, // Scripts JavaScript. responsives : ResponsiveStyles, // Estilos *responsive*. + title : Lc, // Título del documento. + description : Lc, // Descripción del documento. + metadata : Vec<(&'static str, CowStr)>, // Entradas <meta name=...>. + properties : Vec<(&'static str, CowStr)>, // Entradas <meta property=...>. body_props : Props, // Id, clases CSS y atributos del <body>. regions : ChildrenInRegions, // Regiones de componentes para renderizar. deferred : Option<Deferred>, // Componentes de renderizado aplazado. @@ -130,7 +138,7 @@ impl Default for Context { impl Context { // Construye el `Context` compartido por `new()`, `admin()` y `Default::default()`, evitando - // duplicar la lista de campos entre ambos (y la recursión que tendría `new()` llamando a + // duplicar la lista de campos entre ellos (y la recursión que tendría `new()` llamando a // `Default::default()`, o viceversa). Recibe la plantilla para que `admin()` no tenga que // construir con la plantilla estándar y sobrescribirla después. #[rustfmt::skip] @@ -155,6 +163,10 @@ impl Context { stylesheets: Assets::<StyleSheet>::new(), javascripts: Assets::<JavaScript>::new(), responsives: ResponsiveStyles::new(), + title : Lc::none(), + description: Lc::none(), + metadata : Vec::new(), + properties : Vec::new(), body_props : Props::default(), regions : ChildrenInRegions::default(), deferred : None, @@ -247,6 +259,8 @@ impl Context { .await } + // **< Context HELPERS >************************************************************************ + // Empieza a aplazar los componentes que lo pidan (`Component::is_deferred()`), mientras // `Page::render()` renderiza el `<body>`. pub(crate) fn start_deferring(&mut self) { @@ -307,293 +321,20 @@ impl Context { PreEscaped(body) } - // **< Context HELPERS >************************************************************************ - - /// Construye una ruta aplicada al contexto actual. - /// - /// Acepta cualquier tipo convertible a [`RoutePath`] (un literal, un `String`, un `&str` de - /// cualquier vida, o un [`RoutePath`] ya construido con sus propios parámetros). Si la política - /// de negociación del idioma ([`LangNegotiation`](crate::global::LangNegotiation)) indica que - /// debe propagarse el idioma para esta petición, se añade o actualiza automáticamente el - /// parámetro de *query* `lang=...` con el identificador de idioma definido en el contexto. - /// - /// Esto garantiza que los enlaces generados desde el contexto preservan la preferencia de - /// idioma del usuario durante la navegación. Si `path` **parece** una URL externa (ver - /// [`util::url_looks_external()`](crate::util::url_looks_external)), nunca se le añade `lang`. - /// - /// Este método asume que ya tienes `cx` a mano en el momento de construir la ruta (dentro de - /// `prepare()`, un *handler* HTTP, etc.). Si lo que estás definiendo es un campo de componente - /// que se construye una sola vez y se reutiliza en peticiones futuras (un menú, un botón, - /// etc.), usa [`Route`](crate::core::component::Route) en su lugar (su documentación explica el - /// criterio completo para elegir entre ambos). - pub fn route(&self, path: impl Into<RoutePath>) -> RoutePath { - let mut route = path.into(); - if !route.is_external() && self.locale.needs_lang_query() { - route.alter_param("lang", self.locale.lang_query_value()); - } - route - } - - /// Construye un identificador HTML único para el tipo de componente `C`. - /// - /// Toma los `segments` finales del *path* completo del tipo, los une con `-` y los convierte a - /// minúsculas, y añade un contador independiente por tipo. Por ejemplo, para `MyApp::ui::Menu` - /// con `segments = 2` devuelve `ui-menu-1` la primera vez que se invoca para ese tipo, - /// `ui-menu-2` la segunda, etc. - /// - /// Con `segments = 1` se usa sólo el nombre corto del tipo. Si `segments` es `0` o supera el - /// número de segmentos del *path*, se usan todos. - /// - /// Es útil para asignar identificadores cuando el componente no recibe uno explícito. El - /// contador es local a este contexto y se reinicia para cada nueva petición. - pub fn build_id<C: Component>(&self, segments: usize) -> String { - let path: Vec<&str> = TypeInfo::FullName.of::<C>().split("::").collect(); - let segments = if segments == 0 || segments >= path.len() { - path.len() - } else { - segments - }; - let count = { - let mut map = self.id_counters.lock(); - let n = map.entry(TypeId::of::<C>()).or_insert(0); - *n += 1; - *n - }; - let prefix = path[path.len() - segments..].join("-").to_lowercase(); - util::join!(prefix, "-", count.to_string()) - } - - /// Devuelve `id` si contiene un valor, o genera uno único con [`build_id`](Self::build_id) - /// si es `None`. - pub fn required_id<C: Component>(&self, id: Option<String>, segments: usize) -> String { - match id { - Some(id) => id, - None => self.build_id::<C>(segments), - } - } - - /// Acumula un [`StatusMessage`] en el contexto para notificar al usuario. - /// - /// Pueden generarse en cualquier punto del ciclo de una petición web (handlers, renderizado, - /// lógica de negocio, etc.) que tengan acceso al contexto. Los muestra, y los retira, el primer - /// componente [`Messages`](crate::base::component::Messages) que se renderice después de - /// añadirlos: uno propio de la página, si lo hay, o el que encabeza la región - /// [`CoreRegions::Content`], que se renderiza una vez renderizado el resto del `<body>` y - /// recoge los que queden. - /// - /// # Ejemplo - /// - /// ```rust,no_run - /// # use pagetop::prelude::*; - /// # let mut cx = Context::default(); - /// cx.push_message(MessageLevel::Warning, Lc::n("Session is not valid")); - /// ``` - pub fn push_message(&mut self, level: MessageLevel, text: Lc) { - self.messages.push(StatusMessage::new(level, text)); - } - - /// Devuelve los mensajes de usuario acumulados que aún no ha mostrado ningún componente - /// [`Messages`](crate::base::component::Messages). - pub fn messages(&self) -> &[StatusMessage] { - &self.messages - } - - /// Indica si hay mensajes de usuario acumulados que aún no ha mostrado ningún componente - /// [`Messages`](crate::base::component::Messages). - pub fn has_messages(&self) -> bool { - !self.messages.is_empty() - } - // Retira los mensajes acumulados, para que el componente `Messages` los muestre una sola vez. pub(crate) fn take_messages(&mut self) -> Vec<StatusMessage> { std::mem::take(&mut self.messages) } } -/// Permite a [`Context`] actuar como proveedor de idioma. -/// -/// Internamente delega en [`RequestLocale`], que tiene en cuenta la petición HTTP (parámetro -/// `?lang` e idioma preferido del usuario), la configuración global de idioma de la aplicación, la -/// cabecera `Accept-Language` y/o el idioma de respaldo. -/// -/// Todo ello según la negociación indicada en [`global::SETTINGS.app.lang_negotiation`]. Esto -/// permite que el [`Context`] se use como fuente de idioma coherente en [`Lc::lookup()`] o -/// [`Lc::using()`]. -/// -/// [`Context`]: crate::core::component::Context -/// [`global::SETTINGS.app.lang_negotiation`]: crate::global::AppSettings::lang_negotiation -/// [`Lc::lookup()`]: crate::locale::Lc::lookup -/// [`Lc::using()`]: crate::locale::Lc::using -impl LangId for Context { - #[inline] - fn langid(&self) -> &'static LanguageIdentifier { - self.locale.langid() - } -} - -#[builder_impl] impl Contextual for Context { - // **< Contextual BUILDER >********************************************************************* - - fn with_request(mut self, request: Option<HttpRequest>) -> Self { - // Los mensajes para la página siguiente se leen una sola vez, con la primera petición (las - // páginas de error, p. ej., parten de un contexto sin petición). - if self.request.is_none() - && let Some(request) = &request - { - self.messages.extend(read_flash_messages(request.headers())); - } - self.request = request; - // Recalcula el *locale*, el usuario actual, la zona horaria y el tema según la nueva - // petición y la política de negociación configurada. - self.locale = RequestLocale::from_request(self.request.as_ref()); - self.current_user = Self::resolve_current_user(self.request.as_ref()); - self.timezone = self.current_user.timezone(); - self.theme = self.current_user.theme().unwrap_or_else(default_theme); + #[inline] + fn context(&self) -> &Context { self } - fn with_langid(mut self, language: &impl LangId) -> Self { - self.locale.with_langid(language); + #[inline] + fn context_mut(&mut self) -> &mut Context { self } - - fn with_timezone(mut self, tz: Tz) -> Self { - self.timezone = tz; - self - } - - fn with_theme(mut self, theme: ThemeRef) -> Self { - self.theme = theme; - self - } - - fn with_template(mut self, template: TemplateRef) -> Self { - self.template = template; - self - } - - fn with_param<T: Send + Sync + 'static>(mut self, key: &'static str, value: T) -> Self { - let type_name = TypeInfo::FullName.of::<T>(); - self.params.insert(key, (Box::new(value), type_name)); - self - } - - fn with_assets(mut self, op: impl Into<AssetsOp>) -> Self { - match op.into() { - // Favicon. - AssetsOp::SetFavicon(favicon) => { - self.favicon = favicon; - } - AssetsOp::SetFaviconIfNone(icon) => { - if self.favicon.is_none() { - self.favicon = Some(icon); - } - } - // Preloads. - AssetsOp::AddPreload(preload) => { - self.preloads.add(preload); - } - AssetsOp::RemovePreload(path) => { - self.preloads.remove(path); - } - // Stylesheets. - AssetsOp::AddStyleSheet(css) => { - self.stylesheets.add(css); - } - AssetsOp::RemoveStyleSheet(path) => { - self.stylesheets.remove(path); - } - // Scripts JavaScript. - AssetsOp::AddJavaScript(js) => { - self.javascripts.add(js); - } - AssetsOp::RemoveJavaScript(path) => { - self.javascripts.remove(path); - } - // Estilos responsive. - AssetsOp::AddResponsiveStyle(breakpoint, classes, property, value) => { - self.responsives - .add_style(breakpoint, classes, property, value); - } - AssetsOp::AddResponsiveStyles(breakpoint, classes, styles) => { - self.responsives.add_styles(breakpoint, classes, styles); - } - } - self - } - - fn with_body_props(mut self, op: PropsOp) -> Self { - self.body_props.alter_prop(op); - self - } - - fn with_child(mut self, op: impl Into<ChildOp>) -> Self { - self.regions - .alter_child_in(&CoreRegions::Content, op.into()); - self - } - - fn with_child_in(mut self, region: RegionRef, op: impl Into<ChildOp>) -> Self { - self.regions.alter_child_in(region, op.into()); - self - } - - // **< Contextual GETTERS >********************************************************************* - - fn request(&self) -> Option<&HttpRequest> { - self.request.as_ref() - } - - fn current_user(&self) -> &CurrentUser { - &self.current_user - } - - fn timezone(&self) -> Tz { - self.timezone - } - - fn theme(&self) -> ThemeRef { - self.theme - } - - fn template(&self) -> TemplateRef { - self.template - } - - fn param<T: 'static>(&self, key: &'static str) -> Result<&T, ContextError> { - let (any, type_name) = self.params.get(key).ok_or(ContextError::ParamNotFound)?; - any.downcast_ref::<T>() - .ok_or_else(|| ContextError::ParamTypeMismatch { - key, - expected: TypeInfo::FullName.of::<T>(), - saved: type_name, - }) - } - - fn favicon(&self) -> Option<&Favicon> { - self.favicon.as_ref() - } - - fn stylesheets(&self) -> &Assets<StyleSheet> { - &self.stylesheets - } - - fn javascripts(&self) -> &Assets<JavaScript> { - &self.javascripts - } - - fn responsive_styles(&self) -> &ResponsiveStyles { - &self.responsives - } - - fn body_props(&self) -> &Props { - &self.body_props - } - - // **< Contextual HELPERS >********************************************************************* - - fn remove_param(&mut self, key: &'static str) -> bool { - self.params.remove(key).is_some() - } } diff --git a/src/core/component/context/contextual.rs b/src/core/component/context/contextual.rs index 19e2d3e5..63c54eaa 100644 --- a/src/core/component/context/contextual.rs +++ b/src/core/component/context/contextual.rs @@ -1,14 +1,19 @@ -use super::{AssetsOp, ContextError}; +use super::{AssetsOp, Context, ContextError}; use crate::auth::CurrentUser; -use crate::builder_impl; -use crate::core::component::ChildOp; -use crate::core::theme::{RegionRef, TemplateRef, ThemeRef}; +use crate::core::TypeInfo; +use crate::core::component::{ChildOp, Component, MessageLevel, StatusMessage}; +use crate::core::theme::{CoreRegions, RegionRef, TemplateRef, ThemeRef, default_theme}; use crate::datetime::{DateFormat, DatePrecision, RelativeFormat, TimeFormat}; use crate::datetime::{DateInputError, DateTime, NaiveDate, NaiveTime, Tz, Utc}; -use crate::html::{Assets, Favicon, JavaScript, Props, PropsOp, ResponsiveStyles, StyleSheet}; -use crate::locale::{LangId, Lc}; +use crate::html::StyleSheet; +use crate::html::{Assets, Favicon, JavaScript, Props, PropsOp, ResponsiveStyles, RoutePath}; +use crate::locale::{LangId, LanguageIdentifier, Lc, RequestLocale}; +use crate::response::read_flash_messages; use crate::web::HttpRequest; +use crate::{CowStr, builder_impl, util}; + +use std::any::TypeId; // RFC 3339 con el offset de la zona horaria activa (no UTC fijo): igual en todos los idiomas, no // es una clave Fluent. Usado sólo por `format_iso_datetime()`. @@ -16,22 +21,31 @@ const ISO_DATETIME: &str = "%Y-%m-%dT%H:%M:%S%:z"; /// Interfaz para gestionar el **contexto de renderizado** de un documento HTML. /// -/// `Contextual` extiende [`LangId`] para establecer el idioma del documento y añade métodos para: +/// Todo lo que implementa `Contextual` es también proveedor de idioma ([`LangId`]), con el idioma +/// del documento, así que puede usarse directamente en [`Lc::lookup()`] o [`Lc::using()`]. Además, +/// ofrece métodos para: /// -/// - Almacenar la **petición HTTP** de origen. +/// - Establecer el **idioma** del documento ([`with_langid()`](Self::with_langid)). +/// - Almacenar la **petición HTTP** de origen ([`with_request()`](Self::with_request)). /// - Conocer la **identidad del usuario actual** ([`current_user()`](Self::current_user)) y la /// **zona horaria efectiva** del documento ([`timezone()`](Self::timezone)). /// - Seleccionar el **tema** y la **plantilla** de renderizado. +/// - Definir el **título**, la **descripción** y los **metadatos** del documento. /// - Administrar **recursos** del documento como el icono [`Favicon`], las hojas de estilo /// [`StyleSheet`] o los scripts [`JavaScript`], directamente o mediante una operación /// [`AssetsOp`]. /// - Leer y mantener **parámetros dinámicos tipados** de contexto. +/// - Construir **rutas** que preserven el idioma ([`route()`](Self::route)) e **identificadores** +/// únicos ([`build_id()`](Self::build_id)). +/// - Acumular **mensajes para el usuario** ([`push_message()`](Self::push_message)). /// - Formatear **fechas y horas** ([`format_date()`](Self::format_date), /// [`format_time()`](Self::format_time), [`format_datetime()`](Self::format_datetime) y demás) /// para la zona horaria e idioma del documento. /// -/// Lo implementan, típicamente, estructuras que manejan el contexto de renderizado, como -/// [`Context`](crate::core::component::Context) o [`Page`](crate::response::Page). +/// Todos los métodos actúan sobre el [`Context`] que devuelven [`context()`](Self::context) y +/// [`context_mut()`](Self::context_mut), los únicos que hay que implementar. Lo implementan +/// [`Context`] (que se devuelve a sí mismo) y [`Page`](crate::response::Page) (que devuelve el +/// suyo), así que ambos ofrecen exactamente la misma interfaz. /// /// # Ejemplo /// @@ -49,11 +63,23 @@ const ISO_DATETIME: &str = "%Y-%m-%dT%H:%M:%S%:z"; /// } /// ``` #[builder_impl] -pub trait Contextual: LangId { +pub trait Contextual { + /// Devuelve una referencia al contexto de renderizado. + fn context(&self) -> &Context; + + /// Devuelve una referencia mutable al contexto de renderizado. + /// + /// Resulta útil para pasar el contexto a funciones o componentes que lo reciben como parámetro + /// (`&mut Context`). + fn context_mut(&mut self) -> &mut Context; + // **< Contextual BUILDER >********************************************************************* /// Establece el idioma del documento. - fn with_langid(self, language: &impl LangId) -> Self; + fn with_langid(self, language: &impl LangId) -> Self { + self.context_mut().locale.with_langid(language); + self + } /// Fuerza la zona horaria que se utilizará para mostrar fechas y horas en el documento. /// @@ -61,7 +87,10 @@ pub trait Contextual: LangId { /// aplicación) por otra explícita. Ver [`CurrentUser::timezone()`]. /// /// [`CurrentUser::timezone()`]: crate::auth::CurrentUser::timezone - fn with_timezone(self, tz: Tz) -> Self; + fn with_timezone(self, tz: Tz) -> Self { + self.context_mut().timezone = tz; + self + } /// Almacena la petición HTTP de origen en el contexto. /// @@ -77,13 +106,36 @@ pub trait Contextual: LangId { /// [`current_user()`]: Self::current_user /// [`timezone()`]: Self::timezone /// [`theme()`]: Self::theme - fn with_request(self, request: Option<HttpRequest>) -> Self; + fn with_request(self, request: Option<HttpRequest>) -> Self { + let cx = self.context_mut(); + // Los mensajes para la página siguiente se leen una sola vez, con la primera petición (las + // páginas de error, p. ej., parten de un contexto sin petición). + if cx.request.is_none() + && let Some(request) = &request + { + cx.messages.extend(read_flash_messages(request.headers())); + } + cx.request = request; + // Recalcula el *locale*, el usuario actual, la zona horaria y el tema según la nueva + // petición y la política de negociación configurada. + cx.locale = RequestLocale::from_request(cx.request.as_ref()); + cx.current_user = Context::resolve_current_user(cx.request.as_ref()); + cx.timezone = cx.current_user.timezone(); + cx.theme = cx.current_user.theme().unwrap_or_else(default_theme); + self + } /// Especifica el tema para renderizar el documento. - fn with_theme(self, theme: ThemeRef) -> Self; + fn with_theme(self, theme: ThemeRef) -> Self { + self.context_mut().theme = theme; + self + } /// Especifica la plantilla para renderizar el documento. - fn with_template(self, template: TemplateRef) -> Self; + fn with_template(self, template: TemplateRef) -> Self { + self.context_mut().template = template; + self + } /// Añade o modifica un parámetro dinámico del contexto. /// @@ -100,28 +152,122 @@ pub trait Contextual: LangId { /// .with_param("title", "Hello".to_string()) /// .with_param("flags", vec!["a", "b"]); /// ``` - fn with_param<T: Send + Sync + 'static>(self, key: &'static str, value: T) -> Self; + fn with_param<T: Send + Sync + 'static>(self, key: &'static str, value: T) -> Self { + let type_name = TypeInfo::FullName.of::<T>(); + self.context_mut() + .params + .insert(key, (Box::new(value), type_name)); + self + } /// Añade un recurso ([`Favicon`], [`StyleSheet`], [`JavaScript`] o /// [`Preload`](crate::html::Preload)) directamente, o aplica una operación [`AssetsOp`] sobre /// los recursos del contexto. - fn with_assets(self, op: impl Into<AssetsOp>) -> Self; + fn with_assets(self, op: impl Into<AssetsOp>) -> Self { + let cx = self.context_mut(); + match op.into() { + // Favicon. + AssetsOp::SetFavicon(favicon) => { + cx.favicon = favicon; + } + AssetsOp::SetFaviconIfNone(icon) => { + if cx.favicon.is_none() { + cx.favicon = Some(icon); + } + } + // Preloads. + AssetsOp::AddPreload(preload) => { + cx.preloads.add(preload); + } + AssetsOp::RemovePreload(path) => { + cx.preloads.remove(path); + } + // Stylesheets. + AssetsOp::AddStyleSheet(css) => { + cx.stylesheets.add(css); + } + AssetsOp::RemoveStyleSheet(path) => { + cx.stylesheets.remove(path); + } + // Scripts JavaScript. + AssetsOp::AddJavaScript(js) => { + cx.javascripts.add(js); + } + AssetsOp::RemoveJavaScript(path) => { + cx.javascripts.remove(path); + } + // Estilos responsive. + AssetsOp::AddResponsiveStyle(breakpoint, classes, property, value) => { + cx.responsives + .add_style(breakpoint, classes, property, value); + } + AssetsOp::AddResponsiveStyles(breakpoint, classes, styles) => { + cx.responsives.add_styles(breakpoint, classes, styles); + } + } + self + } + + /// Establece el título del documento como un valor traducible. + /// + /// Además de usarse en el `<head>`, lo ven las plantillas y los componentes al renderizarse, + /// como el marco de las páginas del panel de administración + /// ([`AdminFrame`](crate::base::component::AdminFrame)), que lo muestra como encabezado. + fn with_title(self, title: Lc) -> Self { + self.context_mut().title = title; + self + } + + /// Establece la descripción del documento como un valor traducible. + /// + /// Se usa en la etiqueta `<meta name="description">` del `<head>`. + fn with_description(self, description: Lc) -> Self { + self.context_mut().description = description; + self + } + + /// Añade una entrada `<meta name="..." content="...">` al `<head>`. + fn with_metadata(self, name: &'static str, content: impl Into<CowStr>) -> Self { + self.context_mut().metadata.push((name, content.into())); + self + } + + /// Añade una entrada `<meta property="..." content="...">` al `<head>`. + fn with_property(self, property: &'static str, content: impl Into<CowStr>) -> Self { + self.context_mut() + .properties + .push((property, content.into())); + self + } /// Modifica identificador, clases CSS, atributos HTML o valores extra del elemento `<body>`. - fn with_body_props(self, op: PropsOp) -> Self; + fn with_body_props(self, op: PropsOp) -> Self { + self.context_mut().body_props.alter_prop(op); + self + } /// Añade un componente o aplica una operación [`ChildOp`] en la región por defecto del /// documento. - fn with_child(self, op: impl Into<ChildOp>) -> Self; + fn with_child(self, op: impl Into<ChildOp>) -> Self { + self.context_mut() + .regions + .alter_child_in(&CoreRegions::Content, op.into()); + self + } /// Añade un componente o aplica una operación [`ChildOp`] en una región específica del /// documento. - fn with_child_in(self, region: RegionRef, op: impl Into<ChildOp>) -> Self; + fn with_child_in(self, region: RegionRef, op: impl Into<ChildOp>) -> Self { + self.context_mut().regions.alter_child_in(region, op.into()); + self + } // **< Contextual GETTERS >********************************************************************* /// Devuelve una referencia a la petición HTTP asociada, si existe. - fn request(&self) -> Option<&HttpRequest>; + fn request(&self) -> Option<&HttpRequest> { + self.context().request.as_ref() + } /// Devuelve la identidad del usuario actual. /// @@ -141,7 +287,9 @@ pub trait Contextual: LangId { /// page.render().await /// } /// ``` - fn current_user(&self) -> &CurrentUser; + fn current_user(&self) -> &CurrentUser { + &self.context().current_user + } /// Devuelve la zona horaria efectiva para mostrar fechas y horas en el documento. /// @@ -154,13 +302,19 @@ pub trait Contextual: LangId { /// /// [`with_request()`]: Self::with_request /// [`CurrentUser::timezone()`]: crate::auth::CurrentUser::timezone - fn timezone(&self) -> Tz; + fn timezone(&self) -> Tz { + self.context().timezone + } /// Devuelve el tema que se usará para renderizar el documento. - fn theme(&self) -> ThemeRef; + fn theme(&self) -> ThemeRef { + self.context().theme + } /// Devuelve la plantilla configurada para renderizar el documento. - fn template(&self) -> TemplateRef; + fn template(&self) -> TemplateRef { + self.context().template + } /// Recupera una *referencia tipada* al parámetro solicitado. /// @@ -184,7 +338,19 @@ pub trait Contextual: LangId { /// // Error de tipo: /// assert!(cx.param::<String>("user_id").is_err()); /// ``` - fn param<T: 'static>(&self, key: &'static str) -> Result<&T, ContextError>; + fn param<T: 'static>(&self, key: &'static str) -> Result<&T, ContextError> { + let (any, type_name) = self + .context() + .params + .get(key) + .ok_or(ContextError::ParamNotFound)?; + any.downcast_ref::<T>() + .ok_or_else(|| ContextError::ParamTypeMismatch { + key, + expected: TypeInfo::FullName.of::<T>(), + saved: type_name, + }) + } /// Devuelve el parámetro clonado o el **valor por defecto del tipo** (`T::default()`). fn param_or_default<T: Clone + Default + 'static>(&self, key: &'static str) -> T { @@ -202,22 +368,164 @@ pub trait Contextual: LangId { } /// Devuelve el Favicon de los recursos del contexto. - fn favicon(&self) -> Option<&Favicon>; + fn favicon(&self) -> Option<&Favicon> { + self.context().favicon.as_ref() + } /// Devuelve las hojas de estilo de los recursos del contexto. - fn stylesheets(&self) -> &Assets<StyleSheet>; + fn stylesheets(&self) -> &Assets<StyleSheet> { + &self.context().stylesheets + } /// Devuelve los scripts JavaScript de los recursos del contexto. - fn javascripts(&self) -> &Assets<JavaScript>; + fn javascripts(&self) -> &Assets<JavaScript> { + &self.context().javascripts + } /// Devuelve los estilos *responsive* acumulados en el contexto. - fn responsive_styles(&self) -> &ResponsiveStyles; + fn responsive_styles(&self) -> &ResponsiveStyles { + &self.context().responsives + } + + /// Devuelve el título del documento, o [`Lc::none()`] si no tiene. + fn title(&self) -> &Lc { + &self.context().title + } + + /// Devuelve la descripción del documento, o [`Lc::none()`] si no tiene. + fn description(&self) -> &Lc { + &self.context().description + } + + /// Devuelve la lista de metadatos `<meta name=...>`. + fn metadata(&self) -> &[(&'static str, CowStr)] { + &self.context().metadata + } + + /// Devuelve la lista de propiedades `<meta property=...>`. + fn properties(&self) -> &[(&'static str, CowStr)] { + &self.context().properties + } /// Devuelve identificador, clases CSS, atributos HTML y valores extra del elemento `<body>`. - fn body_props(&self) -> &Props; + fn body_props(&self) -> &Props { + &self.context().body_props + } + + /// Devuelve los mensajes de usuario acumulados que aún no ha mostrado ningún componente + /// [`Messages`](crate::base::component::Messages). + fn messages(&self) -> &[StatusMessage] { + &self.context().messages + } + + /// Indica si hay mensajes de usuario acumulados que aún no ha mostrado ningún componente + /// [`Messages`](crate::base::component::Messages). + fn has_messages(&self) -> bool { + !self.context().messages.is_empty() + } // **< Contextual HELPERS >********************************************************************* + /// Construye una ruta aplicada al contexto actual. + /// + /// Acepta cualquier tipo convertible a [`RoutePath`] (un literal, un `String`, un `&str` de + /// cualquier vida, o un [`RoutePath`] ya construido con sus propios parámetros). Si la política + /// de negociación del idioma ([`LangNegotiation`](crate::global::LangNegotiation)) indica que + /// debe propagarse el idioma para esta petición, se añade o actualiza automáticamente el + /// parámetro de *query* `lang=...` con el identificador de idioma definido en el contexto. + /// + /// Esto garantiza que los enlaces generados desde el contexto preservan la preferencia de + /// idioma del usuario durante la navegación. Si `path` **parece** una URL externa (ver + /// [`util::url_looks_external()`](crate::util::url_looks_external)), nunca se le añade `lang`. + /// + /// Este método asume que ya tienes `cx` a mano en el momento de construir la ruta (dentro de + /// `prepare()`, un *handler* HTTP, etc.). Si lo que estás definiendo es un campo de componente + /// que se construye una sola vez y se reutiliza en peticiones futuras (un menú, un botón, + /// etc.), usa [`Route`](crate::core::component::Route) en su lugar (su documentación explica el + /// criterio completo para elegir entre ambos). + fn route(&self, path: impl Into<RoutePath>) -> RoutePath { + let locale = &self.context().locale; + let mut route = path.into(); + if !route.is_external() && locale.needs_lang_query() { + route.alter_param("lang", locale.lang_query_value()); + } + route + } + + /// Construye un identificador HTML único para el tipo de componente `C`. + /// + /// Toma los `segments` finales del *path* completo del tipo, los une con `-` y los convierte a + /// minúsculas, y añade un contador independiente por tipo. Por ejemplo, para `MyApp::ui::Menu` + /// con `segments = 2` devuelve `ui-menu-1` la primera vez que se invoca para ese tipo, + /// `ui-menu-2` la segunda, etc. + /// + /// Con `segments = 1` se usa sólo el nombre corto del tipo. Si `segments` es `0` o supera el + /// número de segmentos del *path*, se usan todos. + /// + /// Es útil para asignar identificadores cuando el componente no recibe uno explícito. El + /// contador es local a este contexto y se reinicia para cada nueva petición. + fn build_id<C: Component>(&self, segments: usize) -> String { + let path: Vec<&str> = TypeInfo::FullName.of::<C>().split("::").collect(); + let segments = if segments == 0 || segments >= path.len() { + path.len() + } else { + segments + }; + let count = { + let mut map = self.context().id_counters.lock(); + let n = map.entry(TypeId::of::<C>()).or_insert(0); + *n += 1; + *n + }; + let prefix = path[path.len() - segments..].join("-").to_lowercase(); + util::join!(prefix, "-", count.to_string()) + } + + /// Devuelve `id` si contiene un valor, o genera uno único con [`build_id`](Self::build_id) + /// si es `None`. + fn required_id<C: Component>(&self, id: Option<String>, segments: usize) -> String { + match id { + Some(id) => id, + None => self.build_id::<C>(segments), + } + } + + /// Acumula un [`StatusMessage`] en el contexto para notificar al usuario. + /// + /// Pueden generarse en cualquier punto del ciclo de una petición web (handlers, renderizado, + /// lógica de negocio, etc.) que tengan acceso al contexto. Los muestra, y los retira, el primer + /// componente [`Messages`](crate::base::component::Messages) que se renderice después de + /// añadirlos: uno propio de la página, si lo hay, o el que encabeza la región + /// [`CoreRegions::Content`], que se renderiza una vez renderizado el resto del `<body>` y + /// recoge los que queden. + /// + /// # Ejemplo + /// + /// ```rust,no_run + /// # use pagetop::prelude::*; + /// # let mut cx = Context::default(); + /// cx.push_message(MessageLevel::Warning, Lc::n("Session is not valid")); + /// ``` + fn push_message(&mut self, level: MessageLevel, text: Lc) { + self.context_mut() + .messages + .push(StatusMessage::new(level, text)); + } + + /// Elimina un parámetro del contexto. Devuelve `true` si la clave existía y se eliminó. + /// + /// # Ejemplo + /// + /// ```rust + /// # use pagetop::prelude::*; + /// let mut cx = Context::default().with_param("temp", 1u8); + /// assert!(cx.remove_param("temp")); + /// assert!(!cx.remove_param("temp")); // ya no existe + /// ``` + fn remove_param(&mut self, key: &'static str) -> bool { + self.context_mut().params.remove(key).is_some() + } + /// Formatea una fecha y hora completas en la zona horaria efectiva del documento /// ([`timezone()`](Self::timezone)), combinando un [`DateFormat`] y un [`TimeFormat`] /// independientes (posiblemente distintos entre sí, como una fecha larga con la hora corta), @@ -471,16 +779,19 @@ pub trait Contextual: LangId { { crate::datetime::input::parse_datetime(text, self, self.timezone()) } - - /// Elimina un parámetro del contexto. Devuelve `true` si la clave existía y se eliminó. - /// - /// # Ejemplo - /// - /// ```rust - /// # use pagetop::prelude::*; - /// let mut cx = Context::default().with_param("temp", 1u8); - /// assert!(cx.remove_param("temp")); - /// assert!(!cx.remove_param("temp")); // ya no existe - /// ``` - fn remove_param(&mut self, key: &'static str) -> bool; +} + +/// Cualquier contexto de renderizado es proveedor de idioma, con el idioma del documento. +/// +/// El idioma lo resuelve [`RequestLocale`], que tiene en cuenta la petición HTTP (parámetro `?lang` +/// e idioma preferido del usuario), la configuración global de idioma de la aplicación, la cabecera +/// `Accept-Language` y/o el idioma de respaldo, según la negociación indicada en +/// [`global::SETTINGS.app.lang_negotiation`]. +/// +/// [`global::SETTINGS.app.lang_negotiation`]: crate::global::AppSettings::lang_negotiation +impl<T: Contextual> LangId for T { + #[inline] + fn langid(&self) -> &'static LanguageIdentifier { + self.context().locale.langid() + } } diff --git a/src/core/component/route.rs b/src/core/component/route.rs index 2b118b26..e2eb317d 100644 --- a/src/core/component/route.rs +++ b/src/core/component/route.rs @@ -1,4 +1,4 @@ -use crate::core::component::Context; +use crate::core::component::{Context, Contextual}; use crate::html::RoutePath; use crate::util; diff --git a/src/core/extension/all.rs b/src/core/extension/all.rs index ccccbb39..fdeabdab 100644 --- a/src/core/extension/all.rs +++ b/src/core/extension/all.rs @@ -1,8 +1,10 @@ +use crate::admin::build_admin_registry; +use crate::auth::build_permission_registry; use crate::core::action::publish_actions; use crate::core::extension::ExtensionRef; use crate::core::theme::ThemeRef; use crate::core::theme::all::register_theme; -use crate::web::Router; +use crate::web::{Layers, Router, Routes, StaticFiles}; use crate::{BoxError, config, global, serve_static_files, trace, web}; use std::sync::OnceLock; @@ -42,6 +44,14 @@ pub enum StartupError { #[source] source: BoxError, }, + /// Rutas del panel de administración montadas sin + /// [`Routes::admin_route()`](crate::web::Routes::admin_route), o que no cuelgan de una página + /// declarada. + #[error( + "Administration routes must use admin_route() and hang from a declared page: {}", + .0.join(", ") + )] + InvalidAdminRoutes(Vec<String>), } // **< REGISTRO DE LAS EXTENSIONES >**************************************************************** @@ -127,6 +137,12 @@ pub fn register_actions() { .flat_map(|extension| extension.actions()) .collect() }); + // El catálogo de permisos se construye con las acciones ya publicadas y antes de inicializar + // las extensiones, que pueden consultarlo en `initialize()`. + build_permission_registry(); + // Luego el registro del panel, cuyas acciones de declaración pueden consultar ya el catálogo + // de permisos. + build_admin_registry(); } // **< CARGA LOS AJUSTES >************************************************************************** @@ -224,7 +240,11 @@ pub async fn shutdown_extensions() { // **< CONFIGURA LAS RUTAS >************************************************************************ -pub fn configure_routes(router: Router) -> Router { +/// Añade las rutas de todas las extensiones, cada una con su acceso. +/// +/// Devuelve un error si alguna ruta del panel de administración no se monta con +/// [`Routes::admin_route()`](crate::web::Routes::admin_route) o no cuelga de una página declarada. +pub fn configure_routes(router: Router) -> Result<Router, StartupError> { // Sólo compila durante el desarrollo, para evitar errores 400 en la traza de eventos. #[cfg(debug_assertions)] let router = router.route( @@ -236,7 +256,9 @@ pub fn configure_routes(router: Router) -> Router { .get() .into_iter() .flatten() - .fold(router, |r, e| e.configure_router(r)) + .fold(Routes::new(router), |r, e| e.configure_router(r)) + .into_router() + .map_err(StartupError::InvalidAdminRoutes) } // **< CONFIGURA EL MIDDLEWARE GLOBAL >************************************************************* @@ -251,7 +273,8 @@ pub fn configure_middleware(router: Router) -> Router { .get() .into_iter() .flatten() - .fold(router, |r, e| e.configure_middleware(r)) + .fold(Layers::new(router), |l, e| e.configure_middleware(l)) + .into_router() } // **< CONFIGURA LOS ARCHIVOS ESTÁTICOS >*********************************************************** @@ -261,15 +284,15 @@ pub fn configure_middleware(router: Router) -> Router { /// Se llama después de [`configure_middleware`], para que estas rutas no pasen por las capas de /// middleware de las extensiones. pub fn configure_static_files(router: Router) -> Router { - let router = EXTENSIONS + let files = EXTENSIONS .get() .into_iter() .flatten() - .fold(router, |r, e| e.configure_static_files(r)); + .fold(StaticFiles::new(router), |f, e| e.configure_static_files(f)); - serve_static_files!(router, [&global::SETTINGS.dev.pagetop_static_dir, assets] => "/pagetop"); + serve_static_files!(files, [&global::SETTINGS.dev.pagetop_static_dir, assets] => "/pagetop"); - router + files.into_router() } #[cfg(test)] diff --git a/src/core/extension/definition.rs b/src/core/extension/definition.rs index ca163357..4404bf01 100644 --- a/src/core/extension/definition.rs +++ b/src/core/extension/definition.rs @@ -6,7 +6,7 @@ use crate::core::AnyInfo; use crate::core::action::ActionBox; use crate::core::theme::ThemeRef; use crate::locale::Lc; -use crate::web::Router; +use crate::web::{Layers, Routes, StaticFiles}; /// Interfaz común que debe implementar cualquier extensión de PageTop. /// @@ -246,29 +246,30 @@ pub trait Extension: AnyInfo + Send + Sync { None } - /// Registra rutas, servicios y capas de la extensión en el servidor web de la aplicación. + /// Registra las rutas de la extensión en el servidor web de la aplicación. /// - /// Recibe las rutas acumuladas hasta ese momento, añade lo que la extensión necesite y retorna - /// las rutas con las nuevas modificaciones. La implementación por defecto devuelve las rutas - /// sin cambios. + /// Recibe las rutas acumuladas hasta ese momento, añade las de la extensión y las devuelve. La + /// implementación por defecto las devuelve sin cambios. /// - /// # Operaciones disponibles + /// Cada ruta se monta con su acceso ([`Access`]): quién puede llegar a su *handler*, que + /// PageTop comprueba antes. No hay forma de montar una sin indicarlo; una ruta pública se + /// monta con [`Routes::public_route()`], que equivale a [`Access::Public`]. Ver [`Routes`] para + /// las operaciones disponibles. /// - /// | Operación | Llamada sobre `router` | - /// |----------------------------------|----------------------------------------------------| - /// | Ruta HTTP | `.route("/path", web::get(handler))` | - /// | Rutas bajo prefijo común | `.nest("/prefix", sub_router)` | - /// | Estado compartido entre handlers | `.with_state(my_state)` | - /// - /// Los archivos estáticos se registran normalmente en [`configure_static_files`], donde no - /// pasan por el middleware de las extensiones. + /// Los archivos estáticos se registran en [`configure_static_files`], donde no pasan por el + /// middleware de las extensiones. /// /// # Ejemplos /// - /// ## Rutas HTTP básicas + /// ## Rutas con su acceso /// /// ```rust,no_run /// # use pagetop::prelude::*; + /// # #[derive(Clone, Copy, Debug)] + /// # enum BlogPermission { Publish } + /// # impl Permission for BlogPermission { + /// # fn key(&self) -> CowStr { "blog:publish".into() } + /// # } /// # async fn list_posts() -> &'static str { "" } /// # async fn view_post() -> &'static str { "" } /// # async fn create_post() -> &'static str { "" } @@ -276,45 +277,20 @@ pub trait Extension: AnyInfo + Send + Sync { /// /// #[async_trait] /// impl Extension for Blog { - /// fn configure_router(&self, router: Router) -> Router { - /// router - /// .route("/posts", web::get(list_posts)) - /// .route("/posts/{id}", web::get(view_post)) - /// .route("/posts/new", web::post(create_post)) + /// fn configure_router(&self, routes: Routes) -> Routes { + /// let publish = Access::Permission(&BlogPermission::Publish); + /// routes + /// .public_route("/posts", web::get(list_posts)) + /// .public_route("/posts/{id}", web::get(view_post)) + /// .route("/posts/new", publish, web::post(create_post)) /// } /// } /// ``` /// - /// ## Rutas agrupadas bajo un prefijo + /// ## Rutas agrupadas con su propio middleware /// - /// ```rust,no_run - /// # use pagetop::prelude::*; - /// # async fn dashboard() -> &'static str { "" } - /// # async fn list_users() -> &'static str { "" } - /// pub struct Admin; - /// - /// #[async_trait] - /// impl Extension for Admin { - /// fn configure_router(&self, router: Router) -> Router { - /// let admin = Router::new() - /// .route("/dashboard", web::get(dashboard)) - /// .route("/users", web::get(list_users)); - /// - /// router.nest("/admin", admin) - /// } - /// } - /// ``` - /// - /// ## Rutas con middleware acotado a esta extensión - /// - /// Cada `Router` mantiene su propia pila de middleware independiente. Cuando se crea un - /// `Router::new()` separado y se llama a `.layer()` sobre él, esa capa sólo se aplica a las - /// rutas de ese router concreto. Al fusionarlo con `.merge()` en el `router` principal, cada - /// ruta se añade con su middleware asociado, sin tocar las demás. - /// - /// Otra cosa es llamar a `.layer()` directamente sobre el `router` principal que se recibe como - /// parámetro, porque ese objeto ya contiene todas las rutas acumuladas por extensiones - /// anteriores, y la capa se aplica a todas las rutas, no sólo a las propias. + /// Un `Router::new()` aparte, con sus capas, se añade bajo un prefijo con + /// [`Routes::nest()`]: sus capas sólo envuelven sus rutas, y todas comparten el mismo acceso. /// /// ```rust,ignore /// # use pagetop::prelude::*; @@ -322,11 +298,11 @@ pub trait Extension: AnyInfo + Send + Sync { /// /// #[async_trait] /// impl Extension for Api { - /// fn configure_router(&self, router: Router) -> Router { + /// fn configure_router(&self, routes: Routes) -> Routes { /// let api = Router::new() - /// .route("/api/data", web::get(get_data)) - /// .layer(auth_layer()); - /// router.merge(api) + /// .route("/data", web::get(get_data)) + /// .layer(api_key_layer()); + /// routes.nest("/api", Access::Public, api) /// } /// } /// ``` @@ -334,10 +310,15 @@ pub trait Extension: AnyInfo + Send + Sync { /// Para el middleware que deba cubrir las rutas de **todas** las extensiones, usar /// [`configure_middleware`]. /// + /// [`Access`]: crate::auth::Access + /// [`Access::Public`]: crate::auth::Access::Public + /// [`Routes`]: crate::web::Routes + /// [`Routes::public_route()`]: crate::web::Routes::public_route + /// [`Routes::nest()`]: crate::web::Routes::nest /// [`configure_static_files`]: Self::configure_static_files /// [`configure_middleware`]: Self::configure_middleware - fn configure_router(&self, router: Router) -> Router { - router + fn configure_router(&self, routes: Routes) -> Routes { + routes } /// Añade capas de middleware globales a las rutas de la aplicación. @@ -364,13 +345,16 @@ pub trait Extension: AnyInfo + Send + Sync { /// /// #[async_trait] /// impl Extension for MyAuth { - /// fn configure_middleware(&self, router: Router) -> Router { - /// router.layer(web::middleware::from_fn(session_middleware)) + /// fn configure_middleware(&self, layers: Layers) -> Layers { + /// layers.layer(web::middleware::from_fn(session_middleware)) /// } /// } /// ``` - fn configure_middleware(&self, router: Router) -> Router { - router + /// + /// Sólo admite capas ([`Layers`](crate::web::Layers)): las rutas se registran en + /// [`configure_router`](Self::configure_router), con su acceso. + fn configure_middleware(&self, layers: Layers) -> Layers { + layers } /// Registra los archivos estáticos de la extensión (hojas de estilo, *scripts*, fuentes, @@ -381,12 +365,13 @@ pub trait Extension: AnyInfo + Send + Sync { /// **después** de [`configure_middleware`](Self::configure_middleware), así que estas rutas /// **no** pasan por las capas de middleware de las extensiones (p. ej. la resolución de /// sesión). Una página carga muchos recursos; sin esta separación, cada uno repetiría ese - /// trabajo, que no necesita. La implementación por defecto devuelve las rutas sin cambios. + /// trabajo, que no necesita. Por eso son siempre públicos. La implementación por defecto los + /// devuelve sin cambios. /// - /// Si algún archivo sí debe pasar por el middleware (p. ej. descargas que requieran una sesión - /// iniciada), se registra en [`configure_router`](Self::configure_router). + /// Si algún archivo debe pasar por el middleware o exigir un acceso (p. ej. descargas que + /// requieran una sesión iniciada), se registra en [`configure_router`](Self::configure_router). /// - /// La macro [`serve_static_files!`](crate::serve_static_files) sombrea `router` internamente, + /// La macro [`serve_static_files!`](crate::serve_static_files) sombrea `files` internamente, /// por lo que el parámetro no necesita `mut`. Sí es necesario devolverlo al final. /// /// # Ejemplo @@ -397,14 +382,14 @@ pub trait Extension: AnyInfo + Send + Sync { /// /// #[async_trait] /// impl Extension for MyExtension { - /// fn configure_static_files(&self, router: Router) -> Router { - /// serve_static_files!(router, [assets] => "/static"); - /// router + /// fn configure_static_files(&self, files: StaticFiles) -> StaticFiles { + /// serve_static_files!(files, [assets] => "/static"); + /// files /// } /// } /// ``` - fn configure_static_files(&self, router: Router) -> Router { - router + fn configure_static_files(&self, files: StaticFiles) -> StaticFiles { + files } } diff --git a/src/core/theme/definition.rs b/src/core/theme/definition.rs index e8934daf..00624fd6 100644 --- a/src/core/theme/definition.rs +++ b/src/core/theme/definition.rs @@ -192,7 +192,9 @@ pub trait Theme: Extension + Send + Sync { parent.render_page_body(page).await } else { let template = page.template(); - layout::Template::of(template).render(page.context()).await + layout::Template::of(template) + .render(page.context_mut()) + .await } } @@ -240,13 +242,13 @@ pub trait Theme: Extension + Send + Sync { html! { meta charset="utf-8"; - @if let Some(title) = page.title() { + @if let Some(title) = page.title().lookup(page) { title { (global::SETTINGS.app.name) (" | ") (title) } } @else { title { (global::SETTINGS.app.name) } } - @if let Some(description) = page.description() { + @if let Some(description) = page.description().lookup(page) { meta name="description" content=(description); } @@ -260,7 +262,7 @@ pub trait Theme: Extension + Send + Sync { meta property=(property) content=(content) {} } - (page.context().render_assets()) + (page.context_mut().render_assets()) } } diff --git a/src/core/theme/layout.rs b/src/core/theme/layout.rs index 09313df1..8eadb1cb 100644 --- a/src/core/theme/layout.rs +++ b/src/core/theme/layout.rs @@ -103,7 +103,7 @@ pub enum CoreRegions { /// [`Messages`]: crate::base::component::Messages /// [`Messages::with_deferred()`]: crate::base::component::Messages::with_deferred /// [`Context`]: crate::core::component::Context - /// [`Context::push_message()`]: crate::core::component::Context::push_message + /// [`Context::push_message()`]: crate::core::component::Contextual::push_message /// [`ResponseExt::with_message()`]: crate::response::ResponseExt::with_message #[default] Content, @@ -177,7 +177,13 @@ pub enum CoreTemplates { /// Plantilla para la **interfaz de administración**, de nombre `"admin"`. /// - /// Se utiliza para páginas de administración o paneles de control. + /// Se utiliza para las páginas del panel de administración ([`Page::admin()`]): además de las + /// regiones de `Standard`, pinta la navegación del panel ([`AdminMenu`]) y el marco de la + /// página ([`AdminFrame`]) alrededor de la región de contenido. + /// + /// [`Page::admin()`]: crate::response::Page::admin + /// [`AdminMenu`]: crate::base::component::AdminMenu + /// [`AdminFrame`]: crate::base::component::AdminFrame Admin, } @@ -193,8 +199,8 @@ impl TemplateName for CoreTemplates { #[inline] fn label(&self) -> Lc { match self { - Self::Standard => Lc::l("template-standard"), - Self::Admin => Lc::l("template-admin"), + Self::Standard => Lc::l("template_standard"), + Self::Admin => Lc::l("template_admin"), } } } diff --git a/src/global.rs b/src/global.rs index 63a79bc5..43daf7cd 100644 --- a/src/global.rs +++ b/src/global.rs @@ -169,6 +169,15 @@ pub struct AppSettings { /// [`CurrentUser::timezone()`]: crate::auth::CurrentUser::timezone #[default = true] pub timezone_per_user: bool, + /// Ruta raíz del panel de administración (p. ej. *"/admin"* o *"/manage"*). + /// + /// Las secciones y páginas del panel se declaran con rutas relativas a ella, y + /// [`admin_path()`](crate::admin::admin_path) devuelve la ruta completa. Debe empezar por `/`, + /// sin `/` final, y cada tramo sólo puede tener letras y dígitos ASCII, `-`, `_`, `.` y `~`, + /// sin ser `.` ni `..`; si no, la aplicación no arranca. + #[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)] @@ -308,6 +317,29 @@ fn origins<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<String>, D: .collect() } +// Ruta para `admin_path`: absoluta, sin `/` final ni tramos vacíos, `.` o `..` (el navegador los +// resolvería antes de pedirla), y sin caracteres que el enrutador interprete (`{`, `}`, `*`...) o +// que haya que codificar en una URL. +fn admin_path<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> { + let raw = String::deserialize(deserializer)?; + let path = raw.trim(); + let valid = path.strip_prefix('/').is_some_and(|rest| { + rest.split('/').all(|segment| { + !matches!(segment, "" | "." | "..") + && segment + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_.~".contains(&b)) + }) + }); + if !valid { + return Err(D::Error::custom(format!( + "invalid admin path \"{raw}\", expected an absolute path without a trailing slash \ + (e.g. \"/admin\")" + ))); + } + Ok(path.to_owned()) +} + // Nombre de cabecera para `client_ip_header`: vacío o un nombre de cabecera HTTP válido, sin // espacios en los extremos. Un nombre que no lo fuera nunca encontraría la cabecera, y // `HttpRequest::client_ip()` devolvería siempre `None` sin que nada lo indicase. @@ -409,6 +441,30 @@ mod tests { assert!(load("Forwarded").is_err()); } + #[test] + fn admin_path_must_be_an_absolute_path_without_a_trailing_slash() { + let load = |value: &str| { + let toml = format!("[app]\nadmin_path = \"{value}\"\n"); + config::load_from_str::<AppSettings>(&toml) + }; + assert_eq!(load(" /manage ").unwrap().admin_path, "/manage"); + assert_eq!(load("/site/admin-2").unwrap().admin_path, "/site/admin-2"); + for invalid in [ + "", + "/", + "admin", + "/admin/", + "/site//admin", + "/.", + "/site/../admin", + "/{admin}", + "/ad min", + ] { + let error = load(invalid).expect_err(invalid); + assert!(error.to_string().contains("invalid admin path"), "{error}"); + } + } + #[test] fn trusted_origins_are_normalized_and_validated() { let load = |value: &str| { diff --git a/src/global/lang_negotiation.rs b/src/global/lang_negotiation.rs index 6ab4de40..7a211689 100644 --- a/src/global/lang_negotiation.rs +++ b/src/global/lang_negotiation.rs @@ -11,7 +11,7 @@ use serde::{Deserialize, Deserializer}; /// /// [`global::SETTINGS.app.lang_negotiation`]: crate::global::AppSettings::lang_negotiation /// [`RequestLocale`]: crate::locale::RequestLocale -/// [`Context::route()`]: crate::core::component::Context::route +/// [`Context::route()`]: crate::core::component::Contextual::route #[derive(AutoDefault, Clone, Copy, Debug, Eq, PartialEq)] pub enum LangNegotiation { /// Usa todas las fuentes disponibles para determinar el idioma, en este orden: comprueba el diff --git a/src/lib.rs b/src/lib.rs index 10aa4801..7e49290a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -54,8 +54,8 @@ struct HelloWorld; #[async_trait] impl Extension for HelloWorld { - fn configure_router(&self, router: Router) -> Router { - router.route("/", web::get(hello_world)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/", web::get(hello_world)) } } @@ -219,6 +219,8 @@ pub mod datetime; pub mod core; // Identidad del usuario y sistema de autorización extensible. pub mod auth; +// Secciones y páginas del panel de administración que declaran las extensiones. +pub mod admin; // Respuestas a peticiones web en sus diferentes formatos. pub mod response; // Gestión del servidor y rutas web. diff --git a/src/locale/en-US/admin.ftl b/src/locale/en-US/admin.ftl new file mode 100644 index 00000000..a03a20a9 --- /dev/null +++ b/src/locale/en-US/admin.ftl @@ -0,0 +1,9 @@ +# Administration panel sections. +admin_section_people = People +admin_section_structure = Structure +admin_section_config = Configuration +admin_section_reports = Reports +admin_section_help = Help + +# Administration panel. +admin_dashboard = Administration diff --git a/src/locale/en-US/theme.ftl b/src/locale/en-US/theme.ftl index 885eb841..54957dd8 100644 --- a/src/locale/en-US/theme.ftl +++ b/src/locale/en-US/theme.ftl @@ -4,6 +4,10 @@ region_content = Content region_footer = Footer region_aside = Aside +# Templates. +template_standard = Standard +template_admin = Administration + # Error Messages. error_code = Error { $code } diff --git a/src/locale/es-ES/admin.ftl b/src/locale/es-ES/admin.ftl new file mode 100644 index 00000000..5dd88036 --- /dev/null +++ b/src/locale/es-ES/admin.ftl @@ -0,0 +1,9 @@ +# Administration panel sections. +admin_section_people = Personas +admin_section_structure = Estructura +admin_section_config = Configuración +admin_section_reports = Informes +admin_section_help = Ayuda + +# Administration panel. +admin_dashboard = Administración diff --git a/src/locale/es-ES/theme.ftl b/src/locale/es-ES/theme.ftl index d77ee3c9..6821ea6e 100644 --- a/src/locale/es-ES/theme.ftl +++ b/src/locale/es-ES/theme.ftl @@ -4,6 +4,10 @@ region_content = Contenido region_footer = Pie de página region_aside = Barra lateral +# Templates. +template_standard = Estándar +template_admin = Administración + # Error Messages. error_code = Error { $code } diff --git a/src/prelude.rs b/src/prelude.rs index e7c7a152..f8a3bdd7 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -37,7 +37,7 @@ pub use crate::locale::*; pub use crate::datetime::*; pub use crate::web; -pub use crate::web::{HttpRequest, IntoResponse, Response, Router}; +pub use crate::web::{HttpRequest, IntoResponse, Layers, Response, Router, Routes, StaticFiles}; pub use crate::core::{AnyCast, AnyInfo, TypeInfo}; @@ -46,6 +46,8 @@ pub use crate::core::component::*; pub use crate::core::extension::*; pub use crate::core::theme::*; +pub use crate::admin::*; + pub use crate::auth::*; pub use crate::response::*; diff --git a/src/response/flash.rs b/src/response/flash.rs index 61216df5..c61b6543 100644 --- a/src/response/flash.rs +++ b/src/response/flash.rs @@ -61,7 +61,7 @@ struct Pending(Vec<(MessageLevel, String)>); /// } /// ``` /// -/// [`Context::push_message()`]: crate::core::component::Context::push_message +/// [`Context::push_message()`]: crate::core::component::Contextual::push_message /// [`CoreRegions::Content`]: crate::core::theme::CoreRegions::Content /// [`Messages`]: crate::base::component::Messages pub trait ResponseExt { diff --git a/src/response/page.rs b/src/response/page.rs index b31db6aa..9c2eb966 100644 --- a/src/response/page.rs +++ b/src/response/page.rs @@ -18,19 +18,14 @@ mod error; pub use error::ErrorPage; pub(crate) use error::{render_error_pages, response_for_panic, route_not_found}; -use crate::auth::CurrentUser; +use crate::AutoDefault; use crate::base::action; use crate::base::component::layout; -use crate::core::component::{AssetsOp, ChildOp, ComponentRender}; -use crate::core::component::{Context, ContextError, Contextual}; -use crate::core::theme::{CoreRegions, RegionName, RegionRef, TemplateRef, ThemeRef}; -use crate::datetime::Tz; -use crate::html::{Assets, Favicon, JavaScript, ResponsiveStyles, StyleSheet}; +use crate::core::component::{ComponentRender, Context, Contextual}; +use crate::core::theme::RegionName; use crate::html::{DOCTYPE, Markup, html}; -use crate::html::{Props, PropsOp}; -use crate::locale::{CharacterDirection, LangId, LanguageIdentifier, Lc}; +use crate::locale::{CharacterDirection, LangId, Lc}; use crate::web::HttpRequest; -use crate::{AutoDefault, builder_impl}; // **< ReservedRegions >**************************************************************************** @@ -83,36 +78,35 @@ impl RegionName for ReservedRegions { /// Representa una página HTML completa lista para renderizar. /// -/// Una instancia de `Page` se compone dinámicamente permitiendo establecer título, descripción, -/// regiones donde disponer los componentes, atributos de `<body>` y otros aspectos del contexto de -/// renderizado. -#[rustfmt::skip] +/// Envuelve el [`Context`] de renderizado de la página e implementa [`Contextual`] sobre él, así +/// que una página se mantiene con los mismos métodos que un contexto: título, descripción, regiones +/// donde disponer los componentes, atributos de `<body>`, recursos, etc. Lo que añade `Page` es el +/// renderizado del documento completo ([`Page::render()`]). #[derive(AutoDefault)] pub struct Page { - title : Lc, - description: Lc, - metadata : Vec<(&'static str, &'static str)>, - properties : Vec<(&'static str, &'static str)>, - context : Context, + context: Context, } -#[builder_impl] impl Page { /// Crea una nueva instancia de página. /// /// La petición HTTP se guarda en el contexto de renderizado, que extrae automáticamente el - /// [`CurrentUser`] inyectado por middleware en sus extensiones (ver + /// [`CurrentUser`](crate::auth::CurrentUser) inyectado por middleware en sus extensiones (ver /// [`Context::new`](crate::core::component::Context::new)). Cualquier handler tiene acceso al /// usuario actual desde el momento en que se crea la página, sin llamadas adicionales. pub fn new(request: HttpRequest) -> Self { Page { context: Context::new(request), - ..Default::default() } } /// Crea una nueva instancia de página con la plantilla [`CoreTemplates::Admin`]. /// + /// Es la forma de crear una página del panel de administración: la plantilla añade la + /// navegación del panel y, alrededor del contenido, las migas de pan, el título + /// ([`with_title()`](Contextual::with_title)) y las pestañas y botones declarados para su ruta + /// (ver el módulo [`admin`](crate::admin)). + /// /// Cada tema puede maquetarla de forma distinta capturando [`Template`] vía /// [`Theme::render_component()`], pero la plantilla en sí es la misma constante para cualquier /// tema. @@ -123,69 +117,9 @@ impl Page { pub fn admin(request: HttpRequest) -> Self { Page { context: Context::admin(request), - ..Default::default() } } - // **< Page BUILDER >*************************************************************************** - - /// Establece el título de la página como un valor traducible. - pub fn with_title(mut self, title: Lc) -> Self { - self.title = title; - self - } - - /// Establece la descripción de la página como un valor traducible. - pub fn with_description(mut self, description: Lc) -> Self { - self.description = description; - self - } - - /// Añade una entrada `<meta name="..." content="...">` al `<head>`. - pub fn with_metadata(mut self, name: &'static str, content: &'static str) -> Self { - self.metadata.push((name, content)); - self - } - - /// Añade una entrada `<meta property="..." content="...">` al `<head>`. - pub fn with_property(mut self, property: &'static str, content: &'static str) -> Self { - self.properties.push((property, content)); - self - } - - // **< Page GETTERS >*************************************************************************** - - /// Devuelve el título traducido para el idioma de la página, si existe. - pub fn title(&self) -> Option<String> { - self.title.lookup(&self.context) - } - - /// Devuelve la descripción traducida para el idioma de la página, si existe. - pub fn description(&self) -> Option<String> { - self.description.lookup(&self.context) - } - - /// Devuelve la lista de metadatos `<meta name=...>`. - pub fn metadata(&self) -> &Vec<(&'static str, &'static str)> { - &self.metadata - } - - /// Devuelve la lista de propiedades `<meta property=...>`. - pub fn properties(&self) -> &Vec<(&'static str, &'static str)> { - &self.properties - } - - /// Devuelve una referencia mutable al [`Context`] de la página. - /// - /// El [`Context`] actúa como intermediario para muchos métodos de `Page` (idioma, tema, - /// *layout*, recursos, petición HTTP, etc.). Resulta especialmente útil cuando un componente - /// o un tema necesita recibir el contexto como parámetro. - pub fn context(&mut self) -> &mut Context { - &mut self.context - } - - // **< Page RENDER >**************************************************************************** - /// Renderiza la página completa en formato HTML. /// /// El proceso de renderizado de la página sigue esta secuencia: @@ -222,7 +156,7 @@ impl Page { /// [`Theme::render_page_head()`]: crate::core::theme::Theme::render_page_head /// [`CoreRegions::Content`]: crate::core::theme::CoreRegions::Content /// [`Component::is_deferred()`]: crate::core::component::Component::is_deferred - /// [`Context::langid()`]: crate::core::component::Context::langid + /// [`Context::langid()`]: crate::locale::LangId::langid /// [`Messages`]: crate::base::component::Messages pub async fn render(&mut self) -> Result<Markup, ErrorPage> { // Acciones específicas del tema antes de renderizar el <body>. @@ -272,121 +206,14 @@ impl Page { } } -/// Permite a [`Page`] actuar como proveedor de idioma usando el [`Context`] de la página. -/// -/// Resulta útil para usar [`Page`] directamente como fuente de traducción en [`Lc::lookup()`] o -/// [`Lc::using()`]. -impl LangId for Page { - #[inline] - fn langid(&self) -> &'static LanguageIdentifier { - self.context.langid() - } -} - -#[builder_impl] impl Contextual for Page { - // **< Contextual BUILDER >********************************************************************* - - fn with_request(mut self, request: Option<HttpRequest>) -> Self { - self.context.alter_request(request); - self + #[inline] + fn context(&self) -> &Context { + &self.context } - fn with_langid(mut self, language: &impl LangId) -> Self { - self.context.alter_langid(language); - self - } - - fn with_timezone(mut self, tz: Tz) -> Self { - self.context.alter_timezone(tz); - self - } - - fn with_theme(mut self, theme: ThemeRef) -> Self { - self.context.alter_theme(theme); - self - } - - fn with_template(mut self, template: TemplateRef) -> Self { - self.context.alter_template(template); - self - } - - fn with_param<T: Send + Sync + 'static>(mut self, key: &'static str, value: T) -> Self { - self.context.alter_param(key, value); - self - } - - fn with_assets(mut self, op: impl Into<AssetsOp>) -> Self { - self.context.alter_assets(op); - self - } - - fn with_body_props(mut self, op: PropsOp) -> Self { - self.context.alter_body_props(op); - self - } - - fn with_child(mut self, op: impl Into<ChildOp>) -> Self { - self.context - .alter_child_in(&CoreRegions::Content, op.into()); - self - } - - fn with_child_in(mut self, region: RegionRef, op: impl Into<ChildOp>) -> Self { - self.context.alter_child_in(region, op.into()); - self - } - - // **< Contextual GETTERS >********************************************************************* - - fn request(&self) -> Option<&HttpRequest> { - self.context.request() - } - - fn current_user(&self) -> &CurrentUser { - self.context.current_user() - } - - fn timezone(&self) -> Tz { - self.context.timezone() - } - - fn theme(&self) -> ThemeRef { - self.context.theme() - } - - fn template(&self) -> TemplateRef { - self.context.template() - } - - fn param<T: 'static>(&self, key: &'static str) -> Result<&T, ContextError> { - self.context.param(key) - } - - fn favicon(&self) -> Option<&Favicon> { - self.context.favicon() - } - - fn stylesheets(&self) -> &Assets<StyleSheet> { - self.context.stylesheets() - } - - fn javascripts(&self) -> &Assets<JavaScript> { - self.context.javascripts() - } - - fn responsive_styles(&self) -> &ResponsiveStyles { - self.context.responsive_styles() - } - - fn body_props(&self) -> &Props { - self.context.body_props() - } - - // **< Contextual HELPERS >********************************************************************* - - fn remove_param(&mut self, key: &'static str) -> bool { - self.context.remove_param(key) + #[inline] + fn context_mut(&mut self) -> &mut Context { + &mut self.context } } diff --git a/src/response/waypoint.rs b/src/response/waypoint.rs index ba200fae..84d56910 100644 --- a/src/response/waypoint.rs +++ b/src/response/waypoint.rs @@ -52,9 +52,9 @@ impl Waypoint { /// Crea un valor explícito. /// /// Sólo acepta una ruta local que empiece por `/`, pero no por `//` ni `/\` que el navegador - /// interpretaría como una URL *protocol-relative*, y sin caracteres de control. Una cadena vacía, una URL absoluta - /// (`https://...`), un esquema arbitrario (`javascript:...`) o cualquier otro valor que no - /// cumpla esa forma se trata igual que `None`. + /// interpretaría como una URL *protocol-relative*, y sin caracteres de control. Una cadena + /// vacía, una URL absoluta (`https://...`), un esquema arbitrario (`javascript:...`) o + /// cualquier otro valor que no cumpla esa forma se trata igual que `None`. /// /// Este filtro protege contra *open redirect*; el `waypoint` viaja en la *query string* de la /// petición, así que un cliente malicioso lo controla por completo. Por eso se aplica siempre, @@ -96,7 +96,7 @@ impl Waypoint { /// hacia otras pantallas (ver el ejemplo). /// /// Preserva cualquier *query string* ya presente en `route` sin romperla (como `lang=...` si - /// `route` se construyó con [`Context::route()`](crate::core::component::Context::route)). + /// `route` se construyó con [`Context::route()`](crate::core::component::Contextual::route)). /// /// # Ejemplo /// diff --git a/src/util.rs b/src/util.rs index c81ef5fd..4b3a86b4 100644 --- a/src/util.rs +++ b/src/util.rs @@ -262,7 +262,7 @@ pub fn normalize_token(s: impl AsRef<str>) -> Option<String> { /// /// La usan [`RoutePath::is_external()`](crate::html::RoutePath::is_external) y las conversiones /// `From<&str>`/`From<String>` de [`Route`](crate::core::component::Route) para decidir si una -/// ruta debe evitar [`Context::route()`](crate::core::component::Context::route). +/// ruta debe evitar [`Context::route()`](crate::core::component::Contextual::route). /// /// Cualquier otro código que necesite el mismo criterio (por ejemplo, para decidir si un enlace /// debe llevar `target="_blank"`) puede usarla en lugar de reimplementar su propia versión. diff --git a/src/web.rs b/src/web.rs index 73b83a8e..d691098c 100644 --- a/src/web.rs +++ b/src/web.rs @@ -51,7 +51,7 @@ pub use axum::extract::multipart; pub use axum::response::{IntoResponse, Response}; // Operaciones HTTP para registrar rutas. -pub use axum::routing::{delete, get, patch, post, put}; +pub use axum::routing::{MethodRouter, delete, get, patch, post, put}; // Middlewares de función (`from_fn`) y tipos asociados (`Next`). pub use axum::middleware; @@ -69,6 +69,10 @@ pub use download::Download; mod csrf; pub(crate) use csrf::reject_cross_origin; +// Rutas de las extensiones con su acceso, capas globales y archivos estáticos. +mod routes; +pub use routes::{Layers, Routes, StaticFiles}; + use axum::body::Body; use axum::extract::FromRequestParts; @@ -212,11 +216,18 @@ impl<S: Send + Sync> FromRequestParts<S> for HttpRequest { parts: &mut http::request::Parts, _state: &S, ) -> Result<Self, Self::Rejection> { - Ok(HttpRequest(Arc::new(RequestParts { + Ok(HttpRequest::from_parts(parts)) + } +} + +impl HttpRequest { + // También la usa el *middleware* que comprueba el acceso de las rutas, antes del *handler*. + pub(crate) fn from_parts(parts: &http::request::Parts) -> Self { + HttpRequest(Arc::new(RequestParts { uri: parts.uri.clone(), headers: parts.headers.clone(), extensions: parts.extensions.clone(), - }))) + })) } } @@ -373,7 +384,8 @@ impl tower::Service<http::Request<Body>> for ServeEmbedded { /// Se usa normalmente en el método [`configure_static_files()`] de las extensiones, para que estas /// rutas no pasen por su middleware. /// -/// La macro añade rutas al [`Router`] del primer argumento usando uno de los tres modos posibles: +/// La macro añade los archivos a los [`StaticFiles`] del primer argumento, siempre públicos, usando +/// uno de los tres modos posibles: /// /// - **Sistema de ficheros o embebido** (`[$dir, $bundle]`): intenta servir los archivos desde el /// directorio `$dir`; si está vacío, no existe o no es un directorio, usa el conjunto de recursos @@ -385,7 +397,7 @@ impl tower::Service<http::Request<Body>> for ServeEmbedded { /// /// # Argumentos /// -/// * `$router` - Variable de tipo [`Router`] donde registrar las rutas. +/// * `$router` - Variable de tipo [`StaticFiles`] donde registrar los archivos. /// * `$dir` - Ruta al directorio local con los archivos estáticos. /// * `$bundle` - Nombre del conjunto de recursos embebidos generado por `build.rs`. /// * `$path` - Prefijo URL bajo el que se publicarán los archivos. @@ -398,17 +410,17 @@ impl tower::Service<http::Request<Body>> for ServeEmbedded { /// /// #[async_trait] /// impl Extension for MyExtension { -/// fn configure_static_files(&self, router: Router) -> Router { +/// fn configure_static_files(&self, files: StaticFiles) -> StaticFiles { /// // Forma 1) Sistema de ficheros o embebido. -/// serve_static_files!(router, ["/var/www/static", assets] => "/public"); +/// serve_static_files!(files, ["/var/www/static", assets] => "/public"); /// /// // Forma 2) Siempre embebido. -/// serve_static_files!(router, [assets] => "/public"); +/// serve_static_files!(files, [assets] => "/public"); /// /// // Forma 3) Sólo sistema de ficheros (no requiere `assets`). -/// serve_static_files!(router, "/var/www/static" => "/public"); +/// serve_static_files!(files, "/var/www/static" => "/public"); /// -/// router +/// files /// } /// } /// ``` @@ -614,7 +626,8 @@ pub mod test { } /// Construye un [`HttpRequest`](super::HttpRequest) listo para pasarlo a - /// [`Context::new`](crate::core::component::Context::new) en tests unitarios de componentes. + /// [`Context::new`](crate::core::component::Context::new) en tests unitarios de + /// componentes. pub fn to_http_request(self) -> super::HttpRequest { let uri = self.uri.parse().unwrap(); super::HttpRequest(std::sync::Arc::new(super::RequestParts { diff --git a/src/web/routes.rs b/src/web/routes.rs new file mode 100644 index 00000000..0caea882 --- /dev/null +++ b/src/web/routes.rs @@ -0,0 +1,320 @@ +use crate::admin::{AdminRegistry, admin_path, strip_admin_path, undeclared_permission}; +use crate::auth::{Access, PermissionRegistry, deny_access}; +use crate::web::{HttpRequest, IntoResponse, Request, Response, Router, middleware}; +use crate::{global, trace}; + +use axum::extract::State; +use axum::routing::{MethodRouter, Route}; +use tower::{Layer, Service}; + +use std::collections::BTreeMap; +use std::convert::Infallible; + +// **< Routes >************************************************************************************* + +/// Rutas de una extensión, cada una con el acceso que la habilita. +/// +/// Es lo que recibe [`Extension::configure_router()`]. A diferencia del [`Router`] de Axum, no hay +/// forma de montar una ruta sin indicar quién puede acceder a ella ([`Access`]): PageTop lo +/// comprueba antes de llegar al *handler* y responde con [`deny_access()`] a quien no lo cumple. +/// Una ruta [`Access::Public`] no añade ninguna comprobación. +/// +/// Las rutas del panel de administración (bajo [`admin_path`]) se montan con [`admin_route()`], que +/// exige el permiso de la página declarada ([`AdminPage`]) de la que cuelgan: el permiso se declara +/// sólo en la página. Montar una con cualquier otro método, o una que no cuelgue de ninguna página, +/// impide arrancar la aplicación. +/// +/// # Ejemplo +/// +/// ```rust,no_run +/// # use pagetop::prelude::*; +/// # #[derive(Clone, Copy, Debug)] +/// # enum BlogPermission { Publish } +/// # impl Permission for BlogPermission { +/// # fn key(&self) -> CowStr { "blog:publish".into() } +/// # } +/// # async fn list_posts() -> &'static str { "" } +/// # async fn new_post_form() -> &'static str { "" } +/// # async fn new_post() -> &'static str { "" } +/// pub struct Blog; +/// +/// #[async_trait] +/// impl Extension for Blog { +/// fn configure_router(&self, routes: Routes) -> Routes { +/// routes +/// .public_route("/posts", web::get(list_posts)) +/// .route( +/// "/posts/new", +/// Access::Permission(&BlogPermission::Publish), +/// web::get(new_post_form).post(new_post), +/// ) +/// } +/// } +/// ``` +/// +/// [`Extension::configure_router()`]: crate::core::extension::Extension::configure_router +/// [`admin_path`]: crate::global::AppSettings::admin_path +/// [`admin_route()`]: Self::admin_route +/// [`AdminPage`]: crate::admin::AdminPage +pub struct Routes { + router: Router, + // Rutas del panel de administración mal montadas, para detener el arranque. + invalid_admin: Vec<String>, + // Rutas que exigen un permiso que no está en el catálogo, por permiso, para avisar. + undeclared: BTreeMap<String, Vec<String>>, +} + +impl Routes { + pub(crate) fn new(router: Router) -> Self { + Routes { + router, + invalid_admin: Vec::new(), + undeclared: BTreeMap::new(), + } + } + + // Devuelve el router, o las rutas del panel de administración mal montadas. Antes avisa de los + // permisos que exigen las rutas sin estar en el catálogo: ninguna extensión de autenticación + // podría ofrecerlos para concederlos. Los de las rutas del panel los avisa su registro. + pub(crate) fn into_router(self) -> Result<Router, Vec<String>> { + for (key, paths) in &self.undeclared { + trace::warn!("{}", undeclared_permission(key, paths)); + } + if self.invalid_admin.is_empty() { + Ok(self.router) + } else { + Err(self.invalid_admin) + } + } + + /// Añade una ruta con su acceso y sus *handlers* por método (`web::get(...)`, + /// `web::get(...).post(...)`...). + /// + /// Se puede llamar varias veces con la misma ruta y otros métodos, cada vez con su acceso: p. + /// ej. ver con un permiso y guardar con otro. Las rutas del panel de administración se montan + /// con [`admin_route()`](Self::admin_route). + pub fn route(mut self, path: &str, access: Access, method_router: MethodRouter) -> Self { + self.reject_admin(path, false); + self.check_declared(path, access); + self.router = self + .router + .route(path, protect_method(method_router, access)); + self + } + + /// Añade una ruta pública ([`Access::Public`]), a la que puede acceder cualquiera, también un + /// usuario anónimo. + /// + /// Equivale a [`route()`](Self::route) con [`Access::Public`], que sigue sirviendo cuando el + /// acceso llega en una variable. + pub fn public_route(self, path: &str, method_router: MethodRouter) -> Self { + self.route(path, Access::Public, method_router) + } + + /// Añade una ruta del panel de administración, relativa a su raíz, con sus *handlers* por + /// método. + /// + /// Exige el permiso de la página declarada ([`AdminPage`]) de la que cuelga: la más cercana que + /// se encuentra al quitarle tramos por el final, tal como se monta, con sus parámetros + /// (`"user/users/{id}/edit"` cuelga de `"user/users"`). Si no cuelga de ninguna, la aplicación + /// no arranca; como las páginas se declaran con rutas fijas, tampoco cuelga una ruta con un + /// parámetro antes de cualquier página (`"{section}/list"`). Un permiso más concreto lo + /// comprueba el *handler* (ver [`require_permission()`](crate::auth::require_permission)). + /// + /// [`AdminPage`]: crate::admin::AdminPage + pub fn admin_route(mut self, path: &str, method_router: MethodRouter) -> Self { + let full_path = admin_path(path); + let relative = strip_admin_path(&full_path).unwrap_or_default(); + match AdminRegistry::global().nearest_page(relative) { + Some(page) => { + let access = Access::Permission(page.permission()); + self.router = self + .router + .route(&full_path, protect_method(method_router, access)); + } + None => self.invalid_admin.push(full_path), + } + self + } + + /// Añade un [`Router`] de Axum bajo un prefijo, con el mismo acceso para todas sus rutas. + /// + /// Sirve para agrupar rutas con sus propias capas de *middleware* (p. ej. una API con su + /// autenticación). El prefijo no puede estar dentro del panel de administración ni contener su + /// raíz. + pub fn nest(mut self, path: &str, access: Access, router: Router) -> Self { + self.reject_admin(path, true); + self.check_declared(path, access); + self.router = self.router.nest(path, protect(router, access)); + self + } + + /// Añade un servicio de Tower bajo un prefijo, con el mismo acceso para todo lo que sirva (p. + /// ej. los recursos de un libro, o una interfaz web de otro *crate*). + /// + /// El prefijo no puede estar dentro del panel de administración ni contener su raíz. + pub fn nest_service<S>(mut self, path: &str, access: Access, service: S) -> Self + where + S: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static, + S::Response: IntoResponse, + S::Future: Send + 'static, + { + self.reject_admin(path, true); + self.check_declared(path, access); + let nested = Router::new().nest_service(path, service); + self.router = self.router.merge(protect(nested, access)); + self + } + + fn check_declared(&mut self, path: &str, access: Access) { + if let Access::Permission(perm) = access + && !PermissionRegistry::global().has(perm) + { + self.undeclared + .entry(perm.key().into_owned()) + .or_default() + .push(path.to_owned()); + } + } + + // Las rutas del panel sólo se montan con `admin_route()`. Un prefijo (`nested`) tampoco puede + // contener la raíz del panel, porque agruparía rutas del panel con otras. + fn reject_admin(&mut self, path: &str, nested: bool) { + let inside = strip_admin_path(path).is_some(); + let contains_root = nested + && global::SETTINGS + .app + .admin_path + .strip_prefix(path.trim_end_matches('/')) + .is_some_and(|rest| rest.starts_with('/')); + if inside || contains_root { + self.invalid_admin.push(path.to_owned()); + } + } +} + +// Con `layer()` y no `route_layer()`, que dejaría sin comprobar el *fallback* propio de las rutas +// (`web::get(...).fallback(...)`) o de un `Router` anidado. Un método no admitido también pasa +// antes por el acceso: quien no lo cumple no llega a saber qué métodos tiene la ruta. +fn protect_method(method_router: MethodRouter, access: Access) -> MethodRouter { + match access { + Access::Public => method_router, + _ => method_router.layer(middleware::from_fn_with_state(access, check_access)), + } +} + +fn protect(router: Router, access: Access) -> Router { + match access { + Access::Public => router, + _ => router.layer(middleware::from_fn_with_state(access, check_access)), + } +} + +// Comprueba el acceso de la ruta antes de llegar a su *handler*. +async fn check_access( + State(access): State<Access>, + request: Request, + next: middleware::Next, +) -> Response { + let (parts, body) = request.into_parts(); + let http_request = HttpRequest::from_parts(&parts); + if access.allows(&http_request) { + next.run(Request::from_parts(parts, body)).await + } else { + deny_access(http_request) + } +} + +// **< Layers >************************************************************************************* + +/// Capas de *middleware* globales, que envuelven todas las rutas de la aplicación. +/// +/// Es lo que recibe [`Extension::configure_middleware()`]. Sólo admite capas: las rutas se montan +/// en [`Extension::configure_router()`], con su acceso ([`Routes`]). +/// +/// [`Extension::configure_middleware()`]: crate::core::extension::Extension::configure_middleware +/// [`Extension::configure_router()`]: crate::core::extension::Extension::configure_router +pub struct Layers(Router); + +impl Layers { + pub(crate) fn new(router: Router) -> Self { + Layers(router) + } + + pub(crate) fn into_router(self) -> Router { + self.0 + } + + /// Añade una capa de *middleware* (p. ej. `web::middleware::from_fn(...)`), igual que + /// [`Router::layer()`]. + pub fn layer<L>(self, layer: L) -> Self + where + L: Layer<Route> + Clone + Send + Sync + 'static, + L::Service: Service<Request> + Clone + Send + Sync + 'static, + <L::Service as Service<Request>>::Response: IntoResponse + 'static, + <L::Service as Service<Request>>::Error: Into<Infallible> + 'static, + <L::Service as Service<Request>>::Future: Send + 'static, + { + Layers(self.0.layer(layer)) + } +} + +// **< StaticFiles >******************************************************************************** + +/// Archivos estáticos de una extensión, siempre públicos. +/// +/// Es lo que recibe [`Extension::configure_static_files()`], y sólo se usa con la macro +/// [`serve_static_files!`](crate::serve_static_files): las demás rutas se montan en +/// [`Extension::configure_router()`], con su acceso ([`Routes`]). +/// +/// [`Extension::configure_static_files()`]: crate::core::extension::Extension::configure_static_files +/// [`Extension::configure_router()`]: crate::core::extension::Extension::configure_router +pub struct StaticFiles(Router); + +impl StaticFiles { + pub(crate) fn new(router: Router) -> Self { + StaticFiles(router) + } + + pub(crate) fn into_router(self) -> Router { + self.0 + } + + // La usa `serve_static_files!` con los servicios de archivos de PageTop. + #[doc(hidden)] + pub fn nest_service<S>(self, path: &str, service: S) -> Self + where + S: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static, + S::Response: IntoResponse, + S::Future: Send + 'static, + { + StaticFiles(self.0.nest_service(path, service)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::CowStr; + use crate::auth::Permission; + use crate::web::get; + + struct UndeclaredPermission; + + impl Permission for UndeclaredPermission { + fn key(&self) -> CowStr { + "test:undeclared".into() + } + } + + #[test] + fn routes_with_permissions_missing_from_the_catalog_are_grouped_by_permission() { + let undeclared = Access::Permission(&UndeclaredPermission); + let routes = Routes::new(Router::new()) + .route("/a", undeclared, get(|| async { "" })) + .route("/b", Access::Public, get(|| async { "" })) + .route("/c", undeclared, get(|| async { "" })); + assert_eq!(routes.undeclared.len(), 1); + assert_eq!(routes.undeclared["test:undeclared"], ["/a", "/c"]); + } +} diff --git a/tests/admin_invalid_route.rs b/tests/admin_invalid_route.rs new file mode 100644 index 00000000..7c2786cd --- /dev/null +++ b/tests/admin_invalid_route.rs @@ -0,0 +1,50 @@ +use pagetop::prelude::*; + +// The administration registry is built once per process: this test needs its own binary. + +struct ToolsPermission; + +impl Permission for ToolsPermission { + fn key(&self) -> CowStr { + "tools:use".into() + } +} + +fn declare_pages(bag: &mut AdminPageBag) { + bag.add(AdminPage::new( + "config/export", + "config", + Lc::n("Export"), + &ToolsPermission, + )); +} + +struct Ext; + +#[async_trait] +impl Extension for Ext { + fn actions(&self) -> Vec<ActionBox> { + actions![action::admin::DeclareAdminPages::new(declare_pages)] + } + + fn configure_router(&self, routes: Routes) -> Routes { + let tools = Access::Permission(&ToolsPermission); + routes + // Valid: hangs from a declared page, whose permission it requires. + .admin_route("config/export/{id}", web::get(unchecked)) + // Does not hang from any declared page. + .admin_route("undeclared", web::get(unchecked)) + // A route of the panel mounted without `admin_route()`, even with the right permission. + .route(&admin_path("config/export/new"), tools, web::get(unchecked)) + } +} + +async fn unchecked() -> &'static str { + "unchecked" +} + +#[pagetop::test] +#[should_panic(expected = "declared page: /admin/undeclared, /admin/config/export/new")] +async fn a_route_of_the_panel_mounted_wrongly_stops_the_application() { + let _ = Application::prepare(&Ext).await.test(); +} diff --git a/tests/admin_registry.rs b/tests/admin_registry.rs new file mode 100644 index 00000000..65311160 --- /dev/null +++ b/tests/admin_registry.rs @@ -0,0 +1,133 @@ +use pagetop::prelude::*; + +// The administration registry is built once per process, at startup: every declaration of this +// test is in a single extension and the cases are different tests on top of it. + +struct ToolsPermission; + +impl Permission for ToolsPermission { + fn key(&self) -> CowStr { + "tools:use".into() + } +} + +fn declare_sections(bag: &mut AdminSectionBag) { + bag.add(AdminSection::new("tools", Lc::n("Tools")).with_weight(35)); + // Replaces the built-in section with the same key. + bag.add( + AdminSection::new("help", Lc::n("Support")) + .with_path("support") + .with_weight(5), + ); +} + +fn declare_pages(bag: &mut AdminPageBag) { + for (path, weight) in [("tools/export", 10), ("/tools/import/", 0)] { + bag.add(AdminPage::new(path, "tools", Lc::n(path), &ToolsPermission).with_weight(weight)); + } +} + +fn declare_tasks(bag: &mut AdminTaskBag) { + for (path, weight) in [("tools/export/json", 1), ("tools/export/csv", 0)] { + bag.add(AdminTask::new(path, "/tools/export", Lc::n(path)).with_weight(weight)); + } +} + +fn declare_actions(bag: &mut AdminActionBag) { + bag.add(AdminAction::new( + "tools/export/new/", + "tools/export", + Lc::n("New export"), + )); +} + +struct Ext; + +#[async_trait] +impl Extension for Ext { + fn actions(&self) -> Vec<ActionBox> { + actions![ + action::admin::DeclareAdminSections::new(declare_sections), + action::admin::DeclareAdminPages::new(declare_pages), + action::admin::DeclareAdminTasks::new(declare_tasks), + action::admin::DeclareAdminActions::new(declare_actions), + ] + } +} + +async fn start() { + // Starting more than once in the same process (as tests do) does not duplicate anything. + let _ = Application::prepare(&Ext).await; + let _ = Application::prepare(&Ext).await; +} + +#[pagetop::test] +async fn built_in_sections_come_first_and_can_be_replaced() { + start().await; + let keys: Vec<_> = AdminRegistry::global() + .sections() + .iter() + .map(|s| (s.key(), s.path())) + .collect(); + assert_eq!( + keys, + [ + ("help", "support"), + ("people", "people"), + ("structure", "structure"), + ("config", "config"), + ("tools", "tools"), + ("reports", "reports"), + ] + ); +} + +#[pagetop::test] +async fn paths_are_kept_relative_without_surrounding_slashes() { + start().await; + let registry = AdminRegistry::global(); + let pages: Vec<_> = registry + .pages_for_section("tools") + .iter() + .map(|p| p.path()) + .collect(); + assert_eq!(pages, ["tools/import", "tools/export"]); + + let tasks: Vec<_> = registry + .tasks_for("tools/export") + .iter() + .map(|t| t.path()) + .collect(); + assert_eq!(tasks, ["tools/export/csv", "tools/export/json"]); + + let actions = registry.actions_for("tools/export"); + assert_eq!(actions.len(), 1); + assert_eq!(actions[0].url(), "tools/export/new"); +} + +#[pagetop::test] +async fn admin_paths_are_built_from_the_root_and_back() { + start().await; + assert_eq!(admin_path(""), "/admin"); + assert_eq!(admin_path("tools/export"), "/admin/tools/export"); + assert_eq!(admin_path("/tools/export/"), "/admin/tools/export"); + + assert_eq!(strip_admin_path("/admin"), Some("")); + assert_eq!(strip_admin_path("/admin/"), Some("")); + assert_eq!( + strip_admin_path("/admin/tools/export/"), + Some("tools/export") + ); + assert_eq!(strip_admin_path("/administrator"), None); + assert_eq!(strip_admin_path("/tools"), None); +} + +#[pagetop::test] +async fn without_an_authentication_extension_nobody_can_access_the_panel() { + start().await; + let request = web::test::TestRequest::get() + .uri("/admin") + .to_http_request(); + let cx = Context::new(request); + assert!(!can_access_admin(&cx)); +} diff --git a/tests/admin_template.rs b/tests/admin_template.rs new file mode 100644 index 00000000..64a4bb49 --- /dev/null +++ b/tests/admin_template.rs @@ -0,0 +1,216 @@ +use pagetop::prelude::*; + +// The administration registry is built once per process, at startup: every declaration of this +// test is in a single extension and the cases are different tests on top of it. + +struct ToolsPermission; + +impl Permission for ToolsPermission { + fn key(&self) -> CowStr { + "tools:use".into() + } +} + +// Not granted by `grant_tools()`. +struct AuditPermission; + +impl Permission for AuditPermission { + fn key(&self) -> CowStr { + "tools:audit".into() + } +} + +// Grants `tools:use` to every request, as an authentication extension would. +fn grant_tools(_: &HttpRequest, perm: PermissionRef, granted: &mut bool) { + if perm.key() == "tools:use" { + *granted = true; + } +} + +fn declare_pages(bag: &mut AdminPageBag) { + bag.add(AdminPage::new( + "config/export", + "config", + Lc::n("Export"), + &ToolsPermission, + )); + bag.add(AdminPage::new( + "reports/audit", + "reports", + Lc::n("Audit"), + &AuditPermission, + )); +} + +fn declare_tasks(bag: &mut AdminTaskBag) { + bag.add(AdminTask::new( + "config/export", + "config/export", + Lc::n("All"), + )); + bag.add(AdminTask::new("config/export/csv", "config/export", Lc::n("CSV")).with_weight(1)); + bag.add( + AdminTask::new("config/export/log", "config/export", Lc::n("Log")) + .with_weight(2) + .with_permission(&AuditPermission), + ); +} + +fn declare_actions(bag: &mut AdminActionBag) { + bag.add(AdminAction::new( + "config/export/new", + "config/export", + Lc::n("New export"), + )); + bag.add( + AdminAction::new( + "config/export/purge", + "config/export", + Lc::n("Purge exports"), + ) + .with_weight(1) + .with_permission(&AuditPermission), + ); +} + +struct Ext; + +#[async_trait] +impl Extension for Ext { + fn actions(&self) -> Vec<ActionBox> { + actions![ + action::auth::CheckPermission::new(grant_tools), + action::admin::DeclareAdminPages::new(declare_pages), + action::admin::DeclareAdminTasks::new(declare_tasks), + action::admin::DeclareAdminActions::new(declare_actions), + ] + } + + // None of these handlers checks any permission: each route requires the one of its page. + fn configure_router(&self, routes: Routes) -> Routes { + routes + .admin_route("config/export", web::get(unchecked)) + .admin_route("config/export/{id}/edit", web::get(unchecked)) + .admin_route("reports/audit", web::get(unchecked)) + .admin_route("reports/audit/{id}", web::get(unchecked)) + } +} + +async fn unchecked() -> &'static str { + "unchecked" +} + +async fn render(page: Page) -> String { + let mut page = page.with_child(Html::with(|_| html! { p { "Body of the page." } })); + page.render().await.unwrap().into_string() +} + +fn request(uri: &str) -> HttpRequest { + web::test::TestRequest::get().uri(uri).to_http_request() +} + +#[pagetop::test] +async fn the_admin_template_frames_the_content_of_the_page() { + let _ = Application::prepare(&Ext).await; + let html = + render(Page::admin(request("/admin/config/export/csv")).with_title(Lc::n("CSV"))).await; + + assert!(html.contains(r#"class="wrapper wrapper-admin""#), "{html}"); + // Navigation: only the sections with an accessible page. + assert!(html.contains("admin-menu"), "{html}"); + assert!(html.contains(r#"href="/admin/config/export""#), "{html}"); + assert!(!html.contains(r#"href="/admin/reports/audit""#), "{html}"); + // Breadcrumbs up to the nearest declared page, then the page title. + assert!(html.contains(r#"href="/admin/config""#), "{html}"); + assert!( + html.contains(r#"<h1 class="admin-page-title">CSV</h1>"#), + "{html}" + ); + // Tasks of the parent page, the current one active, without the one not granted. + assert!( + html.contains( + r#"<li class="admin-task admin-task-active"><a href="/admin/config/export/csv">"# + ), + "{html}" + ); + assert!(!html.contains("config/export/log"), "{html}"); + // The content of the page, inside the frame. + assert!(html.contains(r#"<div class="admin-content">"#), "{html}"); + assert!(html.contains("Body of the page."), "{html}"); +} + +#[pagetop::test] +async fn a_declared_page_shows_its_actions_and_its_declared_title() { + let _ = Application::prepare(&Ext).await; + let html = render(Page::admin(request("/admin/config/export"))).await; + + assert!( + html.contains(r#"<h1 class="admin-page-title">Export</h1>"#), + "{html}" + ); + assert!( + html.contains(r#"href="/admin/config/export/new""#), + "{html}" + ); + // Without the permission of the action, its button is not shown. + assert!(!html.contains("config/export/purge"), "{html}"); + // The declared title also reaches the <title> of the document. + assert!(html.contains("<title>"), "{html}"); + assert!(html.contains(" | Export"), "{html}"); +} + +#[pagetop::test] +async fn the_standard_template_has_no_admin_frame() { + let _ = Application::prepare(&Ext).await; + let html = render(Page::new(request("/admin/config/export")).with_title(Lc::n("Export"))).await; + + assert!(!html.contains("wrapper-admin"), "{html}"); + assert!(!html.contains("admin-menu"), "{html}"); + assert!(!html.contains("admin-content"), "{html}"); + assert!(html.contains("Body of the page."), "{html}"); +} + +async fn get(uri: &str) -> (u16, String) { + let app = Application::prepare(&Ext).await.test(); + let request = web::test::TestRequest::get().uri(uri).to_request(); + let response = web::test::send_request(&app, request).await; + let status = response.status().as_u16(); + (status, web::test::read_body_text(response).await) +} + +#[pagetop::test] +async fn the_dashboard_lists_the_accessible_pages_by_section() { + let (status, html) = get("/admin").await; + assert_eq!(status, 200, "{html}"); + assert!( + html.contains(r#"Export"#), + "{html}" + ); + assert!(!html.contains("Audit"), "{html}"); +} + +#[pagetop::test] +async fn a_section_page_is_mounted_only_for_sections_with_pages() { + let (status, html) = get("/admin/config").await; + assert_eq!(status, 200, "{html}"); + assert!( + html.contains(r#"Export"#), + "{html}" + ); + // Its only page needs a permission that nobody has. + assert_eq!(get("/admin/reports").await.0, 403); + // No page declared in it. + assert_eq!(get("/admin/people").await.0, 404); +} + +#[pagetop::test] +async fn each_route_of_the_panel_requires_the_permission_of_its_page() { + // Granted permission, also on a route below the page. + assert_eq!(get("/admin/config/export").await.0, 200); + assert_eq!(get("/admin/config/export/5/edit").await.0, 200); + // Permission not granted, also on a route below the page. + assert_eq!(get("/admin/reports/audit").await.0, 403); + assert_eq!(get("/admin/reports/audit/5").await.0, 403); + // Routes that are not mounted are not affected. + assert_eq!(get("/admin/config/export/5/missing").await.0, 404); +} diff --git a/tests/admin_without_pages.rs b/tests/admin_without_pages.rs new file mode 100644 index 00000000..720ad6a7 --- /dev/null +++ b/tests/admin_without_pages.rs @@ -0,0 +1,15 @@ +use pagetop::prelude::*; + +struct Ext; + +impl Extension for Ext {} + +#[pagetop::test] +async fn without_declared_pages_the_panel_is_not_mounted() { + let app = Application::prepare(&Ext).await.test(); + for uri in ["/admin", "/admin/config"] { + let request = web::test::TestRequest::get().uri(uri).to_request(); + let response = web::test::send_request(&app, request).await; + assert_eq!(response.status().as_u16(), 404, "{uri}"); + } +} diff --git a/tests/auth_permissions.rs b/tests/auth_permissions.rs new file mode 100644 index 00000000..37dac58a --- /dev/null +++ b/tests/auth_permissions.rs @@ -0,0 +1,114 @@ +use pagetop::prelude::*; + +// The permission catalog is built once per process, at startup: every declaration of this test is +// in a single extension and the cases are different tests on top of it. + +#[derive(Clone, Copy, Debug)] +enum Perm { + Read, + Write, + Audit, +} + +impl Permission for Perm { + fn key(&self) -> CowStr { + match self { + Self::Read => "test:read".into(), + Self::Write => "test:write".into(), + Self::Audit => "test:audit".into(), + } + } + + fn group(&self) -> &'static str { + match self { + Self::Read | Self::Write => "content", + Self::Audit => "security", + } + } +} + +// Same key as `Perm::Read`, declared again by another action. +struct Duplicate; + +impl Permission for Duplicate { + fn key(&self) -> CowStr { + "test:read".into() + } + + fn group(&self) -> &'static str { + "duplicated" + } +} + +fn declare_audit(registry: &mut PermissionRegistry) { + registry.register(&Perm::Audit); +} + +fn declare_content(registry: &mut PermissionRegistry) { + registry.register(&Perm::Read); + registry.register(&Perm::Write); + registry.register(&Duplicate); +} + +struct Ext; + +#[async_trait] +impl Extension for Ext { + fn actions(&self) -> Vec { + actions![ + action::auth::DeclarePermissions::new(declare_audit), + action::auth::DeclarePermissions::new(declare_content).with_weight(-1), + ] + } +} + +async fn start() { + // Starting more than once in the same process (as tests do) does not duplicate the catalog. + let _ = Application::prepare(&Ext).await; + let _ = Application::prepare(&Ext).await; +} + +fn keys(permissions: impl Iterator) -> Vec { + permissions.map(|p| p.key().into_owned()).collect() +} + +#[pagetop::test] +async fn declarations_are_registered_by_weight_then_registration_order() { + start().await; + let registry = PermissionRegistry::global(); + assert_eq!( + keys(registry.all()), + ["test:read", "test:write", "test:audit"] + ); + let groups: Vec<_> = registry.groups().iter().map(|(g, _)| *g).collect(); + assert_eq!(groups, ["content", "security"]); +} + +#[pagetop::test] +async fn a_repeated_key_is_ignored_with_its_group() { + start().await; + let registry = PermissionRegistry::global(); + assert!(registry.has(&Duplicate)); + assert!(registry.has_key("test:read")); + assert!(!registry.has_key("test:unknown")); + assert!(!registry.groups().iter().any(|(g, _)| *g == "duplicated")); +} + +#[pagetop::test] +async fn permissions_are_listed_by_group() { + start().await; + let registry = PermissionRegistry::global(); + assert_eq!( + keys(registry.by_group("content")), + ["test:read", "test:write"] + ); + assert_eq!(keys(registry.by_group("security")), ["test:audit"]); + assert!(registry.by_group("missing").next().is_none()); +} + +#[pagetop::test] +async fn declaring_a_permission_does_not_grant_it() { + start().await; + let request = web::test::TestRequest::get().uri("/").to_http_request(); + assert!(!has_permission(&request, &Perm::Read)); +} diff --git a/tests/component_template.rs b/tests/component_template.rs index f32b3c0a..a0f34298 100644 --- a/tests/component_template.rs +++ b/tests/component_template.rs @@ -55,12 +55,12 @@ async fn default_template_identity_is_independent_of_theme() { #[pagetop::test] async fn admin_template_identity_is_independent_of_theme() { - let mut page = Page::admin(web::test::TestRequest::get().to_http_request()); - assert_eq!(page.context().template().name(), "admin"); + let page = Page::admin(web::test::TestRequest::get().to_http_request()); + assert_eq!(page.template().name(), "admin"); - let mut page = + let page = Page::admin(web::test::TestRequest::get().to_http_request()).with_theme(&MarkerTheme); - assert_eq!(page.context().template().name(), "admin"); + assert_eq!(page.template().name(), "admin"); } #[pagetop::test] @@ -116,3 +116,21 @@ async fn page_admin_render_reflects_the_active_theme_template() { assert!(html.contains("marker-template-output")); } + +#[pagetop::test] +async fn core_templates_have_translated_labels() { + let es = Locale::resolve("es-ES"); + let en = Locale::resolve("en-US"); + assert_eq!( + CoreTemplates::Standard.label().lookup(&es).as_deref(), + Some("Estándar") + ); + assert_eq!( + CoreTemplates::Admin.label().lookup(&es).as_deref(), + Some("Administración") + ); + assert_eq!( + CoreTemplates::Admin.label().lookup(&en).as_deref(), + Some("Administration") + ); +} diff --git a/tests/error_handling.rs b/tests/error_handling.rs index 9bd2d893..5d8b23fe 100644 --- a/tests/error_handling.rs +++ b/tests/error_handling.rs @@ -6,8 +6,8 @@ struct PanicExtension; #[async_trait] impl Extension for PanicExtension { - fn configure_router(&self, router: Router) -> Router { - router.route("/boom", web::get(boom)) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/boom", web::get(boom)) } } diff --git a/tests/response_flash.rs b/tests/response_flash.rs index 894621a6..c70a8178 100644 --- a/tests/response_flash.rs +++ b/tests/response_flash.rs @@ -6,15 +6,15 @@ struct FlashExtension; #[async_trait] impl Extension for FlashExtension { - fn configure_router(&self, router: Router) -> Router { - router - .route("/save", web::post(save)) - .route( + fn configure_router(&self, routes: Routes) -> Routes { + routes + .public_route("/save", web::post(save)) + .public_route( "/again", web::get(|| async { Redirect::see_other("/done") }), ) - .route("/done", web::get(done)) - .route("/file", web::get(|| async { "plain text" })) + .public_route("/done", web::get(done)) + .public_route("/file", web::get(|| async { "plain text" })) } } diff --git a/tests/response_page.rs b/tests/response_page.rs index 947670e4..724723b1 100644 --- a/tests/response_page.rs +++ b/tests/response_page.rs @@ -4,12 +4,29 @@ fn request() -> HttpRequest { web::test::TestRequest::get().to_http_request() } +// Sets the document description and metadata from its own context while it renders. +#[derive(Clone)] +struct Article; + +#[async_trait] +impl Component for Article { + fn new() -> Self { + Self + } + + fn setup(&mut self, cx: &mut Context) { + cx.alter_description(Lc::n("Article summary")) + .alter_metadata("author", String::from("Article author")) + .alter_property("og:type", "article"); + } +} + #[pagetop::test] async fn title_and_description_are_absent_by_default() { let page = Page::new(request()); - assert_eq!(page.title(), None); - assert_eq!(page.description(), None); + assert!(page.title().is_none()); + assert!(page.description().is_none()); } #[pagetop::test] @@ -18,9 +35,9 @@ async fn title_and_description_reflect_the_values_set() { .with_title(Lc::n("Dashboard")) .with_description(Lc::n("Overview of recent activity")); - assert_eq!(page.title(), Some("Dashboard".to_string())); + assert_eq!(page.title().lookup(&page), Some("Dashboard".to_string())); assert_eq!( - page.description(), + page.description().lookup(&page), Some("Overview of recent activity".to_string()) ); } @@ -33,6 +50,34 @@ async fn lc_none_clears_a_previously_set_title_and_description() { .with_title(Lc::none()) .with_description(Lc::none()); - assert_eq!(page.title(), None); - assert_eq!(page.description(), None); + assert!(page.title().is_none()); + assert!(page.description().is_none()); +} + +#[pagetop::test] +async fn page_and_its_context_share_the_same_state() { + let mut page = Page::new(request()) + .with_title(Lc::n("Dashboard")) + .with_metadata("robots", "noindex"); + page.context_mut().alter_property("og:title", "Dashboard"); + + let cx = page.context(); + assert_eq!(cx.title().lookup(cx), Some("Dashboard".to_string())); + assert_eq!(cx.metadata(), &[("robots", CowStr::from("noindex"))]); + assert_eq!( + page.properties(), + &[("og:title", CowStr::from("Dashboard"))] + ); +} + +#[pagetop::test] +async fn components_can_set_the_description_and_metadata_of_the_page() { + Application::new().await; + + let mut page = Page::new(request()).with_child(Article); + let html = page.render().await.expect("page renders").into_string(); + + assert!(html.contains(r#""#)); + assert!(html.contains(r#""#)); + assert!(html.contains(r#""#)); } diff --git a/tests/static_files.rs b/tests/static_files.rs index 9706d7a3..2f740412 100644 --- a/tests/static_files.rs +++ b/tests/static_files.rs @@ -25,12 +25,12 @@ struct MarkingExtension; #[async_trait] impl Extension for MarkingExtension { - fn configure_router(&self, router: Router) -> Router { - router.route("/page", web::get(|| async { "page" })) + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route("/page", web::get(|| async { "page" })) } - fn configure_middleware(&self, router: Router) -> Router { - router.layer(web::middleware::from_fn(mark_response)) + fn configure_middleware(&self, layers: Layers) -> Layers { + layers.layer(web::middleware::from_fn(mark_response)) } } diff --git a/tests/web_csrf.rs b/tests/web_csrf.rs index 36559e4a..c9939a40 100644 --- a/tests/web_csrf.rs +++ b/tests/web_csrf.rs @@ -18,15 +18,15 @@ struct ActionExtension; #[async_trait] impl Extension for ActionExtension { - fn configure_router(&self, router: Router) -> Router { - router.route( + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route( "/action/{name}", web::get(|| async { "read" }).post(|| async { "done" }), ) } - fn configure_middleware(&self, router: Router) -> Router { - router.layer(web::middleware::from_fn(record_path)) + fn configure_middleware(&self, layers: Layers) -> Layers { + layers.layer(web::middleware::from_fn(record_path)) } } diff --git a/tests/web_routes_access.rs b/tests/web_routes_access.rs new file mode 100644 index 00000000..e95b5bda --- /dev/null +++ b/tests/web_routes_access.rs @@ -0,0 +1,151 @@ +use pagetop::prelude::*; + +struct Granted; + +impl Permission for Granted { + fn key(&self) -> CowStr { + "test:granted".into() + } +} + +struct Denied; + +impl Permission for Denied { + fn key(&self) -> CowStr { + "test:denied".into() + } +} + +// Grants `test:granted` to everybody, as an authentication extension would. +fn grant(_: &HttpRequest, perm: PermissionRef, granted: &mut bool) { + if perm.key() == "test:granted" { + *granted = true; + } +} + +// Offers the login form to an anonymous user without access, as an authentication extension would. +fn offer_login(_: &HttpRequest) -> Option { + Some(Redirect::see_other("/login")) +} + +// Signs in the requests that carry an `x-user` header. +async fn sign_in(mut request: web::Request, next: web::middleware::Next) -> Response { + if request.headers().contains_key("x-user") { + request + .extensions_mut() + .insert(CurrentUser::authenticated(1, "Test user")); + } + next.run(request).await +} + +async fn ok() -> &'static str { + "ok" +} + +struct Ext; + +#[async_trait] +impl Extension for Ext { + fn actions(&self) -> Vec { + actions![ + action::auth::CheckPermission::new(grant), + action::auth::AnonymousDenied::new(offer_login), + ] + } + + fn configure_router(&self, routes: Routes) -> Routes { + routes + .public_route("/public", web::get(ok)) + .route("/account", Access::Authenticated, web::get(ok)) + .route("/granted", Access::Permission(&Granted), web::get(ok)) + .route("/denied", Access::Permission(&Denied), web::get(ok)) + // Reading is public, writing needs a permission that nobody has. + .public_route("/notes", web::get(ok)) + .route("/notes", Access::Permission(&Denied), web::post(ok)) + // Their own fallbacks require the access too. + .route( + "/hooks", + Access::Permission(&Denied), + web::get(ok).fallback(ok), + ) + .nest( + "/api", + Access::Permission(&Denied), + Router::new().route("/data", web::get(ok)).fallback(ok), + ) + .nest_service("/files", Access::Authenticated, web::ServeDir::new("tests")) + } + + fn configure_middleware(&self, layers: Layers) -> Layers { + layers.layer(web::middleware::from_fn(sign_in)) + } +} + +async fn send(method: &str, uri: &str, user: bool) -> (u16, Option) { + let app = Application::prepare(&Ext).await.test(); + let request = if method == "POST" { + web::test::TestRequest::post() + } else { + web::test::TestRequest::get() + }; + let request = if user { + request.header("x-user", "1") + } else { + request + }; + let response = web::test::send_request(&app, request.uri(uri).to_request()).await; + let location = response + .headers() + .get("location") + .map(|value| value.to_str().unwrap().to_owned()); + (response.status().as_u16(), location) +} + +#[pagetop::test] +async fn a_public_route_is_open_to_everybody() { + assert_eq!(send("GET", "/public", false).await.0, 200); + assert_eq!(send("GET", "/public", true).await.0, 200); +} + +#[pagetop::test] +async fn an_anonymous_user_without_access_gets_the_response_of_the_action() { + let login = (303, Some("/login".to_owned())); + assert_eq!(send("GET", "/account", false).await, login); + assert_eq!(send("GET", "/denied", false).await, login); + // A granted permission does not need a session. + assert_eq!(send("GET", "/granted", false).await.0, 200); +} + +#[pagetop::test] +async fn an_authenticated_user_without_access_gets_access_denied() { + assert_eq!(send("GET", "/account", true).await.0, 200); + assert_eq!(send("GET", "/granted", true).await.0, 200); + assert_eq!(send("GET", "/denied", true).await.0, 403); +} + +#[pagetop::test] +async fn each_method_of_a_route_has_its_own_access() { + assert_eq!(send("GET", "/notes", true).await.0, 200); + assert_eq!(send("POST", "/notes", true).await.0, 403); +} + +#[pagetop::test] +async fn the_fallback_of_a_route_requires_its_access() { + assert_eq!(send("POST", "/hooks", true).await.0, 403); + assert_eq!(send("GET", "/api/other", true).await.0, 403); +} + +#[pagetop::test] +async fn nested_routers_and_services_share_the_access_of_the_prefix() { + assert_eq!(send("GET", "/api/data", true).await.0, 403); + assert_eq!( + send("GET", "/files/web_routes_access.rs", true).await.0, + 200 + ); + assert_eq!( + send("GET", "/files/web_routes_access.rs", false).await.0, + 303 + ); + // Routes that are not mounted are not affected. + assert_eq!(send("GET", "/missing", true).await.0, 404); +} diff --git a/tests/web_test_request.rs b/tests/web_test_request.rs index 014c8b7e..c8235901 100644 --- a/tests/web_test_request.rs +++ b/tests/web_test_request.rs @@ -18,8 +18,8 @@ struct Echo; #[async_trait] impl Extension for Echo { - fn configure_router(&self, router: Router) -> Router { - router.route( + fn configure_router(&self, routes: Routes) -> Routes { + routes.public_route( "/item", web::get(|| async { "get" }) .post(echo) diff --git a/tests/web_upload.rs b/tests/web_upload.rs index f0fd8eb5..091d9f03 100644 --- a/tests/web_upload.rs +++ b/tests/web_upload.rs @@ -78,15 +78,15 @@ struct Uploads; #[async_trait] impl Extension for Uploads { - fn configure_router(&self, router: Router) -> Router { - router - .route( + fn configure_router(&self, routes: Routes) -> Routes { + routes + .public_route( "/plain", web::post(|multipart: web::Multipart| { save_all(web::Upload::new().with_subdir("plain"), multipart) }), ) - .route( + .public_route( "/images", web::post(|multipart: web::Multipart| { let upload = web::Upload::new() @@ -95,20 +95,20 @@ impl Extension for Uploads { save_all(upload, multipart) }), ) - .route( + .public_route( "/small", web::post(|multipart: web::Multipart| { let upload = web::Upload::new().with_subdir("small").with_max_size(4); save_all(upload, multipart) }), ) - .route( + .public_route( "/escape", web::post(|multipart: web::Multipart| { save_all(web::Upload::new().with_subdir("../escape"), multipart) }), ) - .route( + .public_route( "/receive/{subdir}", web::post( |web::Path(subdir): web::Path, multipart: web::Multipart| { @@ -116,7 +116,7 @@ impl Extension for Uploads { }, ), ) - .route( + .public_route( "/form", web::post( |web::Form(form): web::Form>| async move { @@ -124,13 +124,13 @@ impl Extension for Uploads { }, ), ) - .route( + .public_route( "/files/{*path}", web::get(|request: HttpRequest, web::Path(path): web::Path| { serve(request, web::Download::new(path)) }), ) - .route( + .public_route( "/named/{*path}", web::get(|request: HttpRequest, web::Path(path): web::Path| { serve( @@ -139,7 +139,7 @@ impl Extension for Uploads { ) }), ) - .route( + .public_route( "/attach/{*path}", web::get(|request: HttpRequest, web::Path(path): web::Path| { serve(request, web::Download::new(path).with_attachment(true))