✨ (admin): Integra el panel de administración
El núcleo reúne al arrancar las secciones, páginas, pestañas y botones que declaran las extensiones. La plantilla Admin pinta la navegación (AdminMenu) y el marco de cada página (AdminFrame), y PageTop monta el dashboard y las páginas de sección. La raíz del panel se configura con admin_path.
This commit is contained in:
parent
ecba7b2bd8
commit
8e0c887ba6
24 changed files with 1737 additions and 19 deletions
|
|
@ -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";
|
||||
|
||||
|
|
|
|||
51
assets/scss/basic/_admin.scss
Normal file
51
assets/scss/basic/_admin.scss
Normal file
|
|
@ -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;
|
||||
}
|
||||
|
|
@ -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'.
|
||||
|
|
|
|||
142
src/admin.rs
Normal file
142
src/admin.rs
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
//! 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 {
|
||||
//! path: "config/export".to_owned(),
|
||||
//! section: "config".to_owned(),
|
||||
//! title: Lc::n("Export"),
|
||||
//! description: Lc::n("Export site data."),
|
||||
//! weight: 0,
|
||||
//! permission: &ToolsPermission::Export,
|
||||
//! });
|
||||
//! }
|
||||
//!
|
||||
//! // PageTop ya ha comprobado el permiso de la página antes de llegar aquí.
|
||||
//! async fn export(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
//! Page::admin(request)
|
||||
//! .with_title(Lc::n("Export"))
|
||||
//! .render()
|
||||
//! .await
|
||||
//! }
|
||||
//!
|
||||
//! pub struct Tools;
|
||||
//!
|
||||
//! #[async_trait]
|
||||
//! impl Extension for Tools {
|
||||
//! fn actions(&self) -> Vec<ActionBox> {
|
||||
//! 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()
|
||||
.values()
|
||||
.any(|page| registry.sections().contains_key(&page.section) && page.is_accessible(cx))
|
||||
}
|
||||
57
src/admin/bag.rs
Normal file
57
src/admin/bag.rs
Normal file
|
|
@ -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<AdminSection>,
|
||||
}
|
||||
|
||||
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<AdminPage>,
|
||||
}
|
||||
|
||||
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<AdminTask>,
|
||||
}
|
||||
|
||||
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<AdminAction>,
|
||||
}
|
||||
|
||||
impl AdminActionBag {
|
||||
/// Añade una acción local al registro.
|
||||
pub fn add(&mut self, action: AdminAction) {
|
||||
self.actions.push(action);
|
||||
}
|
||||
}
|
||||
125
src/admin/pages.rs
Normal file
125
src/admin/pages.rs
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
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 clave, la misma que encuentra
|
||||
// `section_page()`.
|
||||
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().values() {
|
||||
if section.path.is_empty()
|
||||
|| registry.pages().contains_key(§ion.path)
|
||||
|| registry.pages_for_section(§ion.key).is_empty()
|
||||
|| !mounted.insert(section.path.as_str())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
router = router.route(&admin_path(§ion.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().ordered_sections();
|
||||
let Some(content) = sections_with_pages(page.context(), §ions) 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()
|
||||
.sections()
|
||||
.values()
|
||||
.find(|s| s.path == path)
|
||||
else {
|
||||
return ErrorPage::NotFound(Some(request)).into_response();
|
||||
};
|
||||
|
||||
let page = Page::admin(request.clone());
|
||||
let Some(content) = sections_with_pages(page.context(), &[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<Container> {
|
||||
let registry = AdminRegistry::global();
|
||||
let visible: Vec<_> = candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.map(|section| {
|
||||
let pages: Vec<_> = registry
|
||||
.pages_for_section(§ion.key)
|
||||
.into_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(§ion.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)
|
||||
}
|
||||
512
src/admin/registry.rs
Normal file
512
src/admin/registry.rs
Normal file
|
|
@ -0,0 +1,512 @@
|
|||
use crate::Getters;
|
||||
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::{trace, util};
|
||||
|
||||
use super::bag::{AdminActionBag, AdminPageBag, AdminSectionBag, AdminTaskBag};
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
// **< Tipos del registro >*************************************************************************
|
||||
|
||||
/// 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.
|
||||
#[derive(Clone)]
|
||||
pub struct AdminSection {
|
||||
/// Identificador único de la sección (p. ej. `"config"`).
|
||||
pub key: String,
|
||||
/// Ruta de la sección, relativa a la raíz del panel (p. ej. `"config"`).
|
||||
pub path: String,
|
||||
/// Título visible en la navegación.
|
||||
pub title: Lc,
|
||||
/// Peso para ordenar las secciones (menor = antes).
|
||||
pub weight: i32,
|
||||
}
|
||||
|
||||
/// Página del panel de administración.
|
||||
#[derive(Clone)]
|
||||
pub struct AdminPage {
|
||||
/// Ruta de la página, relativa a la raíz del panel (p. ej. `"config/site"`).
|
||||
pub path: String,
|
||||
/// Clave de la sección a la que pertenece.
|
||||
pub section: String,
|
||||
/// Título visible en la navegación y en el encabezado de la página.
|
||||
pub title: Lc,
|
||||
/// Descripción breve para el *dashboard* y las páginas de sección, o [`Lc::none()`] si no
|
||||
/// tiene.
|
||||
pub description: Lc,
|
||||
/// Peso dentro de la sección (menor = antes).
|
||||
pub weight: i32,
|
||||
/// 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)).
|
||||
pub permission: PermissionRef,
|
||||
}
|
||||
|
||||
impl AdminPage {
|
||||
/// 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))
|
||||
}
|
||||
}
|
||||
|
||||
/// Tarea (pestaña) local dentro de una página de administración.
|
||||
#[derive(Clone)]
|
||||
pub struct AdminTask {
|
||||
/// Ruta de la tarea, relativa a la raíz del panel.
|
||||
pub path: String,
|
||||
/// Ruta de la página padre, relativa a la raíz del panel.
|
||||
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 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*.
|
||||
pub permission: Option<PermissionRef>,
|
||||
}
|
||||
|
||||
/// Acción local (botón de acción) en una página de administración.
|
||||
#[derive(Clone)]
|
||||
pub struct AdminAction {
|
||||
/// Ruta de destino de la acción, relativa a la raíz del panel.
|
||||
pub url: String,
|
||||
/// Página en la que aparece el botón, relativa a la raíz del panel.
|
||||
pub for_path: String,
|
||||
/// Etiqueta del botón.
|
||||
pub title: Lc,
|
||||
/// Peso (menor = primero).
|
||||
pub weight: i32,
|
||||
/// 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*.
|
||||
pub permission: Option<PermissionRef>,
|
||||
}
|
||||
|
||||
// **< 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.
|
||||
#[derive(Getters)]
|
||||
pub struct AdminRegistry {
|
||||
/// Devuelve las secciones indexadas por clave (`BTreeMap` para orden estable por clave).
|
||||
sections: BTreeMap<String, AdminSection>,
|
||||
/// Devuelve las páginas indexadas por ruta.
|
||||
pages: BTreeMap<String, AdminPage>,
|
||||
/// Devuelve las tareas indexadas por ruta de página padre.
|
||||
tasks: BTreeMap<String, Vec<AdminTask>>,
|
||||
/// Devuelve las acciones indexadas por ruta de página.
|
||||
actions: BTreeMap<String, Vec<AdminAction>>,
|
||||
}
|
||||
|
||||
static REGISTRY: OnceLock<AdminRegistry> = OnceLock::new();
|
||||
|
||||
static EMPTY_REGISTRY: AdminRegistry = AdminRegistry {
|
||||
sections: BTreeMap::new(),
|
||||
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)
|
||||
}
|
||||
|
||||
// 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.pages.get(candidate) {
|
||||
return Some(page);
|
||||
}
|
||||
candidate = candidate.rsplit_once('/')?.0;
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
|
||||
// **< 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 registry = AdminRegistry {
|
||||
sections: BTreeMap::new(),
|
||||
pages: BTreeMap::new(),
|
||||
tasks: BTreeMap::new(),
|
||||
actions: BTreeMap::new(),
|
||||
};
|
||||
|
||||
let mut section_bag = AdminSectionBag {
|
||||
sections: default_sections(),
|
||||
};
|
||||
DeclareAdminSections::dispatch(&mut section_bag);
|
||||
for mut s in section_bag.sections {
|
||||
s.path = relative(s.path);
|
||||
registry.sections.insert(s.key.clone(), s);
|
||||
}
|
||||
|
||||
let mut warnings = Vec::new();
|
||||
|
||||
let mut page_bag = AdminPageBag { pages: Vec::new() };
|
||||
DeclareAdminPages::dispatch(&mut page_bag);
|
||||
for mut p in page_bag.pages {
|
||||
p.path = relative(p.path);
|
||||
if registry.pages.contains_key(&p.path) {
|
||||
warnings.push(format!(
|
||||
"Admin page \"{}\" is declared more than once; the last declaration wins",
|
||||
p.path
|
||||
));
|
||||
}
|
||||
registry.pages.insert(p.path.clone(), p);
|
||||
}
|
||||
|
||||
let mut task_bag = AdminTaskBag { tasks: Vec::new() };
|
||||
DeclareAdminTasks::dispatch(&mut task_bag);
|
||||
for mut t in task_bag.tasks {
|
||||
t.path = relative(t.path);
|
||||
t.parent_path = relative(t.parent_path);
|
||||
registry
|
||||
.tasks
|
||||
.entry(t.parent_path.clone())
|
||||
.or_default()
|
||||
.push(t);
|
||||
}
|
||||
|
||||
let mut action_bag = AdminActionBag {
|
||||
actions: Vec::new(),
|
||||
};
|
||||
DeclareAdminActions::dispatch(&mut action_bag);
|
||||
for mut a in action_bag.actions {
|
||||
a.url = relative(a.url);
|
||||
a.for_path = relative(a.for_path);
|
||||
registry
|
||||
.actions
|
||||
.entry(a.for_path.clone())
|
||||
.or_default()
|
||||
.push(a);
|
||||
}
|
||||
|
||||
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 clave tendría página.
|
||||
fn check_references(registry: &AdminRegistry) -> Vec<String> {
|
||||
let mut warnings = Vec::new();
|
||||
let mut section_paths: BTreeMap<&str, &str> = BTreeMap::new();
|
||||
for section in registry.sections.values() {
|
||||
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 registry.pages.values() {
|
||||
if !registry.sections.contains_key(&page.section) {
|
||||
warnings.push(format!(
|
||||
"Admin page \"{}\" belongs to the unknown section \"{}\", not shown",
|
||||
page.path, page.section
|
||||
));
|
||||
}
|
||||
}
|
||||
for (parent, tasks) in ®istry.tasks {
|
||||
if !registry.pages.contains_key(parent) {
|
||||
for task in tasks {
|
||||
warnings.push(format!(
|
||||
"Admin task \"{}\" belongs to the undeclared page \"{parent}\", not shown",
|
||||
task.path
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let is_task = |path: &str| registry.tasks.values().flatten().any(|t| t.path == path);
|
||||
for (for_path, actions) in ®istry.actions {
|
||||
if !registry.pages.contains_key(for_path) && !is_task(for_path) {
|
||||
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<String> {
|
||||
let mut missing: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
let mut check = |perm: PermissionRef, piece: String| {
|
||||
if !catalog.has(perm) {
|
||||
missing
|
||||
.entry(perm.key().into_owned())
|
||||
.or_default()
|
||||
.push(piece);
|
||||
}
|
||||
};
|
||||
for page in registry.pages.values() {
|
||||
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<AdminSection> {
|
||||
[
|
||||
("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 {
|
||||
key: key.to_owned(),
|
||||
path: key.to_owned(),
|
||||
title: Lc::l(title),
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
fn page(path: &str, section: &str) -> AdminPage {
|
||||
AdminPage {
|
||||
path: path.to_owned(),
|
||||
section: section.to_owned(),
|
||||
title: Lc::n("Page"),
|
||||
description: Lc::none(),
|
||||
weight: 0,
|
||||
permission: &AnyPermission,
|
||||
}
|
||||
}
|
||||
|
||||
fn task(path: &str, parent_path: &str) -> AdminTask {
|
||||
AdminTask {
|
||||
path: path.to_owned(),
|
||||
parent_path: parent_path.to_owned(),
|
||||
title: Lc::n("Task"),
|
||||
weight: 0,
|
||||
is_default: false,
|
||||
permission: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn action(url: &str, for_path: &str) -> AdminAction {
|
||||
AdminAction {
|
||||
url: url.to_owned(),
|
||||
for_path: for_path.to_owned(),
|
||||
title: Lc::n("Action"),
|
||||
weight: 0,
|
||||
permission: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_to_undeclared_pieces_are_reported() {
|
||||
let mut registry = AdminRegistry {
|
||||
sections: default_sections()
|
||||
.into_iter()
|
||||
.map(|s| (s.key.clone(), s))
|
||||
.collect(),
|
||||
pages: BTreeMap::new(),
|
||||
tasks: BTreeMap::new(),
|
||||
actions: BTreeMap::new(),
|
||||
};
|
||||
let mut settings = registry.sections["config"].clone();
|
||||
settings.key = "settings".to_owned();
|
||||
registry.sections.insert(settings.key.clone(), settings);
|
||||
for p in [page("config/site", "config"), page("tools/x", "tools")] {
|
||||
registry.pages.insert(p.path.clone(), p);
|
||||
}
|
||||
registry.tasks.insert(
|
||||
"config/site".to_owned(),
|
||||
vec![task("config/site/advanced", "config/site")],
|
||||
);
|
||||
registry.tasks.insert(
|
||||
"config/sit".to_owned(),
|
||||
vec![task("config/sit/typo", "config/sit")],
|
||||
);
|
||||
for a in [
|
||||
action("config/site/new", "config/site"),
|
||||
action("config/site/advanced/new", "config/site/advanced"),
|
||||
action("config/other/new", "config/other"),
|
||||
] {
|
||||
registry
|
||||
.actions
|
||||
.entry(a.for_path.clone())
|
||||
.or_default()
|
||||
.push(a);
|
||||
}
|
||||
|
||||
let warnings = check_references(®istry);
|
||||
assert_eq!(warnings.len(), 4, "{warnings:?}");
|
||||
assert!(warnings[0].contains("\"config\" and \"settings\" 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"));
|
||||
}
|
||||
|
||||
struct OtherPermission;
|
||||
|
||||
impl Permission for OtherPermission {
|
||||
fn key(&self) -> CowStr {
|
||||
"test:other".into()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions_missing_from_the_catalog_are_reported_once_each() {
|
||||
let mut registry = AdminRegistry {
|
||||
sections: BTreeMap::new(),
|
||||
pages: BTreeMap::new(),
|
||||
tasks: BTreeMap::new(),
|
||||
actions: BTreeMap::new(),
|
||||
};
|
||||
for p in [
|
||||
page("config/site", "config"),
|
||||
page("config/other", "config"),
|
||||
] {
|
||||
registry.pages.insert(p.path.clone(), p);
|
||||
}
|
||||
let mut advanced = task("config/site/advanced", "config/site");
|
||||
advanced.permission = Some(&OtherPermission);
|
||||
registry
|
||||
.tasks
|
||||
.insert("config/site".to_owned(), vec![advanced]);
|
||||
|
||||
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\""));
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
||||
|
|
|
|||
175
src/base/component/admin_frame.rs
Normal file
175
src/base/component/admin_frame.rs
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
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 `<title>` 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().pages().get(&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.sections().get(&page.section) {
|
||||
bc = bc.with_crumb(breadcrumb::Crumb::new(
|
||||
section.title.clone(),
|
||||
admin_path(§ion.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.sections().values().find(|s| s.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
|
||||
.tasks()
|
||||
.values()
|
||||
.flatten()
|
||||
.find(|task| task.path == path)
|
||||
.map_or(path, |task| task.parent_path.as_str());
|
||||
let tasks: Vec<_> = registry
|
||||
.tasks_for(parent)
|
||||
.into_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)
|
||||
.into_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))
|
||||
})
|
||||
}
|
||||
60
src/base/component/admin_menu.rs
Normal file
60
src/base/component/admin_menu.rs
Normal file
|
|
@ -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.ordered_sections() {
|
||||
let pages: Vec<_> = registry
|
||||
.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(),
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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! {
|
||||
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)
|
||||
}
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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| {
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
9
src/locale/en-US/admin.ftl
Normal file
9
src/locale/en-US/admin.ftl
Normal file
|
|
@ -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
|
||||
|
|
@ -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 }
|
||||
|
||||
|
|
|
|||
9
src/locale/es-ES/admin.ftl
Normal file
9
src/locale/es-ES/admin.ftl
Normal file
|
|
@ -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
|
||||
|
|
@ -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 }
|
||||
|
||||
|
|
|
|||
|
|
@ -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::*;
|
||||
|
|
|
|||
52
tests/admin_invalid_route.rs
Normal file
52
tests/admin_invalid_route.rs
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
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 {
|
||||
path: "config/export".to_owned(),
|
||||
section: "config".to_owned(),
|
||||
title: Lc::n("Export"),
|
||||
description: Lc::none(),
|
||||
weight: 0,
|
||||
permission: &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();
|
||||
}
|
||||
155
tests/admin_registry.rs
Normal file
155
tests/admin_registry.rs
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
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 {
|
||||
key: "tools".to_owned(),
|
||||
path: "tools".to_owned(),
|
||||
title: Lc::n("Tools"),
|
||||
weight: 35,
|
||||
});
|
||||
// Replaces the built-in section with the same key.
|
||||
bag.add(AdminSection {
|
||||
key: "help".to_owned(),
|
||||
path: "support".to_owned(),
|
||||
title: Lc::n("Support"),
|
||||
weight: 5,
|
||||
});
|
||||
}
|
||||
|
||||
fn declare_pages(bag: &mut AdminPageBag) {
|
||||
for (path, weight) in [("tools/export", 10), ("/tools/import/", 0)] {
|
||||
bag.add(AdminPage {
|
||||
path: path.to_owned(),
|
||||
section: "tools".to_owned(),
|
||||
title: Lc::n(path),
|
||||
description: Lc::none(),
|
||||
weight,
|
||||
permission: &ToolsPermission,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn declare_tasks(bag: &mut AdminTaskBag) {
|
||||
for (path, weight) in [("tools/export/json", 1), ("tools/export/csv", 0)] {
|
||||
bag.add(AdminTask {
|
||||
path: path.to_owned(),
|
||||
parent_path: "/tools/export".to_owned(),
|
||||
title: Lc::n(path),
|
||||
weight,
|
||||
is_default: weight == 0,
|
||||
permission: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn declare_actions(bag: &mut AdminActionBag) {
|
||||
bag.add(AdminAction {
|
||||
url: "tools/export/new/".to_owned(),
|
||||
for_path: "tools/export".to_owned(),
|
||||
title: Lc::n("New export"),
|
||||
weight: 0,
|
||||
permission: None,
|
||||
});
|
||||
}
|
||||
|
||||
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()
|
||||
.ordered_sections()
|
||||
.into_iter()
|
||||
.map(|s| (s.key.as_str(), s.path.as_str()))
|
||||
.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")
|
||||
.into_iter()
|
||||
.map(|p| p.path.as_str())
|
||||
.collect();
|
||||
assert_eq!(pages, ["tools/import", "tools/export"]);
|
||||
|
||||
let tasks: Vec<_> = registry
|
||||
.tasks_for("tools/export")
|
||||
.into_iter()
|
||||
.map(|t| t.path.as_str())
|
||||
.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));
|
||||
}
|
||||
233
tests/admin_template.rs
Normal file
233
tests/admin_template.rs
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
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 {
|
||||
path: "config/export".to_owned(),
|
||||
section: "config".to_owned(),
|
||||
title: Lc::n("Export"),
|
||||
description: Lc::none(),
|
||||
weight: 0,
|
||||
permission: &ToolsPermission,
|
||||
});
|
||||
bag.add(AdminPage {
|
||||
path: "reports/audit".to_owned(),
|
||||
section: "reports".to_owned(),
|
||||
title: Lc::n("Audit"),
|
||||
description: Lc::none(),
|
||||
weight: 0,
|
||||
permission: &AuditPermission,
|
||||
});
|
||||
}
|
||||
|
||||
fn declare_tasks(bag: &mut AdminTaskBag) {
|
||||
bag.add(AdminTask {
|
||||
path: "config/export".to_owned(),
|
||||
parent_path: "config/export".to_owned(),
|
||||
title: Lc::n("All"),
|
||||
weight: 0,
|
||||
is_default: true,
|
||||
permission: None,
|
||||
});
|
||||
bag.add(AdminTask {
|
||||
path: "config/export/csv".to_owned(),
|
||||
parent_path: "config/export".to_owned(),
|
||||
title: Lc::n("CSV"),
|
||||
weight: 1,
|
||||
is_default: false,
|
||||
permission: None,
|
||||
});
|
||||
bag.add(AdminTask {
|
||||
path: "config/export/log".to_owned(),
|
||||
parent_path: "config/export".to_owned(),
|
||||
title: Lc::n("Log"),
|
||||
weight: 2,
|
||||
is_default: false,
|
||||
permission: Some(&AuditPermission),
|
||||
});
|
||||
}
|
||||
|
||||
fn declare_actions(bag: &mut AdminActionBag) {
|
||||
bag.add(AdminAction {
|
||||
url: "config/export/new".to_owned(),
|
||||
for_path: "config/export".to_owned(),
|
||||
title: Lc::n("New export"),
|
||||
weight: 0,
|
||||
permission: None,
|
||||
});
|
||||
bag.add(AdminAction {
|
||||
url: "config/export/purge".to_owned(),
|
||||
for_path: "config/export".to_owned(),
|
||||
title: Lc::n("Purge exports"),
|
||||
weight: 1,
|
||||
permission: Some(&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</title>"), "{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#"<a href="/admin/config/export">Export</a>"#),
|
||||
"{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#"<a href="/admin/config/export">Export</a>"#),
|
||||
"{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);
|
||||
}
|
||||
15
tests/admin_without_pages.rs
Normal file
15
tests/admin_without_pages.rs
Normal file
|
|
@ -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}");
|
||||
}
|
||||
}
|
||||
|
|
@ -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")
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue