Compare commits
No commits in common. "a0416e567070f4198cba2a7b15f8b23016529542" and "9afbafdefb5c70486f3e324155ca8f8a5714e6bc" have entirely different histories.
a0416e5670
...
9afbafdefb
125 changed files with 2646 additions and 5163 deletions
1
Cargo.lock
generated
1
Cargo.lock
generated
|
|
@ -2308,6 +2308,7 @@ dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
"base64ct",
|
"base64ct",
|
||||||
"pagetop",
|
"pagetop",
|
||||||
|
"pagetop-admin",
|
||||||
"pagetop-htmx",
|
"pagetop-htmx",
|
||||||
"pagetop-mail",
|
"pagetop-mail",
|
||||||
"pagetop-seaorm",
|
"pagetop-seaorm",
|
||||||
|
|
|
||||||
10
README.md
10
README.md
|
|
@ -53,8 +53,8 @@ struct HelloWorld;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for HelloWorld {
|
impl Extension for HelloWorld {
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/", web::get(hello_world))
|
router.route("/", web::get(hello_world))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -102,8 +102,8 @@ El código se organiza en un *workspace* donde actualmente se incluyen los sigui
|
||||||
### Extensiones
|
### Extensiones
|
||||||
|
|
||||||
* **[pagetop-admin](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-admin)**,
|
* **[pagetop-admin](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-admin)**,
|
||||||
páginas de ajustes del panel de administración que se guardan en la base de datos y se cambian
|
panel de administración extensible, al que cada extensión añade sus secciones, páginas y
|
||||||
desde el propio panel.
|
formularios de configuración.
|
||||||
|
|
||||||
* **[pagetop-aliner](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-aliner)**,
|
* **[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.
|
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.
|
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)**,
|
* **[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 el panel.
|
gestiona usuarios, autenticación, roles y permisos, con su administración en `pagetop-admin`.
|
||||||
|
|
||||||
## Pruebas
|
## Pruebas
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -34,9 +34,6 @@
|
||||||
// Theme regions.
|
// Theme regions.
|
||||||
@use "basic/regions";
|
@use "basic/regions";
|
||||||
|
|
||||||
// Frame of the administration pages.
|
|
||||||
@use "basic/admin";
|
|
||||||
|
|
||||||
// Styles for the pages of the `pagetop-user` extension.
|
// Styles for the pages of the `pagetop-user` extension.
|
||||||
@use "basic/user";
|
@use "basic/user";
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,51 +0,0 @@
|
||||||
// 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,10 +76,6 @@ 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
|
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
|
# se usa siempre 'timezone' (false). Con false no se ofrece
|
||||||
# elegirla y la guardada se conserva por si se reactiva.
|
# 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"
|
startup_banner = "Slant" # Banner ASCII al arrancar: "Off", "Slant", "Small", "Speed"
|
||||||
# o "Starwars".
|
# o "Starwars".
|
||||||
|
|
||||||
|
|
@ -125,11 +121,11 @@ trusted_origins = [] # Otros orígenes desde los que un navega
|
||||||
dir = "uploads" # Directorio de los archivos subidos, absoluto o relativo al
|
dir = "uploads" # Directorio de los archivos subidos, absoluto o relativo al
|
||||||
# directorio de trabajo. Se crea al guardar el primero.
|
# 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'
|
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;
|
# completo (32 MiB), con todos sus archivos y campos; sustituye
|
||||||
# sustituye a 'server.max_body_size' en estas peticiones.
|
# a 'server.max_body_size' en estas peticiones. Para admitir
|
||||||
# Para admitir varios archivos debe ser varias veces mayor
|
# varios archivos debe ser varias veces mayor que
|
||||||
# que 'max_file_size'. Uno mayor se rechaza con 413. 0 ->
|
# 'max_file_size'. Uno mayor se rechaza con 413. 0 -> sin
|
||||||
# sin límite.
|
# límite.
|
||||||
max_file_size = 8_388_608 # Tamaño máximo en bytes de cada archivo por separado
|
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
|
# (8 MiB). La aplicación puede cambiarlo en una subida
|
||||||
# concreta. 0 -> sólo limita 'max_request_size'.
|
# concreta. 0 -> sólo limita 'max_request_size'.
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,8 @@ impl Extension for FormControls {
|
||||||
vec![&pagetop_aliner::Aliner, &pagetop_bootsier::Bootsier]
|
vec![&pagetop_aliner::Aliner, &pagetop_bootsier::Bootsier]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/", web::get(form_controls).post(form_controls))
|
router.route("/", web::get(form_controls).post(form_controls))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@ struct HelloName;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for HelloName {
|
impl Extension for HelloName {
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/hello/{name}", web::get(hello_name))
|
router.route("/hello/{name}", web::get(hello_name))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@ struct HelloWorld;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for HelloWorld {
|
impl Extension for HelloWorld {
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/", web::get(hello_world))
|
router.route("/", web::get(hello_world))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,8 @@ struct IntroColors;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for IntroColors {
|
impl Extension for IntroColors {
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/", web::get(intro_colors))
|
router.route("/", web::get(intro_colors))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,8 @@ struct IntroDatetime;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for IntroDatetime {
|
impl Extension for IntroDatetime {
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/", web::get(intro_datetime))
|
router.route("/", web::get(intro_datetime))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,8 @@ impl Extension for IntroFlex {
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
vec![&pagetop_bootsier::Bootsier]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/", web::get(intro_flex))
|
router.route("/", web::get(intro_flex))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,8 @@ impl Extension for IntroGrid {
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
vec![&pagetop_bootsier::Bootsier]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/", web::get(intro_grid))
|
router.route("/", web::get(intro_grid))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,8 @@ impl Extension for IntroResponsive {
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
vec![&pagetop_bootsier::Bootsier]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/", web::get(intro_responsive))
|
router.route("/", web::get(intro_responsive))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,8 @@ impl Extension for IntroSpacing {
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
vec![&pagetop_bootsier::Bootsier]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/", web::get(intro_spacing))
|
router.route("/", web::get(intro_spacing))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,8 @@ impl Extension for NavbarMenus {
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
vec![&pagetop_bootsier::Bootsier]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/", web::get(navbar_menus))
|
router.route("/", web::get(navbar_menus))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
[package]
|
[package]
|
||||||
name = "pagetop-admin"
|
name = "pagetop-admin"
|
||||||
description = "Ajustes guardados en la base de datos para el panel de administración de PageTop."
|
description = "Panel de administración extensible para PageTop."
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
categories = ["web-programming", "development-tools"]
|
categories = ["web-programming", "development-tools"]
|
||||||
keywords = ["pagetop", "admin", "cms", "settings", "ssr"]
|
keywords = ["pagetop", "admin", "cms", "settings", "ssr"]
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
<h1>PageTop Admin</h1>
|
<h1>PageTop Admin</h1>
|
||||||
|
|
||||||
<p>Ajustes guardados en la base de datos para el panel de administración de <strong>PageTop</strong>.</p>
|
<p>Panel de administración extensible para <strong>PageTop</strong>.</p>
|
||||||
|
|
||||||
[](https://docs.rs/pagetop-admin)
|
[](https://docs.rs/pagetop-admin)
|
||||||
[](https://crates.io/crates/pagetop-admin)
|
[](https://crates.io/crates/pagetop-admin)
|
||||||
|
|
@ -11,8 +11,11 @@
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
Añade al panel de administración de PageTop **ajustes que se guardan en la base de datos** y que un
|
Añade a una aplicación PageTop un panel de administración en `/admin` que cada extensión amplía con
|
||||||
administrador cambia desde el propio panel, con la aplicación en marcha.
|
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.
|
||||||
|
|
||||||
## Sobre PageTop
|
## Sobre PageTop
|
||||||
|
|
||||||
|
|
@ -20,35 +23,6 @@ administrador cambia desde el propio panel, con la aplicación en marcha.
|
||||||
clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y
|
clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y
|
||||||
configurables, basadas en HTML, CSS y JavaScript.
|
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
|
## Guía rápida
|
||||||
|
|
||||||
**Añade la dependencia** a tu `Cargo.toml`:
|
**Añade la dependencia** a tu `Cargo.toml`:
|
||||||
|
|
@ -58,15 +32,16 @@ casillas (`"42"`, `"true"`): se leen como `String` y se convierten al usarlos.
|
||||||
pagetop-admin = "..."
|
pagetop-admin = "..."
|
||||||
```
|
```
|
||||||
|
|
||||||
Los ajustes se guardan con `pagetop-seaorm`: la aplicación elige el motor de base de datos con su
|
La configuración se guarda con `pagetop-seaorm`: la aplicación elige el motor de base de datos con
|
||||||
*feature* (`postgres`, `mysql` o `sqlite`) y configura la conexión en la sección `[database]`.
|
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`); si no, sus páginas
|
**Declara la extensión** como dependencia de la tuya (`&pagetop_admin::Admin`) y **añade al panel**
|
||||||
de ajustes no se montan. Después **declara tus páginas de ajustes**, cada una con su permiso:
|
tus secciones, páginas o formularios de configuración:
|
||||||
|
|
||||||
```rust,no_run
|
```rust,no_run
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
use pagetop_admin::prelude::*;
|
use pagetop_admin::prelude::*;
|
||||||
|
use pagetop_admin::settings::{SettingField, SettingsSchema};
|
||||||
|
|
||||||
pub struct MyApp;
|
pub struct MyApp;
|
||||||
|
|
||||||
|
|
@ -77,17 +52,25 @@ impl Extension for MyApp {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
fn actions(&self) -> Vec<ActionBox> {
|
||||||
actions![DeclareConfigForms::new(declare_forms)]
|
actions![
|
||||||
|
DeclareAdminPages::new(declare_pages),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
|
router.route("/admin/config/myapp", web::get(config_handler))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn declare_forms(bag: &mut ConfigFormBag) {
|
fn declare_pages(bag: &mut PageBag) {
|
||||||
bag.add(ConfigFormPage {
|
bag.add(AdminPage {
|
||||||
page: AdminPage::new("config/myapp", "config", Lc::n("My App"), &MyPermission::Config)
|
path: "/admin/config/myapp".to_owned(),
|
||||||
.with_description(Lc::n("Name of the site.")),
|
section: "config".to_owned(),
|
||||||
schema: SettingsSchema::new("myapp").with_field(
|
title: Lc::n("My App"),
|
||||||
SettingField::text("site_name", Lc::n("Site name")).with_required(true),
|
description: Some(Lc::n("Configure My App.")),
|
||||||
),
|
weight: 0,
|
||||||
|
permission: &MyPermission::Config,
|
||||||
|
kind: AdminPageKind::View,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -104,12 +87,31 @@ impl Permission for MyPermission {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Los valores se guardan con la clave `<ámbito>.<campo>`.
|
async fn config_handler(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
async fn site_name() -> String {
|
let schema = SettingsSchema::new("myapp.config")
|
||||||
pagetop_admin::settings::get_or("myapp.site_name", String::new()).await
|
.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
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
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
|
## Advertencia
|
||||||
|
|
||||||
**PageTop** es un proyecto personal para aprender [Rust](https://www.rust-lang.org/es) y conocer su
|
**PageTop** es un proyecto personal para aprender [Rust](https://www.rust-lang.org/es) y conocer su
|
||||||
|
|
|
||||||
|
|
@ -1,119 +1,286 @@
|
||||||
//! Acción para declarar páginas de ajustes que `pagetop-admin` pinta y guarda por sí solo.
|
//! 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.
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
use crate::registry::{AdminAction, AdminPage, AdminSection, AdminTask};
|
||||||
use std::sync::OnceLock;
|
|
||||||
|
|
||||||
use crate::settings::SettingsSchema;
|
// **< Tipo de callbacks >**************************************************************************
|
||||||
|
|
||||||
// **< ConfigFormPage >*****************************************************************************
|
pub type FnSectionBag = fn(&mut SectionBag);
|
||||||
|
pub type FnPageBag = fn(&mut PageBag);
|
||||||
|
pub type FnTaskBag = fn(&mut TaskBag);
|
||||||
|
pub type FnActionBag = fn(&mut ActionBag);
|
||||||
|
|
||||||
/// Página de ajustes del panel: una [`AdminPage`] y el esquema de su formulario.
|
// **< Bolsas de declaración >**********************************************************************
|
||||||
///
|
|
||||||
/// `pagetop-admin` la añade al registro del panel como cualquier otra página, monta su ruta y
|
/// Bolsa de secciones para [`DeclareAdminSections`].
|
||||||
/// responde a su `GET` (el formulario con los valores guardados) y a su `POST` (los guarda en la
|
pub struct SectionBag {
|
||||||
/// base de datos). La extensión que la declara no registra ninguna ruta.
|
pub(crate) sections: Vec<AdminSection>,
|
||||||
#[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`].
|
impl SectionBag {
|
||||||
pub struct ConfigFormBag {
|
/// Añade una sección al registro.
|
||||||
forms: Vec<ConfigFormPage>,
|
pub fn add(&mut self, section: AdminSection) {
|
||||||
}
|
self.sections.push(section);
|
||||||
|
|
||||||
impl ConfigFormBag {
|
|
||||||
/// Añade una página de ajustes.
|
|
||||||
pub fn add(&mut self, form: ConfigFormPage) {
|
|
||||||
self.forms.push(form);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< DeclareConfigForms >*************************************************************************
|
/// Bolsa de páginas para [`DeclareAdminPages`].
|
||||||
|
pub struct PageBag {
|
||||||
|
pub(crate) pages: Vec<AdminPage>,
|
||||||
|
}
|
||||||
|
|
||||||
/// Tipo de función para declarar páginas de ajustes.
|
impl PageBag {
|
||||||
pub type FnActionDeclareConfigForms = fn(bag: &mut ConfigFormBag);
|
/// Añade una página al registro.
|
||||||
|
pub fn add(&mut self, page: AdminPage) {
|
||||||
|
self.pages.push(page);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Acción para declarar páginas de ajustes que gestiona `pagetop-admin` (ver [`ConfigFormPage`]).
|
/// Bolsa de tareas para [`DeclareAdminTasks`].
|
||||||
|
pub struct TaskBag {
|
||||||
|
pub(crate) tasks: Vec<AdminTask>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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<AdminAction>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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.
|
||||||
|
///
|
||||||
|
/// Se despacha durante `registry::build()` (dentro de `initialize()`). El callback
|
||||||
|
/// recibe un [`SectionBag`] y puede llamar a `add()` para registrar secciones.
|
||||||
///
|
///
|
||||||
/// # Ejemplo
|
/// # Ejemplo
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// use pagetop::prelude::*;
|
/// use pagetop::prelude::*;
|
||||||
/// use pagetop_admin::prelude::*;
|
/// use pagetop_admin::action::{DeclareAdminSections, SectionBag};
|
||||||
|
/// use pagetop_admin::registry::AdminSection;
|
||||||
///
|
///
|
||||||
/// #[derive(Clone, Copy, Debug)]
|
/// fn declare_sections(bag: &mut SectionBag) {
|
||||||
/// enum MyPermission {
|
/// bag.add(AdminSection {
|
||||||
/// Config,
|
/// key: "tools".to_owned(),
|
||||||
/// }
|
/// path: "/admin/tools".to_owned(),
|
||||||
///
|
/// title: Lc::n("Tools"),
|
||||||
/// impl Permission for MyPermission {
|
/// weight: 60,
|
||||||
/// fn key(&self) -> CowStr {
|
|
||||||
/// "myapp:config".into()
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
///
|
|
||||||
/// 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():
|
/// // En Extension::actions():
|
||||||
/// // DeclareConfigForms::new(declare_forms)
|
/// // DeclareAdminSections::new(declare_sections)
|
||||||
/// ```
|
/// ```
|
||||||
pub struct DeclareConfigForms {
|
pub struct DeclareAdminSections {
|
||||||
f: FnActionDeclareConfigForms,
|
f: FnSectionBag,
|
||||||
weight: Weight,
|
weight: Weight,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ActionDispatcher for DeclareConfigForms {
|
impl ActionDispatcher for DeclareAdminSections {
|
||||||
fn weight(&self) -> Weight {
|
fn weight(&self) -> Weight {
|
||||||
self.weight
|
self.weight
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DeclareConfigForms {
|
impl DeclareAdminSections {
|
||||||
/// Registra una nueva acción para declarar páginas de ajustes.
|
pub fn new(f: FnSectionBag) -> Self {
|
||||||
pub fn new(f: FnActionDeclareConfigForms) -> Self {
|
DeclareAdminSections { f, weight: 0 }
|
||||||
DeclareConfigForms { f, weight: 0 }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Opcional. Acciones con pesos más bajos se aplican antes. Se pueden usar valores negativos.
|
pub fn with_weight(mut self, w: Weight) -> Self {
|
||||||
pub fn with_weight(mut self, value: Weight) -> Self {
|
self.weight = w;
|
||||||
self.weight = value;
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// **< Registro de las páginas de ajustes >*********************************************************
|
pub(crate) fn dispatch(bag: &mut SectionBag) {
|
||||||
|
dispatch_actions(|action: &Self| (action.f)(bag));
|
||||||
// Esquemas de las páginas de ajustes, por su ruta relativa a la raíz del panel.
|
|
||||||
static CONFIG_FORMS: OnceLock<BTreeMap<String, SettingsSchema>> = 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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Esquemas de las páginas de ajustes, por su ruta relativa a la raíz del panel.
|
// **< DeclareAdminPages >**************************************************************************
|
||||||
pub(crate) fn config_forms() -> &'static BTreeMap<String, SettingsSchema> {
|
|
||||||
static EMPTY: BTreeMap<String, SettingsSchema> = BTreeMap::new();
|
/// Acción para declarar páginas del panel de administración.
|
||||||
CONFIG_FORMS.get().unwrap_or(&EMPTY)
|
///
|
||||||
|
/// 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 {
|
||||||
|
/// fn key(&self) -> CowStr {
|
||||||
|
/// "tools:export".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,
|
||||||
|
/// });
|
||||||
|
/// }
|
||||||
|
/// // En Extension::actions():
|
||||||
|
/// // DeclareAdminPages::new(declare_pages)
|
||||||
|
/// ```
|
||||||
|
pub struct DeclareAdminPages {
|
||||||
|
f: FnPageBag,
|
||||||
|
weight: Weight,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActionDispatcher for DeclareAdminPages {
|
||||||
|
fn weight(&self) -> Weight {
|
||||||
|
self.weight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeclareAdminPages {
|
||||||
|
pub fn new(f: FnPageBag) -> Self {
|
||||||
|
DeclareAdminPages { f, weight: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn with_weight(mut self, w: Weight) -> Self {
|
||||||
|
self.weight = w;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn dispatch(bag: &mut PageBag) {
|
||||||
|
dispatch_actions(|action: &Self| (action.f)(bag));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< DeclareAdminTasks >**************************************************************************
|
||||||
|
|
||||||
|
/// 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,
|
||||||
|
}
|
||||||
|
|
||||||
|
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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,9 @@
|
||||||
//! Componentes de renderizado del panel de administración.
|
//! Componentes de renderizado del panel de administración.
|
||||||
|
|
||||||
|
mod admin_frame;
|
||||||
|
mod admin_menu;
|
||||||
mod config_form;
|
mod config_form;
|
||||||
|
|
||||||
|
pub use admin_frame::AdminFrame;
|
||||||
|
pub use admin_menu::AdminMenu;
|
||||||
pub use config_form::ConfigForm;
|
pub use config_form::ConfigForm;
|
||||||
|
|
|
||||||
150
extensions/pagetop-admin/src/component/admin_frame.rs
Normal file
150
extensions/pagetop-admin/src/component/admin_frame.rs
Normal file
|
|
@ -0,0 +1,150 @@
|
||||||
|
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
|
||||||
|
/// <nav class="admin-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>
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// 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<Markup, ComponentError> {
|
||||||
|
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<ChildOp>) -> 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))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
38
extensions/pagetop-admin/src/component/admin_menu.rs
Normal file
38
extensions/pagetop-admin/src/component/admin_menu.rs
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
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<Markup, ComponentError> {
|
||||||
|
if !matches!(
|
||||||
|
cx.template().downcast_ref::<CoreTemplates>(),
|
||||||
|
Some(CoreTemplates::Admin)
|
||||||
|
) {
|
||||||
|
return Ok(html! {});
|
||||||
|
}
|
||||||
|
Ok(registry::admin_navbar(cx).render(cx).await)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -3,27 +3,35 @@ use pagetop::prelude::*;
|
||||||
use crate::LOCALES_ADMIN;
|
use crate::LOCALES_ADMIN;
|
||||||
use crate::settings::{SettingFieldType, SettingsSchema, get_or};
|
use crate::settings::{SettingFieldType, SettingsSchema, get_or};
|
||||||
|
|
||||||
/// Formulario de un [`SettingsSchema`], con los valores guardados en la tabla `settings`.
|
/// Componente que renderiza un formulario de configuración persistente.
|
||||||
///
|
///
|
||||||
/// En las páginas declaradas con [`DeclareConfigForms`](crate::action::DeclareConfigForms),
|
/// Genera campos HTML a partir de un [`SettingsSchema`] y carga los valores
|
||||||
/// `pagetop-admin` lo muestra y guarda lo que se envía. En una página propia sólo lo muestra: el
|
/// actuales desde `settings`. El POST es procesado por el handler interno
|
||||||
/// envío llega a la ruta de la página, o a la de [`with_action_path()`](Self::with_action_path), y
|
/// `config_form_post`.
|
||||||
/// lo guarda su *handler* (ver [`settings::set()`](crate::settings::set)).
|
|
||||||
///
|
///
|
||||||
/// # Ejemplo
|
/// # Ejemplo
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// use pagetop::prelude::*;
|
/// use pagetop::prelude::*;
|
||||||
/// use pagetop_admin::component::ConfigForm;
|
/// use pagetop_admin::component::{AdminFrame, ConfigForm};
|
||||||
/// use pagetop_admin::settings::{SettingField, SettingsSchema};
|
/// use pagetop_admin::settings::{SettingField, SettingsSchema};
|
||||||
///
|
///
|
||||||
/// async fn settings_handler(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
/// async fn settings_handler(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
/// let schema = SettingsSchema::new("myapp.general")
|
/// let schema = SettingsSchema::new("myapp.general")
|
||||||
/// .with_field(SettingField::text("site_name", Lc::n("Site name")).with_required(true));
|
/// .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;
|
||||||
///
|
///
|
||||||
/// Page::admin(request)
|
/// Page::admin(request)
|
||||||
/// .with_title(Lc::n("General settings"))
|
/// .with_title(Lc::n(title))
|
||||||
/// .with_child(ConfigForm::with_schema(schema))
|
/// .with_child(
|
||||||
|
/// AdminFrame::new()
|
||||||
|
/// .with_title(Lc::n(title))
|
||||||
|
/// .with_child(Html::with(move |_| content.clone())),
|
||||||
|
/// )
|
||||||
/// .render()
|
/// .render()
|
||||||
/// .await
|
/// .await
|
||||||
/// }
|
/// }
|
||||||
|
|
@ -34,6 +42,10 @@ pub struct ConfigForm {
|
||||||
schema: Option<SettingsSchema>,
|
schema: Option<SettingsSchema>,
|
||||||
/// Devuelve la ruta de destino del formulario, si se ha personalizado.
|
/// Devuelve la ruta de destino del formulario, si se ha personalizado.
|
||||||
action_path: Option<Route>,
|
action_path: Option<Route>,
|
||||||
|
/// 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]
|
#[async_trait]
|
||||||
|
|
@ -52,11 +64,22 @@ impl Component for ConfigForm {
|
||||||
None => cx.route(cx.request().map(|r| r.path()).unwrap_or("/")),
|
None => cx.route(cx.request().map(|r| r.path()).unwrap_or("/")),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Pre-computa los valores de BD para cada campo antes del macro html! (que es síncrono). El
|
let save_label = Lc::t("config-save-label", &LOCALES_ADMIN)
|
||||||
// formulario guarda todos los valores como texto (`"42"`, `"true"`), así que se leen como
|
.lookup(cx)
|
||||||
// texto también los de los campos numéricos y las casillas.
|
.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).
|
||||||
struct FieldVals {
|
struct FieldVals {
|
||||||
raw_val: String,
|
raw_val: String,
|
||||||
|
num_val: String,
|
||||||
checked: bool,
|
checked: bool,
|
||||||
}
|
}
|
||||||
let mut prepared: Vec<FieldVals> = Vec::with_capacity(schema.fields().len());
|
let mut prepared: Vec<FieldVals> = Vec::with_capacity(schema.fields().len());
|
||||||
|
|
@ -64,18 +87,27 @@ impl Component for ConfigForm {
|
||||||
let key = schema.key_for(field.name());
|
let key = schema.key_for(field.name());
|
||||||
let raw_val =
|
let raw_val =
|
||||||
get_or::<String>(&key, field.default_value().cloned().unwrap_or_default()).await;
|
get_or::<String>(&key, field.default_value().cloned().unwrap_or_default()).await;
|
||||||
let checked = raw_val == "true";
|
let num_val = get_or::<f64>(&key, 0.0).await.to_string();
|
||||||
prepared.push(FieldVals { raw_val, checked });
|
let checked = get_or::<bool>(&key, false).await;
|
||||||
|
prepared.push(FieldVals {
|
||||||
|
raw_val,
|
||||||
|
num_val,
|
||||||
|
checked,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(html! {
|
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) {
|
form class="admin-config-form" method="post" action=(action) {
|
||||||
@for (i, field) in schema.fields().iter().enumerate() {
|
@for (i, field) in schema.fields().iter().enumerate() {
|
||||||
@let pf = &prepared[i];
|
@let pf = &prepared[i];
|
||||||
div class="admin-form-field" {
|
div class="admin-form-field" {
|
||||||
label class="admin-form-label" for=(field.name()) {
|
label class="admin-form-label" for=(field.name()) { (field.label()) }
|
||||||
(field.label().using(cx))
|
|
||||||
}
|
|
||||||
@match field.field_type() {
|
@match field.field_type() {
|
||||||
SettingFieldType::Text { max_length } => {
|
SettingFieldType::Text { max_length } => {
|
||||||
@if let Some(max) = max_length {
|
@if let Some(max) = max_length {
|
||||||
|
|
@ -101,7 +133,7 @@ impl Component for ConfigForm {
|
||||||
type="number"
|
type="number"
|
||||||
id=(field.name())
|
id=(field.name())
|
||||||
name=(field.name())
|
name=(field.name())
|
||||||
value=(&pf.raw_val)
|
value=(&pf.num_val)
|
||||||
min=(lo)
|
min=(lo)
|
||||||
max=(hi)
|
max=(hi)
|
||||||
required[*field.required()];
|
required[*field.required()];
|
||||||
|
|
@ -110,7 +142,7 @@ impl Component for ConfigForm {
|
||||||
type="number"
|
type="number"
|
||||||
id=(field.name())
|
id=(field.name())
|
||||||
name=(field.name())
|
name=(field.name())
|
||||||
value=(&pf.raw_val)
|
value=(&pf.num_val)
|
||||||
min=(lo)
|
min=(lo)
|
||||||
required[*field.required()];
|
required[*field.required()];
|
||||||
} @else if let Some(hi) = max {
|
} @else if let Some(hi) = max {
|
||||||
|
|
@ -118,7 +150,7 @@ impl Component for ConfigForm {
|
||||||
type="number"
|
type="number"
|
||||||
id=(field.name())
|
id=(field.name())
|
||||||
name=(field.name())
|
name=(field.name())
|
||||||
value=(&pf.raw_val)
|
value=(&pf.num_val)
|
||||||
max=(hi)
|
max=(hi)
|
||||||
required[*field.required()];
|
required[*field.required()];
|
||||||
} @else {
|
} @else {
|
||||||
|
|
@ -126,7 +158,7 @@ impl Component for ConfigForm {
|
||||||
type="number"
|
type="number"
|
||||||
id=(field.name())
|
id=(field.name())
|
||||||
name=(field.name())
|
name=(field.name())
|
||||||
value=(&pf.raw_val)
|
value=(&pf.num_val)
|
||||||
required[*field.required()];
|
required[*field.required()];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -146,22 +178,22 @@ impl Component for ConfigForm {
|
||||||
{
|
{
|
||||||
@for (val, label) in options {
|
@for (val, label) in options {
|
||||||
@if &pf.raw_val == val {
|
@if &pf.raw_val == val {
|
||||||
option value=(val) selected { (label.using(cx)) }
|
option value=(val) selected { (label) }
|
||||||
} @else {
|
} @else {
|
||||||
option value=(val) { (label.using(cx)) }
|
option value=(val) { (label) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@if !field.help_text().is_none() {
|
@if let Some(help) = field.help_text() {
|
||||||
small class="admin-form-help" { (field.help_text().using(cx)) }
|
small class="admin-form-help" { (help) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
div class="admin-form-actions" {
|
div class="admin-form-actions" {
|
||||||
button class="admin-btn admin-btn-primary" type="submit" {
|
button class="admin-btn admin-btn-primary" type="submit" {
|
||||||
(Lc::t("config-save-label", &LOCALES_ADMIN).using(cx))
|
(&save_label)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -180,10 +212,17 @@ impl ConfigForm {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Establece la ruta a la que se envía el formulario, o `None` para enviarlo a la de la
|
pub fn with_action_path(mut self, v: impl Into<Option<Route>>) -> Self {
|
||||||
/// página.
|
if let Some(v) = v.into() {
|
||||||
pub fn with_action_path(mut self, path: impl Into<Option<Route>>) -> Self {
|
self.action_path = Some(v);
|
||||||
self.action_path = path.into();
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[builder_skip]
|
||||||
|
pub(crate) fn with_saved(mut self, saved: bool, error: bool) -> Self {
|
||||||
|
self.saved = saved;
|
||||||
|
self.error = error;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,128 +3,212 @@ use std::collections::HashMap;
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
use crate::LOCALES_ADMIN;
|
use crate::LOCALES_ADMIN;
|
||||||
use crate::action::config_forms;
|
use crate::component::{AdminFrame, ConfigForm};
|
||||||
use crate::component::ConfigForm;
|
use crate::registry::{self, AdminPageKind, AdminSection};
|
||||||
use crate::settings::{self, SettingFieldType, SettingsSchema};
|
use crate::settings;
|
||||||
|
|
||||||
// **< Config form >********************************************************************************
|
// **< Dashboard >**********************************************************************************
|
||||||
|
|
||||||
// Página del registro y esquema de la página de ajustes de la petición.
|
/// GET /admin - Dashboard de administración: lista todas las secciones disponibles.
|
||||||
fn config_form_page(
|
///
|
||||||
request: &HttpRequest,
|
/// Devuelve [`ErrorPage::AccessDenied`] si el usuario actual no tiene acceso a ninguna página.
|
||||||
) -> Result<(&'static AdminPage, &'static SettingsSchema), ErrorPage> {
|
pub async fn dashboard(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
let not_found = || ErrorPage::NotFound(Some(request.clone()));
|
let cx = Context::new(request.clone());
|
||||||
let path = strip_admin_path(request.path()).ok_or_else(not_found)?;
|
let sections = registry::global().ordered_sections();
|
||||||
let page = AdminRegistry::global().page(path).ok_or_else(not_found)?;
|
|
||||||
let schema = config_forms().get(path).ok_or_else(not_found)?;
|
let title = Lc::t("dashboard-title", &LOCALES_ADMIN);
|
||||||
Ok((page, schema))
|
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<Markup, ErrorPage> {
|
||||||
|
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<Container> {
|
||||||
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< Config form - GET >**************************************************************************
|
// **< Config form - GET >**************************************************************************
|
||||||
|
|
||||||
// GET de una página de ajustes: el formulario con los valores guardados.
|
/// GET de una página [`AdminPageKind::ConfigForm`].
|
||||||
|
///
|
||||||
|
/// Lee el schema del registro y renderiza el formulario con los valores actuales.
|
||||||
pub async fn config_form_get(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
pub async fn config_form_get(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
let (page, schema) = config_form_page(&request)?;
|
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;
|
||||||
|
|
||||||
Page::admin(request)
|
Page::admin(request)
|
||||||
.with_title(page.title().clone())
|
.with_title(title.clone())
|
||||||
.with_child(ConfigForm::with_schema(schema.clone()))
|
.with_child(
|
||||||
|
AdminFrame::new()
|
||||||
|
.with_title(title)
|
||||||
|
.with_child(Html::with(move |_| content.clone())),
|
||||||
|
)
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< Config form - POST >*************************************************************************
|
// **< Config form - POST >*************************************************************************
|
||||||
|
|
||||||
// POST de una página de ajustes: guarda los valores enviados y vuelve a mostrar el formulario con
|
/// POST de una página [`AdminPageKind::ConfigForm`].
|
||||||
// un mensaje. Si falta algún campo obligatorio no guarda ninguno.
|
///
|
||||||
|
/// Valida y persiste los valores en `settings`, luego redirige al GET con
|
||||||
|
/// estado `saved=true`.
|
||||||
pub async fn config_form_post(
|
pub async fn config_form_post(
|
||||||
request: HttpRequest,
|
request: HttpRequest,
|
||||||
web::Form(data): web::Form<HashMap<String, String>>,
|
web::Form(data): web::Form<HashMap<String, String>>,
|
||||||
) -> Result<Markup, ErrorPage> {
|
) -> Result<Markup, ErrorPage> {
|
||||||
let (page, schema) = config_form_page(&request)?;
|
let path = request.path().to_owned();
|
||||||
let mut admin = Page::admin(request).with_title(page.title().clone());
|
let reg = registry::global();
|
||||||
|
let page = reg
|
||||||
|
.pages()
|
||||||
|
.get(&path)
|
||||||
|
.ok_or_else(|| ErrorPage::NotFound(Some(request.clone())))?;
|
||||||
|
|
||||||
let (level, message) = match submitted_values(schema, &data) {
|
let AdminPageKind::ConfigForm(ref schema) = page.kind else {
|
||||||
None => (MessageLevel::Error, "config-required"),
|
return Err(ErrorPage::NotFound(Some(request.clone())));
|
||||||
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));
|
|
||||||
|
|
||||||
admin
|
require_permission(&request, page.permission)?;
|
||||||
.with_child(ConfigForm::with_schema(schema.clone()))
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
settings::set::<String>(&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())),
|
||||||
|
)
|
||||||
.render()
|
.render()
|
||||||
.await
|
.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<String, String>,
|
|
||||||
) -> Option<Vec<(String, String)>> {
|
|
||||||
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<String, String> {
|
|
||||||
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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
|
|
||||||
<h1>PageTop Admin</h1>
|
<h1>PageTop Admin</h1>
|
||||||
|
|
||||||
<p>Ajustes guardados en la base de datos para el panel de administración de <strong>PageTop</strong>.</p>
|
<p>Panel de administración extensible para <strong>PageTop</strong>.</p>
|
||||||
|
|
||||||
[](https://docs.rs/pagetop-admin)
|
[](https://docs.rs/pagetop-admin)
|
||||||
[](https://crates.io/crates/pagetop-admin)
|
[](https://crates.io/crates/pagetop-admin)
|
||||||
|
|
@ -12,8 +12,11 @@
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
Añade al panel de administración de PageTop **ajustes que se guardan en la base de datos** y que un
|
Añade a una aplicación PageTop un panel de administración en `/admin` que cada extensión amplía con
|
||||||
administrador cambia desde el propio panel, con la aplicación en marcha.
|
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.
|
||||||
|
|
||||||
## Sobre PageTop
|
## Sobre PageTop
|
||||||
|
|
||||||
|
|
@ -21,36 +24,6 @@ administrador cambia desde el propio panel, con la aplicación en marcha.
|
||||||
clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y
|
clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y
|
||||||
configurables, basadas en HTML, CSS y JavaScript.
|
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
|
## Guía rápida
|
||||||
|
|
||||||
**Añade la dependencia** a tu `Cargo.toml`:
|
**Añade la dependencia** a tu `Cargo.toml`:
|
||||||
|
|
@ -60,15 +33,16 @@ casillas (`"42"`, `"true"`): se leen como `String` y se convierten al usarlos.
|
||||||
pagetop-admin = "..."
|
pagetop-admin = "..."
|
||||||
```
|
```
|
||||||
|
|
||||||
Los ajustes se guardan con `pagetop-seaorm`: la aplicación elige el motor de base de datos con su
|
La configuración se guarda con `pagetop-seaorm`: la aplicación elige el motor de base de datos con
|
||||||
*feature* (`postgres`, `mysql` o `sqlite`) y configura la conexión en la sección `[database]`.
|
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`); si no, sus páginas
|
**Declara la extensión** como dependencia de la tuya (`&pagetop_admin::Admin`) y **añade al panel**
|
||||||
de ajustes no se montan. Después **declara tus páginas de ajustes**, cada una con su permiso:
|
tus secciones, páginas o formularios de configuración:
|
||||||
|
|
||||||
```rust,no_run
|
```rust,no_run
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
use pagetop_admin::prelude::*;
|
use pagetop_admin::prelude::*;
|
||||||
|
use pagetop_admin::settings::{SettingField, SettingsSchema};
|
||||||
|
|
||||||
pub struct MyApp;
|
pub struct MyApp;
|
||||||
|
|
||||||
|
|
@ -79,17 +53,25 @@ impl Extension for MyApp {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
fn actions(&self) -> Vec<ActionBox> {
|
||||||
actions![DeclareConfigForms::new(declare_forms)]
|
actions![
|
||||||
|
DeclareAdminPages::new(declare_pages),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
|
router.route("/admin/config/myapp", web::get(config_handler))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn declare_forms(bag: &mut ConfigFormBag) {
|
fn declare_pages(bag: &mut PageBag) {
|
||||||
bag.add(ConfigFormPage {
|
bag.add(AdminPage {
|
||||||
page: AdminPage::new("config/myapp", "config", Lc::n("My App"), &MyPermission::Config)
|
path: "/admin/config/myapp".to_owned(),
|
||||||
.with_description(Lc::n("Name of the site.")),
|
section: "config".to_owned(),
|
||||||
schema: SettingsSchema::new("myapp").with_field(
|
title: Lc::n("My App"),
|
||||||
SettingField::text("site_name", Lc::n("Site name")).with_required(true),
|
description: Some(Lc::n("Configure My App.")),
|
||||||
),
|
weight: 0,
|
||||||
|
permission: &MyPermission::Config,
|
||||||
|
kind: AdminPageKind::View,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -106,11 +88,30 @@ impl Permission for MyPermission {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Los valores se guardan con la clave `<ámbito>.<campo>`.
|
async fn config_handler(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
async fn site_name() -> String {
|
let schema = SettingsSchema::new("myapp.config")
|
||||||
pagetop_admin::settings::get_or("myapp.site_name", String::new()).await
|
.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
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
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::*;
|
use pagetop::prelude::*;
|
||||||
|
|
@ -118,24 +119,39 @@ use pagetop_seaorm::install_migrations;
|
||||||
|
|
||||||
include_locales!(LOCALES_ADMIN);
|
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 action;
|
||||||
pub mod component;
|
pub mod component;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
pub mod registry;
|
||||||
pub mod settings;
|
pub mod settings;
|
||||||
|
|
||||||
pub(crate) mod entity;
|
pub(crate) mod entity;
|
||||||
pub(crate) mod handlers;
|
pub(crate) mod handlers;
|
||||||
pub(crate) mod migration;
|
pub(crate) mod migration;
|
||||||
|
pub(crate) mod seed;
|
||||||
|
|
||||||
pub use action::{ConfigFormBag, ConfigFormPage, DeclareConfigForms};
|
pub use action::{
|
||||||
pub use component::ConfigForm;
|
ActionBag, DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks,
|
||||||
|
PageBag, SectionBag, TaskBag,
|
||||||
|
};
|
||||||
|
pub use component::{AdminFrame, AdminMenu, ConfigForm};
|
||||||
|
pub use registry::{AdminAction, AdminPage, AdminPageKind, AdminSection, AdminTask};
|
||||||
pub use settings::{SettingField, SettingFieldType, SettingsSchema};
|
pub use settings::{SettingField, SettingFieldType, SettingsSchema};
|
||||||
|
|
||||||
/// Prelude de `pagetop-admin`.
|
/// Prelude de `pagetop-admin`.
|
||||||
pub mod prelude {
|
pub mod prelude {
|
||||||
pub use crate::action::{ConfigFormBag, ConfigFormPage, DeclareConfigForms};
|
pub use crate::action::{
|
||||||
pub use crate::component::ConfigForm;
|
ActionBag, DeclareAdminActions, DeclareAdminPages, DeclareAdminSections, DeclareAdminTasks,
|
||||||
|
PageBag, SectionBag, TaskBag,
|
||||||
|
};
|
||||||
|
pub use crate::component::{AdminFrame, AdminMenu, ConfigForm};
|
||||||
pub use crate::error::AdminError;
|
pub use crate::error::AdminError;
|
||||||
|
pub use crate::registry::{AdminAction, AdminPage, AdminPageKind, AdminSection, AdminTask};
|
||||||
pub use crate::settings::{SettingField, SettingFieldType, SettingsSchema};
|
pub use crate::settings::{SettingField, SettingFieldType, SettingsSchema};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -159,22 +175,42 @@ impl Extension for Admin {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
fn actions(&self) -> Vec<ActionBox> {
|
||||||
actions![pagetop::base::action::admin::DeclareAdminPages::new(
|
actions![action::DeclareAdminSections::new(seed::declare_default_sections).with_weight(-99),]
|
||||||
action::declare_config_form_pages
|
|
||||||
)]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn initialize(&self) -> Result<(), BoxError> {
|
async fn initialize(&self) -> Result<(), BoxError> {
|
||||||
install_migrations!(m20260629_000001_create_settings)?;
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
action::config_forms().keys().fold(routes, |routes, path| {
|
let base = ADMIN_BASE_PATH;
|
||||||
routes.admin_route(
|
let reg = registry::global();
|
||||||
path,
|
|
||||||
web::get(handlers::config_form_get).post(handlers::config_form_post),
|
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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,21 @@
|
||||||
extension_name = PageTop Admin
|
extension_name = PageTop Admin
|
||||||
extension_description = Settings stored in the database for the PageTop administration panel.
|
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
|
||||||
|
|
||||||
# Config form
|
# Config form
|
||||||
config-save-label = Save configuration
|
config-save-label = Save configuration
|
||||||
config-saved-ok = Configuration saved.
|
config-saved-ok = Configuration saved.
|
||||||
config-saved-error = Could not save configuration.
|
config-saved-error = Could not save configuration.
|
||||||
config-required = Fill in the required fields. Nothing was saved.
|
|
||||||
|
# Navigation
|
||||||
|
admin-breadcrumb-home = Administration
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,21 @@
|
||||||
extension_name = PageTop Admin
|
extension_name = PageTop Admin
|
||||||
extension_description = Ajustes guardados en la base de datos para el panel de administración de PageTop.
|
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
|
||||||
|
|
||||||
# Config form
|
# Config form
|
||||||
config-save-label = Guardar configuración
|
config-save-label = Guardar configuración
|
||||||
config-saved-ok = Configuración guardada.
|
config-saved-ok = Configuración guardada.
|
||||||
config-saved-error = No se pudo guardar la configuración.
|
config-saved-error = No se pudo guardar la configuración.
|
||||||
config-required = Rellena los campos obligatorios. No se ha guardado nada.
|
|
||||||
|
# Navigation
|
||||||
|
admin-breadcrumb-home = Administración
|
||||||
|
|
|
||||||
279
extensions/pagetop-admin/src/registry.rs
Normal file
279
extensions/pagetop-admin/src/registry.rs
Normal file
|
|
@ -0,0 +1,279 @@
|
||||||
|
//! 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<Lc>,
|
||||||
|
/// 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<PermissionRef>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<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>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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<AdminRegistry> = 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))
|
||||||
|
}
|
||||||
45
extensions/pagetop-admin/src/seed.rs
Normal file
45
extensions/pagetop-admin/src/seed.rs
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
@ -25,9 +25,32 @@ pub async fn get_or<T: DeserializeOwned>(key: &str, default: T) -> T {
|
||||||
|
|
||||||
/// Escribe un valor en la tabla `settings`.
|
/// Escribe un valor en la tabla `settings`.
|
||||||
///
|
///
|
||||||
/// Si la clave no existe se inserta; si existe, se actualiza. Devuelve el error si no se puede
|
/// Si la clave no existe se inserta; si existe, se actualiza.
|
||||||
/// guardar.
|
pub async fn set<T: Serialize>(key: &str, value: &T, scope: &str, user_id: Option<i32>) {
|
||||||
pub async fn set<T: Serialize>(
|
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<T: DeserializeOwned>(key: &str) -> Result<T, AdminError> {
|
||||||
|
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<T: Serialize>(
|
||||||
key: &str,
|
key: &str,
|
||||||
value: &T,
|
value: &T,
|
||||||
scope: &str,
|
scope: &str,
|
||||||
|
|
@ -59,27 +82,11 @@ pub async fn set<T: Serialize>(
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Elimina una entrada de `settings` por clave. Devuelve el error si no se puede eliminar.
|
async fn delete_async(key: &str) -> Result<(), AdminError> {
|
||||||
pub async fn delete(key: &str) -> Result<(), AdminError> {
|
|
||||||
Entity::delete_by_id(key).exec(dbconn()).await?;
|
Entity::delete_by_id(key).exec(dbconn()).await?;
|
||||||
Ok(())
|
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<T: DeserializeOwned>(key: &str) -> Result<T, AdminError> {
|
|
||||||
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<Vec<(String, String)>, AdminError> {
|
async fn list_scope_async(scope: &str) -> Result<Vec<(String, String)>, AdminError> {
|
||||||
let rows = Entity::find()
|
let rows = Entity::find()
|
||||||
.filter(Column::Scope.eq(scope))
|
.filter(Column::Scope.eq(scope))
|
||||||
|
|
@ -100,7 +107,7 @@ pub enum SettingFieldType {
|
||||||
/// Casilla de verificación (booleano).
|
/// Casilla de verificación (booleano).
|
||||||
Boolean,
|
Boolean,
|
||||||
/// Lista de opciones `(valor, etiqueta)`.
|
/// Lista de opciones `(valor, etiqueta)`.
|
||||||
Select { options: Vec<(String, Lc)> },
|
Select { options: Vec<(String, String)> },
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Definición de un campo dentro de un [`SettingsSchema`].
|
/// Definición de un campo dentro de un [`SettingsSchema`].
|
||||||
|
|
@ -109,66 +116,70 @@ pub struct SettingField {
|
||||||
/// Devuelve el nombre del campo (clave dentro del scope, p. ej. `"site_name"`).
|
/// Devuelve el nombre del campo (clave dentro del scope, p. ej. `"site_name"`).
|
||||||
name: String,
|
name: String,
|
||||||
/// Devuelve la etiqueta visible en el formulario.
|
/// Devuelve la etiqueta visible en el formulario.
|
||||||
label: Lc,
|
label: String,
|
||||||
/// Devuelve el tipo de campo.
|
/// Devuelve el tipo de campo.
|
||||||
field_type: SettingFieldType,
|
field_type: SettingFieldType,
|
||||||
/// Devuelve si el campo es obligatorio.
|
/// Devuelve si el campo es obligatorio.
|
||||||
required: bool,
|
required: bool,
|
||||||
/// Devuelve el texto de ayuda bajo el campo, o [`Lc::none()`] si no tiene.
|
/// Devuelve el texto de ayuda opcional bajo el campo.
|
||||||
help_text: Lc,
|
help_text: Option<String>,
|
||||||
/// Devuelve el valor por defecto, como texto, igual que guarda el formulario los valores.
|
/// Devuelve el valor por defecto como cadena JSON.
|
||||||
default_value: Option<String>,
|
default_value: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[builder_impl]
|
#[builder_impl]
|
||||||
impl SettingField {
|
impl SettingField {
|
||||||
/// Crea un campo de texto con nombre y etiqueta.
|
/// Crea un campo de texto con nombre y etiqueta.
|
||||||
pub fn text(name: impl Into<String>, label: Lc) -> Self {
|
pub fn text(name: impl Into<String>, label: impl Into<String>) -> Self {
|
||||||
SettingField {
|
SettingField {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
label,
|
label: label.into(),
|
||||||
field_type: SettingFieldType::Text { max_length: None },
|
field_type: SettingFieldType::Text { max_length: None },
|
||||||
required: false,
|
required: false,
|
||||||
help_text: Lc::none(),
|
help_text: None,
|
||||||
default_value: None,
|
default_value: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Crea un campo numérico con nombre y etiqueta.
|
/// Crea un campo numérico con nombre y etiqueta.
|
||||||
pub fn number(name: impl Into<String>, label: Lc) -> Self {
|
pub fn number(name: impl Into<String>, label: impl Into<String>) -> Self {
|
||||||
SettingField {
|
SettingField {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
label,
|
label: label.into(),
|
||||||
field_type: SettingFieldType::Number {
|
field_type: SettingFieldType::Number {
|
||||||
min: None,
|
min: None,
|
||||||
max: None,
|
max: None,
|
||||||
},
|
},
|
||||||
required: false,
|
required: false,
|
||||||
help_text: Lc::none(),
|
help_text: None,
|
||||||
default_value: None,
|
default_value: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Crea un campo booleano con nombre y etiqueta.
|
/// Crea un campo booleano con nombre y etiqueta.
|
||||||
pub fn boolean(name: impl Into<String>, label: Lc) -> Self {
|
pub fn boolean(name: impl Into<String>, label: impl Into<String>) -> Self {
|
||||||
SettingField {
|
SettingField {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
label,
|
label: label.into(),
|
||||||
field_type: SettingFieldType::Boolean,
|
field_type: SettingFieldType::Boolean,
|
||||||
required: false,
|
required: false,
|
||||||
help_text: Lc::none(),
|
help_text: None,
|
||||||
default_value: None,
|
default_value: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Crea un campo de selección con nombre, etiqueta y opciones.
|
/// Crea un campo de selección con nombre, etiqueta y opciones.
|
||||||
pub fn select(name: impl Into<String>, label: Lc, options: Vec<(String, Lc)>) -> Self {
|
pub fn select(
|
||||||
|
name: impl Into<String>,
|
||||||
|
label: impl Into<String>,
|
||||||
|
options: Vec<(String, String)>,
|
||||||
|
) -> Self {
|
||||||
SettingField {
|
SettingField {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
label,
|
label: label.into(),
|
||||||
field_type: SettingFieldType::Select { options },
|
field_type: SettingFieldType::Select { options },
|
||||||
required: false,
|
required: false,
|
||||||
help_text: Lc::none(),
|
help_text: None,
|
||||||
default_value: None,
|
default_value: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -180,20 +191,14 @@ impl SettingField {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Añade texto de ayuda bajo el campo.
|
/// Añade texto de ayuda bajo el campo.
|
||||||
pub fn with_help(mut self, text: Lc) -> Self {
|
pub fn with_help(mut self, text: impl Into<String>) -> Self {
|
||||||
self.help_text = text;
|
self.help_text = Some(text.into());
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Establece el valor por defecto, el que muestra el formulario mientras no se guarde otro.
|
/// Establece el valor por defecto (como valor JSON serializado).
|
||||||
///
|
|
||||||
/// 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<T: Serialize>(mut self, value: &T) -> Self {
|
pub fn with_default<T: Serialize>(mut self, value: &T) -> Self {
|
||||||
self.default_value = serde_json::to_value(value).ok().map(|value| match value {
|
self.default_value = serde_json::to_string(value).ok();
|
||||||
serde_json::Value::String(text) => text,
|
|
||||||
other => other.to_string(),
|
|
||||||
});
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
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());
|
|
||||||
}
|
|
||||||
|
|
@ -104,9 +104,9 @@ impl Extension for Aliner {
|
||||||
Some(&Self)
|
Some(&Self)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
fn configure_static_files(&self, router: Router) -> Router {
|
||||||
serve_static_files!(files, [aliner] => "/aliner");
|
serve_static_files!(router, [aliner] => "/aliner");
|
||||||
files
|
router
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -77,8 +77,10 @@ async fn homepage(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
|
|
||||||
Bootsier maqueta las dos plantillas de PageTop (`CoreTemplates`) con las mismas regiones (cabecera,
|
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
|
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()` y añade el panel de
|
se activa creando la página con `Page::admin()` en lugar de `Page::new()`. Ambas se maquetan igual
|
||||||
administración (ver más abajo).
|
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).
|
||||||
|
|
||||||
```rust,no_run
|
```rust,no_run
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
@ -93,12 +95,12 @@ async fn about(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Panel de administración
|
## Menú de administración
|
||||||
|
|
||||||
En la plantilla `Admin`, Bootsier sigue la composición del núcleo: tras la cabecera pinta la
|
`pagetop-admin` (si está presente en la aplicación) registra su propio menú de secciones y
|
||||||
navegación del panel (`AdminMenu`) y, en lugar del contenido, el marco de la página (`AdminFrame`:
|
páginas en `CoreRegions::Aside`, autolimitado a páginas con la plantilla `Admin` -- no requiere
|
||||||
migas, título, botones y pestañas). Los dos se construyen con componentes del núcleo
|
ningún registro por parte de Bootsier. Se construye con `Navbar`/`Nav`/`Dropdown`, los mismos
|
||||||
(`Navbar`/`Nav`/`Dropdown`, `Breadcrumb`), que Bootsier ya pinta con su aspecto.
|
componentes disponibles para cualquier página de la aplicación.
|
||||||
|
|
||||||
## Selector de modo de color
|
## Selector de modo de color
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -248,51 +248,3 @@ fieldset > legend {
|
||||||
border-start-start-radius: 0;
|
border-start-start-radius: 0;
|
||||||
border-end-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;
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -78,8 +78,10 @@ async fn homepage(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
|
|
||||||
Bootsier maqueta las dos plantillas de PageTop (`CoreTemplates`) con las mismas regiones (cabecera,
|
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
|
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()` y añade el panel de
|
se activa creando la página con `Page::admin()` en lugar de `Page::new()`. Ambas se maquetan igual
|
||||||
administración (ver más abajo).
|
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).
|
||||||
|
|
||||||
```rust,no_run
|
```rust,no_run
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
@ -94,12 +96,12 @@ async fn about(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Panel de administración
|
## Menú de administración
|
||||||
|
|
||||||
En la plantilla `Admin`, Bootsier sigue la composición del núcleo: tras la cabecera pinta la
|
`pagetop-admin` (si está presente en la aplicación) registra su propio menú de secciones y
|
||||||
navegación del panel (`AdminMenu`) y, en lugar del contenido, el marco de la página (`AdminFrame`:
|
páginas en `CoreRegions::Aside`, autolimitado a páginas con la plantilla `Admin` -- no requiere
|
||||||
migas, título, botones y pestañas). Los dos se construyen con componentes del núcleo
|
ningún registro por parte de Bootsier. Se construye con `Navbar`/`Nav`/`Dropdown`, los mismos
|
||||||
(`Navbar`/`Nav`/`Dropdown`, `Breadcrumb`), que Bootsier ya pinta con su aspecto.
|
componentes disponibles para cualquier página de la aplicación.
|
||||||
|
|
||||||
## Selector de modo de color
|
## Selector de modo de color
|
||||||
|
|
||||||
|
|
@ -154,7 +156,7 @@ impl Extension for Bootsier {
|
||||||
Some(&config::SETTINGS)
|
Some(&config::SETTINGS)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
fn configure_static_files(&self, router: Router) -> Router {
|
||||||
let base = &config::SETTINGS.static_dir;
|
let base = &config::SETTINGS.static_dir;
|
||||||
let subdir = |s: &str| {
|
let subdir = |s: &str| {
|
||||||
if base.is_empty() {
|
if base.is_empty() {
|
||||||
|
|
@ -163,10 +165,10 @@ impl Extension for Bootsier {
|
||||||
format!("{base}/{s}")
|
format!("{base}/{s}")
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
serve_static_files!(files, [subdir("css"), bootsier_css] => "/bootsier/css");
|
serve_static_files!(router, [subdir("css"), bootsier_css] => "/bootsier/css");
|
||||||
serve_static_files!(files, [subdir("js"), bootsier_js] => "/bootsier/js");
|
serve_static_files!(router, [subdir("js"), bootsier_js] => "/bootsier/js");
|
||||||
serve_static_files!(files, [subdir("fonts"), bootsier_fonts] => "/bootsier/fonts");
|
serve_static_files!(router, [subdir("fonts"), bootsier_fonts] => "/bootsier/fonts");
|
||||||
files
|
router
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -232,8 +234,12 @@ impl Theme for Bootsier {
|
||||||
// Etiquetas de los botones del modal de confirmación que sustituye al `confirm()` nativo
|
// 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
|
// 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 `<body>`.
|
// acceso al `Context` para resolverlas antes de escribirlas en el `<body>`.
|
||||||
let confirm_ok = Lc::l("confirm_ok").lookup(page).unwrap_or_default();
|
let confirm_ok = Lc::l("confirm_ok")
|
||||||
let confirm_cancel = Lc::l("confirm_cancel").lookup(page).unwrap_or_default();
|
.lookup(page.context())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let confirm_cancel = Lc::l("confirm_cancel")
|
||||||
|
.lookup(page.context())
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
// Las URLs de las fuentes deben coincidir exactamente con las declaradas en @font-face de
|
// 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.
|
// _bootsier-custom.scss; cualquier discrepancia hace que el navegador descargue dos veces.
|
||||||
|
|
|
||||||
|
|
@ -13,8 +13,10 @@
|
||||||
//!
|
//!
|
||||||
//! Bootsier maqueta las dos plantillas de PageTop ([`CoreTemplates`]) con la misma cabecera,
|
//! 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
|
//! 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()`] y añade el panel de
|
//! activa creando la página con [`Page::admin()`] en lugar de [`Page::new()`]. Ambas se maquetan
|
||||||
//! administración (ver más abajo).
|
//! 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`).
|
||||||
//!
|
//!
|
||||||
//! ```rust,no_run
|
//! ```rust,no_run
|
||||||
//! use pagetop::prelude::*;
|
//! use pagetop::prelude::*;
|
||||||
|
|
@ -33,12 +35,13 @@
|
||||||
//! [`Page::admin()`]: pagetop::response::Page::admin
|
//! [`Page::admin()`]: pagetop::response::Page::admin
|
||||||
//! [`Page::new()`]: pagetop::response::Page::new
|
//! [`Page::new()`]: pagetop::response::Page::new
|
||||||
//!
|
//!
|
||||||
//! # Panel de administración
|
//! # Menú de administración
|
||||||
//!
|
//!
|
||||||
//! En la plantilla `Admin`, Bootsier sigue la composición del núcleo: tras la cabecera pinta la
|
//! `pagetop-admin` (si está presente en la aplicación) registra su propio menú de secciones y
|
||||||
//! navegación del panel ([`AdminMenu`]) y, en lugar del contenido, el marco de la página
|
//! páginas en [`CoreRegions::Aside`], autolimitado a
|
||||||
//! ([`AdminFrame`]: migas, título, botones y pestañas). Los dos se construyen con componentes del
|
//! páginas con la plantilla `Admin` -- no requiere ningún registro por parte de Bootsier. Se
|
||||||
//! núcleo ([`Navbar`]/[`Nav`]/[`Dropdown`], [`Breadcrumb`]), que Bootsier ya pinta con su aspecto.
|
//! construye con [`Navbar`]/[`Nav`]/[`Dropdown`], los mismos
|
||||||
|
//! componentes disponibles para cualquier página de la aplicación.
|
||||||
//!
|
//!
|
||||||
//! # Selector de modo de color
|
//! # Selector de modo de color
|
||||||
//!
|
//!
|
||||||
|
|
|
||||||
|
|
@ -8,23 +8,28 @@ use crate::theme::bs;
|
||||||
// `CoreTemplates`, dejando que el resto de la cadena de temas (o el propio componente) resuelva el
|
// `CoreTemplates`, dejando que el resto de la cadena de temas (o el propio componente) resuelva el
|
||||||
// renderizado por defecto.
|
// renderizado por defecto.
|
||||||
//
|
//
|
||||||
// `CoreTemplates::Admin` sigue la composición del núcleo: tras la cabecera, la navegación del
|
// `CoreTemplates::Admin` delega hoy en el mismo maquetado que `Standard`: la diferencia entre
|
||||||
// panel (`AdminMenu`) y, en lugar del contenido, el marco de la página (`AdminFrame`), que
|
// página "normal" y de administración no vive en la plantilla, sino en qué se registra en cada
|
||||||
// contiene la región `Content`.
|
// 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.
|
||||||
pub(crate) async fn render(
|
pub(crate) async fn render(
|
||||||
component: &layout::Template,
|
component: &layout::Template,
|
||||||
cx: &mut Context,
|
cx: &mut Context,
|
||||||
) -> Option<Result<Markup, ComponentError>> {
|
) -> Option<Result<Markup, ComponentError>> {
|
||||||
match component.template().downcast_ref::<CoreTemplates>()? {
|
match component.template().downcast_ref::<CoreTemplates>()? {
|
||||||
CoreTemplates::Standard => Some(Ok(render_standard(cx).await)),
|
CoreTemplates::Standard => Some(Ok(render_standard(cx).await)),
|
||||||
CoreTemplates::Admin => Some(Ok(render_admin(cx).await)),
|
CoreTemplates::Admin => Some(Ok(render_standard(cx).await)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// `CoreRegions::Header`, `CoreRegions::Aside`, `CoreRegions::Content` y `CoreRegions::Footer`
|
// `CoreRegions::Header`, `CoreRegions::Aside`, `CoreRegions::Content` y `CoreRegions::Footer`
|
||||||
// envueltos en un contenedor de ancho configurable.
|
// envueltos en un contenedor de ancho configurable.
|
||||||
async fn render_standard(cx: &mut Context) -> Markup {
|
async fn render_standard(cx: &mut Context) -> Markup {
|
||||||
wrapper()
|
bs::Container::new()
|
||||||
|
.with_prop(PropsOp::add_classes("container-wrapper"))
|
||||||
|
.with_width(bs::container::Width::FluidMax(config::SETTINGS.max_width))
|
||||||
.with_child(layout::Region::header())
|
.with_child(layout::Region::header())
|
||||||
.with_child(layout::Region::aside())
|
.with_child(layout::Region::aside())
|
||||||
.with_child(layout::Region::default())
|
.with_child(layout::Region::default())
|
||||||
|
|
@ -32,23 +37,3 @@ async fn render_standard(cx: &mut Context) -> Markup {
|
||||||
.render(cx)
|
.render(cx)
|
||||||
.await
|
.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))
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -391,11 +391,11 @@ impl Extension for Cron {
|
||||||
scheduler::shutdown().await;
|
scheduler::shutdown().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
if config::SETTINGS.mode != config::CronMode::External {
|
if config::SETTINGS.mode != config::CronMode::External {
|
||||||
return routes;
|
return router;
|
||||||
}
|
}
|
||||||
routes.public_route(TRIGGER_PATH, web::post(trigger_post).fallback(not_found))
|
router.route(TRIGGER_PATH, web::post(trigger_post).fallback(not_found))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -70,7 +70,7 @@ use crate::hx;
|
||||||
/// [`SortLink`]: pagetop::base::component::table::SortLink
|
/// [`SortLink`]: pagetop::base::component::table::SortLink
|
||||||
/// [`SortLink::with_prop()`]: pagetop::base::component::table::SortLink::with_prop
|
/// [`SortLink::with_prop()`]: pagetop::base::component::table::SortLink::with_prop
|
||||||
/// [`SortLink::with_dir()`]: pagetop::base::component::table::SortLink::with_dir
|
/// [`SortLink::with_dir()`]: pagetop::base::component::table::SortLink::with_dir
|
||||||
/// [`Context::route()`]: pagetop::core::component::Contextual::route
|
/// [`Context::route()`]: pagetop::core::component::Context::route
|
||||||
pub fn sort_link(
|
pub fn sort_link(
|
||||||
href: impl Into<RoutePath>,
|
href: impl Into<RoutePath>,
|
||||||
target: impl AsRef<str>,
|
target: impl AsRef<str>,
|
||||||
|
|
|
||||||
|
|
@ -147,9 +147,9 @@ impl Extension for Htmx {
|
||||||
actions![action::page::BeforeRenderBody::new(add_htmx_script)]
|
actions![action::page::BeforeRenderBody::new(add_htmx_script)]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
fn configure_static_files(&self, router: Router) -> Router {
|
||||||
serve_static_files!(files, [htmx] => "/htmx");
|
serve_static_files!(router, [htmx] => "/htmx");
|
||||||
files
|
router
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -141,7 +141,7 @@ impl HtmxResponse {
|
||||||
/// objetivo definido por el destino. Para personalizar `target`, `swap`, `select` o `values`,
|
/// objetivo definido por el destino. Para personalizar `target`, `swap`, `select` o `values`,
|
||||||
/// usa [`location_json()`](Self::location_json).
|
/// usa [`location_json()`](Self::location_json).
|
||||||
///
|
///
|
||||||
/// Usa [`Context::route()`](pagetop::core::component::Contextual::route) en lugar de un literal
|
/// Usa [`Context::route()`](pagetop::core::component::Context::route) en lugar de un literal
|
||||||
/// para que la URL preserve el parámetro `lang` cuando corresponda:
|
/// para que la URL preserve el parámetro `lang` cuando corresponda:
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```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
|
/// 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.
|
/// aunque esté habilitado por el atributo `hx-push-url` del elemento.
|
||||||
///
|
///
|
||||||
/// Usa [`Context::route()`](pagetop::core::component::Contextual::route) en lugar de un literal
|
/// Usa [`Context::route()`](pagetop::core::component::Context::route) en lugar de un literal
|
||||||
/// para que la URL preserve el parámetro `lang` cuando corresponda:
|
/// para que la URL preserve el parámetro `lang` cuando corresponda:
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
|
|
@ -231,7 +231,7 @@ impl HtmxResponse {
|
||||||
/// Reemplaza la URL actual en el historial sin añadir una nueva entrada.
|
/// Reemplaza la URL actual en el historial sin añadir una nueva entrada.
|
||||||
///
|
///
|
||||||
/// Usar `"false"` para desactivar el reemplazo. Usa
|
/// Usar `"false"` para desactivar el reemplazo. Usa
|
||||||
/// [`Context::route()`](pagetop::core::component::Contextual::route) en lugar de un literal para
|
/// [`Context::route()`](pagetop::core::component::Context::route) en lugar de un literal para
|
||||||
/// que la URL preserve el parámetro `lang` cuando corresponda.
|
/// que la URL preserve el parámetro `lang` cuando corresponda.
|
||||||
pub fn replace_url(self, url: impl Into<RoutePath>) -> Self {
|
pub fn replace_url(self, url: impl Into<RoutePath>) -> Self {
|
||||||
self.set_header(hx::response::REPLACE_URL.as_bytes(), url.into().to_string())
|
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
|
/// A diferencia de [`location()`](Self::location), esta redirección recarga la página por
|
||||||
/// completo, como un `window.location.href = url` en JavaScript.
|
/// completo, como un `window.location.href = url` en JavaScript.
|
||||||
///
|
///
|
||||||
/// Usa [`Context::route()`](pagetop::core::component::Contextual::route) en lugar de un literal
|
/// Usa [`Context::route()`](pagetop::core::component::Context::route) en lugar de un literal
|
||||||
/// para que la URL preserve el parámetro `lang` cuando corresponda:
|
/// para que la URL preserve el parámetro `lang` cuando corresponda:
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
|
|
|
||||||
|
|
@ -9,8 +9,8 @@ impl Extension for TestApp {
|
||||||
vec![&Htmx]
|
vec![&Htmx]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/page", web::get(render_page))
|
router.route("/page", web::get(render_page))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -5,8 +5,8 @@ struct TestApp;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for TestApp {
|
impl Extension for TestApp {
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/echo", web::get(echo_request))
|
router.route("/echo", web::get(echo_request))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -172,16 +172,6 @@ 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
|
cabeceras, HTML con el diseño común, texto plano y adjuntos, sin enviar nada. Ver el módulo
|
||||||
`preview`.
|
`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
|
## Texto plano automático
|
||||||
|
|
||||||
Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques
|
Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques
|
||||||
|
|
|
||||||
|
|
@ -1,207 +0,0 @@
|
||||||
//! 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<Markup, ErrorPage> {
|
|
||||||
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<TestMailForm>,
|
|
||||||
) -> Result<Response, ErrorPage> {
|
|
||||||
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<Lc> {
|
|
||||||
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<String>| 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)),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -170,16 +170,6 @@ 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:
|
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`].
|
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
|
## Texto plano automático
|
||||||
|
|
||||||
Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques
|
Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques
|
||||||
|
|
@ -283,9 +273,6 @@ pub mod outbox;
|
||||||
pub mod preview;
|
pub mod preview;
|
||||||
pub use preview::{DeclareMailPreviews, MailPreviews};
|
pub use preview::{DeclareMailPreviews, MailPreviews};
|
||||||
|
|
||||||
mod admin;
|
|
||||||
pub use admin::MailPermission;
|
|
||||||
|
|
||||||
mod text;
|
mod text;
|
||||||
|
|
||||||
mod transport;
|
mod transport;
|
||||||
|
|
@ -320,21 +307,9 @@ impl Extension for Mail {
|
||||||
vec![&pagetop_seaorm::SeaORM, &pagetop_cron::Cron]
|
vec![&pagetop_seaorm::SeaORM, &pagetop_cron::Cron]
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "queue"))]
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
actions![
|
|
||||||
action::auth::DeclarePermissions::new(admin::declare_permissions),
|
|
||||||
action::admin::DeclareAdminPages::new(admin::declare_pages),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "queue")]
|
#[cfg(feature = "queue")]
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
fn actions(&self) -> Vec<ActionBox> {
|
||||||
actions![
|
actions![pagetop_cron::DeclareCronJobs::new(queue::declare_jobs)]
|
||||||
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> {
|
fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
||||||
|
|
@ -350,16 +325,13 @@ impl Extension for Mail {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
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 {
|
if !config::SETTINGS.previews {
|
||||||
return routes;
|
return router;
|
||||||
}
|
}
|
||||||
routes
|
router
|
||||||
.public_route(preview::PREVIEW_PATH, web::get(preview::list_get))
|
.route(preview::PREVIEW_PATH, web::get(preview::list_get))
|
||||||
.public_route(
|
.route(
|
||||||
&util::join!(preview::PREVIEW_PATH, "/{key}"),
|
&util::join!(preview::PREVIEW_PATH, "/{key}"),
|
||||||
web::get(preview::preview_get),
|
web::get(preview::preview_get),
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -20,37 +20,3 @@ preview_attachments = Attachments
|
||||||
preview_html = HTML
|
preview_html = HTML
|
||||||
preview_text = Plain text
|
preview_text = Plain text
|
||||||
preview_none = None
|
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
|
|
||||||
|
|
|
||||||
|
|
@ -20,37 +20,3 @@ preview_attachments = Adjuntos
|
||||||
preview_html = HTML
|
preview_html = HTML
|
||||||
preview_text = Texto plano
|
preview_text = Texto plano
|
||||||
preview_none = Ninguno
|
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
|
|
||||||
|
|
|
||||||
|
|
@ -1,124 +0,0 @@
|
||||||
// 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<ExtensionRef> {
|
|
||||||
vec![&pagetop_mail::Mail]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
|
||||||
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());
|
|
||||||
}
|
|
||||||
|
|
@ -20,6 +20,7 @@ demo-data = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
pagetop.workspace = true
|
pagetop.workspace = true
|
||||||
|
pagetop-admin.workspace = true
|
||||||
pagetop-seaorm.workspace = true
|
pagetop-seaorm.workspace = true
|
||||||
pagetop-htmx.workspace = true
|
pagetop-htmx.workspace = true
|
||||||
pagetop-mail.workspace = true
|
pagetop-mail.workspace = true
|
||||||
|
|
|
||||||
|
|
@ -14,8 +14,8 @@
|
||||||
Añade cuentas de usuario a una aplicación PageTop: registro, inicio de sesión con sesiones en la
|
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
|
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
|
control de acceso con roles y permisos. Incluye las páginas de administración de usuarios, roles y
|
||||||
permisos en el panel de administración del núcleo, hechas sólo con componentes del núcleo para que
|
permisos sobre `pagetop-admin`, hechas sólo con componentes del núcleo para que funcionen con
|
||||||
funcionen con cualquier tema.
|
cualquier tema.
|
||||||
|
|
||||||
## Sobre PageTop
|
## Sobre PageTop
|
||||||
|
|
||||||
|
|
@ -47,11 +47,9 @@ admin_email = "admin@example.com"
|
||||||
# Sin 'admin_password', se genera una aleatoria y se muestra una sola vez al crearlo.
|
# Sin 'admin_password', se genera una aleatoria y se muestra una sola vez al crearlo.
|
||||||
```
|
```
|
||||||
|
|
||||||
**Protege tus rutas** con su acceso (`Access`): PageTop lo comprueba antes de llegar al *handler*
|
**Comprueba los permisos** en tus *handlers*. El usuario actual se inyecta automáticamente en el
|
||||||
con los permisos que concede esta extensión, y a un usuario anónimo sin acceso le ofrece el inicio
|
contexto de cada `Page` al crearla con `Page::new()`, y las funciones del núcleo, como
|
||||||
de sesión. Dentro del *handler*, el usuario actual está en el contexto de cada `Page` al crearla
|
`has_permission()`, lo consultan:
|
||||||
con `Page::new()`, y funciones del núcleo como `has_permission()` lo consultan para las
|
|
||||||
comprobaciones más concretas:
|
|
||||||
|
|
||||||
```rust,no_run
|
```rust,no_run
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
@ -78,16 +76,15 @@ impl Extension for MyApp {
|
||||||
vec![&pagetop_user::User]
|
vec![&pagetop_user::User]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.route(
|
router.route("/dashboard", web::get(dashboard))
|
||||||
"/dashboard",
|
|
||||||
Access::Permission(&MyPermission::SeeDashboard),
|
|
||||||
web::get(dashboard),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn dashboard(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
async fn dashboard(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
|
if !has_permission(&request, &MyPermission::SeeDashboard) {
|
||||||
|
return Err(ErrorPage::NotFound(Some(request)));
|
||||||
|
}
|
||||||
Page::new(request)
|
Page::new(request)
|
||||||
.with_child(Html::with(|_| html! { h1 { "Panel" } }))
|
.with_child(Html::with(|_| html! { h1 { "Panel" } }))
|
||||||
.render().await
|
.render().await
|
||||||
|
|
|
||||||
|
|
@ -58,8 +58,6 @@ impl PermissionSet {
|
||||||
/// Se almacena en las extensiones de la petición HTTP durante la fase de middleware y se accede
|
/// 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
|
/// desde los handlers o desde handlers de [`CheckPermission`] mediante
|
||||||
/// [`HttpRequest::extension::<Account>()`](pagetop::web::HttpRequest::extension).
|
/// [`HttpRequest::extension::<Account>()`](pagetop::web::HttpRequest::extension).
|
||||||
///
|
|
||||||
/// [`CheckPermission`]: pagetop::base::action::auth::CheckPermission
|
|
||||||
#[derive(Clone, Debug, Getters)]
|
#[derive(Clone, Debug, Getters)]
|
||||||
pub struct Account {
|
pub struct Account {
|
||||||
/// Identificador del usuario.
|
/// Identificador del usuario.
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
//! Menú de cuenta (iniciar y cerrar sesión).
|
//! Menú de cuenta (iniciar y cerrar sesión).
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_admin::registry::can_access_admin;
|
||||||
use pagetop_htmx::prelude::*;
|
use pagetop_htmx::prelude::*;
|
||||||
|
|
||||||
use crate::config::SETTINGS;
|
use crate::config::SETTINGS;
|
||||||
|
|
@ -48,7 +49,7 @@ pub fn account_menu(cx: &Context) -> Nav {
|
||||||
if can_access_admin(cx) {
|
if can_access_admin(cx) {
|
||||||
menu = menu.with_item(dropdown::Item::link(
|
menu = menu.with_item(dropdown::Item::link(
|
||||||
Lc::t("menu-admin", &LOCALES_USER),
|
Lc::t("menu-admin", &LOCALES_USER),
|
||||||
cx.route(admin_path("")),
|
cx.route(pagetop_admin::ADMIN_BASE_PATH),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
nav.with_item(nav::Item::dropdown(
|
nav.with_item(nav::Item::dropdown(
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,7 @@ impl Component for RoleForm {
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
let action = match self.mode() {
|
let action = match self.mode() {
|
||||||
RoleFormMode::New => util::join!(ADMIN_ROLES_PATH.as_str(), "/new"),
|
RoleFormMode::New => util::join!(ADMIN_ROLES_PATH, "/new"),
|
||||||
RoleFormMode::Edit => role_path(self.role_id().copied().unwrap_or_default(), "edit"),
|
RoleFormMode::Edit => role_path(self.role_id().copied().unwrap_or_default(), "edit"),
|
||||||
};
|
};
|
||||||
let action = self.waypoint().append_to(cx.route(action));
|
let action = self.waypoint().append_to(cx.route(action));
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,7 @@ impl Component for RoleTable {
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
let pager = Pager::new()
|
let pager = Pager::new()
|
||||||
.with_base_path(ADMIN_ROLES_PATH.as_str())
|
.with_base_path(ADMIN_ROLES_PATH)
|
||||||
.with_extra_query("sort", self.sort().as_str())
|
.with_extra_query("sort", self.sort().as_str())
|
||||||
.with_extra_query("dir", *self.dir())
|
.with_extra_query("dir", *self.dir())
|
||||||
.with_current_page(self.page())
|
.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.as_str(), "/new")));
|
let new_href = waypoint.append_to(cx.route(util::join!(ADMIN_ROLES_PATH, "/new")));
|
||||||
|
|
||||||
Ok(html! {
|
Ok(html! {
|
||||||
div (self.props().unpack(cx)) {
|
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
|
// 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.
|
// construye con `cx.route()` para que preserve el parámetro `lang` cuando corresponda.
|
||||||
fn list_href(&self, cx: &Context) -> String {
|
fn list_href(&self, cx: &Context) -> String {
|
||||||
cx.route(ADMIN_ROLES_PATH.as_str())
|
cx.route(ADMIN_ROLES_PATH)
|
||||||
.alter_param("sort", self.sort().as_str())
|
.alter_param("sort", self.sort().as_str())
|
||||||
.alter_param("dir", *self.dir())
|
.alter_param("dir", *self.dir())
|
||||||
.alter_param("page", self.page().to_string())
|
.alter_param("page", self.page().to_string())
|
||||||
|
|
@ -200,7 +200,7 @@ impl RoleTable {
|
||||||
let is_active = *self.sort() == field;
|
let is_active = *self.sort() == field;
|
||||||
let active = is_active.then_some(*self.dir());
|
let active = is_active.then_some(*self.dir());
|
||||||
let next_dir = SortDir::next_for(active);
|
let next_dir = SortDir::next_for(active);
|
||||||
let mut route = cx.route(ADMIN_ROLES_PATH.as_str());
|
let mut route = cx.route(ADMIN_ROLES_PATH);
|
||||||
route
|
route
|
||||||
.alter_param("sort", field.as_str())
|
.alter_param("sort", field.as_str())
|
||||||
.alter_param("dir", next_dir);
|
.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
|
// 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
|
// editar/borrar sólo si el rol no está bloqueado por el sistema. Devuelve un componente `Html` para que el marcado se genere cuando
|
||||||
// que el marcado se genere cuando `Table` renderice la celda, no al construir la fila.
|
// `Table` renderice la celda, no al construir la fila.
|
||||||
async fn actions_cell(
|
async fn actions_cell(
|
||||||
role: &RoleListItem,
|
role: &RoleListItem,
|
||||||
waypoint: &Waypoint,
|
waypoint: &Waypoint,
|
||||||
|
|
|
||||||
|
|
@ -54,7 +54,7 @@ impl Component for UserForm {
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
let action = match self.mode() {
|
let action = match self.mode() {
|
||||||
UserFormMode::New => util::join!(ADMIN_USERS_PATH.as_str(), "/new"),
|
UserFormMode::New => util::join!(ADMIN_USERS_PATH, "/new"),
|
||||||
UserFormMode::Edit => user_path(self.user_id().copied().unwrap_or_default(), "edit"),
|
UserFormMode::Edit => user_path(self.user_id().copied().unwrap_or_default(), "edit"),
|
||||||
UserFormMode::Profile => PROFILE_EDIT_PATH.into(),
|
UserFormMode::Profile => PROFILE_EDIT_PATH.into(),
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -39,7 +39,7 @@ impl Component for UserTable {
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
let pager = Pager::new()
|
let pager = Pager::new()
|
||||||
.with_base_path(ADMIN_USERS_PATH.as_str())
|
.with_base_path(ADMIN_USERS_PATH)
|
||||||
.with_extra_query("q", self.query().cloned().unwrap_or_default())
|
.with_extra_query("q", self.query().cloned().unwrap_or_default())
|
||||||
.with_extra_query("sort", self.sort().as_str())
|
.with_extra_query("sort", self.sort().as_str())
|
||||||
.with_extra_query("dir", *self.dir())
|
.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.as_str(), "/new")));
|
let new_href = waypoint.append_to(cx.route(util::join!(ADMIN_USERS_PATH, "/new")));
|
||||||
|
|
||||||
Ok(html! {
|
Ok(html! {
|
||||||
div (self.props().unpack(cx)) {
|
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.
|
// `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.
|
// Se construye con `cx.route()` para que preserve el parámetro `lang` cuando corresponda.
|
||||||
fn list_href(&self, cx: &Context) -> String {
|
fn list_href(&self, cx: &Context) -> String {
|
||||||
let mut route = cx.route(ADMIN_USERS_PATH.as_str());
|
let mut route = cx.route(ADMIN_USERS_PATH);
|
||||||
if let Some(q) = self.query().filter(|q| !q.is_empty()) {
|
if let Some(q) = self.query().filter(|q| !q.is_empty()) {
|
||||||
route.alter_param("q", q);
|
route.alter_param("q", q);
|
||||||
}
|
}
|
||||||
|
|
@ -167,7 +167,7 @@ impl UserTable {
|
||||||
let active = is_active.then_some(*self.dir());
|
let active = is_active.then_some(*self.dir());
|
||||||
let next_dir = SortDir::next_for(active);
|
let next_dir = SortDir::next_for(active);
|
||||||
|
|
||||||
let mut route = cx.route(ADMIN_USERS_PATH.as_str());
|
let mut route = cx.route(ADMIN_USERS_PATH);
|
||||||
if let Some(q) = self.query().filter(|q| !q.is_empty()) {
|
if let Some(q) = self.query().filter(|q| !q.is_empty()) {
|
||||||
route.alter_param("q", q);
|
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
|
// 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
|
// 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
|
// 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, como en las demás celdas.
|
// `Table`); el resto del marcado se difiere al `Html` que se devuelve, igual que el resto de celdas.
|
||||||
async fn roles_cell(user: &UserListItem, cx: &mut Context) -> Html {
|
async fn roles_cell(user: &UserListItem, cx: &mut Context) -> Html {
|
||||||
let mut badges = Vec::with_capacity(user.roles.len().max(1));
|
let mut badges = Vec::with_capacity(user.roles.len().max(1));
|
||||||
if user.is_admin {
|
if user.is_admin {
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,6 @@
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
use pagetop_htmx::prelude::*;
|
|
||||||
|
|
||||||
use crate::account::{Account, UserStatus};
|
use crate::account::{Account, UserStatus};
|
||||||
use crate::auth;
|
use crate::auth;
|
||||||
|
|
@ -40,33 +39,6 @@ fn login_redirect(request: HttpRequest, next: &'static str) -> Response {
|
||||||
Redirect::see_other(waypoint.append_to(cx.route(LOGIN_PATH))).into_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<Response> {
|
|
||||||
let is_htmx = request.is_htmx();
|
|
||||||
let waypoint = if is_htmx {
|
|
||||||
Waypoint::new(
|
|
||||||
request
|
|
||||||
.hx_current_url()
|
|
||||||
.and_then(|url| url.parse::<web::http::Uri>().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 >********************************************************************************
|
// **< profile_get >********************************************************************************
|
||||||
|
|
||||||
/// GET /user - Perfil del usuario autenticado. Redirige al formulario de inicio de sesión si no hay
|
/// GET /user - Perfil del usuario autenticado. Redirige al formulario de inicio de sesión si no hay
|
||||||
|
|
@ -88,8 +60,8 @@ pub(crate) async fn profile_get(request: HttpRequest) -> Response {
|
||||||
let can_change_password = has_permission(&request, &UserPermission::ChangeOwnPassword);
|
let can_change_password = has_permission(&request, &UserPermission::ChangeOwnPassword);
|
||||||
|
|
||||||
let mut page = Page::new(request);
|
let mut page = Page::new(request);
|
||||||
let details_block = user_details(&user, page.context_mut()).await;
|
let details_block = user_details(&user, page.context()).await;
|
||||||
let roles_block = profile_roles(&roles, page.context_mut()).await;
|
let roles_block = profile_roles(&roles, page.context()).await;
|
||||||
let actions = profile_actions(can_edit, can_change_password, page.context());
|
let actions = profile_actions(can_edit, can_change_password, page.context());
|
||||||
|
|
||||||
page.with_title(Lc::t("title-profile", &LOCALES_USER))
|
page.with_title(Lc::t("title-profile", &LOCALES_USER))
|
||||||
|
|
@ -187,12 +159,9 @@ pub(crate) async fn public_profile_get(
|
||||||
request: HttpRequest,
|
request: HttpRequest,
|
||||||
web::Path(id): web::Path<i32>,
|
web::Path(id): web::Path<i32>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
// El permiso se comprueba antes de buscar al usuario para no revelar qué ids existen. Sin él, la
|
// El permiso se comprueba antes de buscar al usuario para no revelar qué ids existen.
|
||||||
// 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) {
|
||||||
if current_user_id(&request) != Some(id)
|
require_permission(&request, &UserPermission::ViewProfiles)?;
|
||||||
&& !has_permission(&request, &UserPermission::ViewProfiles)
|
|
||||||
{
|
|
||||||
return Ok(deny_access(request));
|
|
||||||
}
|
}
|
||||||
let Ok(user) = user_admin::find_user(id).await else {
|
let Ok(user) = user_admin::find_user(id).await else {
|
||||||
return Err(ErrorPage::NotFound(Some(request)));
|
return Err(ErrorPage::NotFound(Some(request)));
|
||||||
|
|
@ -207,7 +176,7 @@ pub(crate) async fn public_profile_get(
|
||||||
Some(name) => name.to_owned(),
|
Some(name) => name.to_owned(),
|
||||||
None => user.username.clone(),
|
None => user.username.clone(),
|
||||||
};
|
};
|
||||||
let page = Page::new(request);
|
let mut page = Page::new(request);
|
||||||
let details = public_profile_details(&user, page.context());
|
let details = public_profile_details(&user, page.context());
|
||||||
|
|
||||||
Ok(page
|
Ok(page
|
||||||
|
|
@ -259,6 +228,7 @@ pub(crate) async fn profile_edit_get(request: HttpRequest) -> Result<Response, E
|
||||||
let Some(id) = current_user_id(&request) else {
|
let Some(id) = current_user_id(&request) else {
|
||||||
return Ok(login_redirect(request, PROFILE_EDIT_PATH));
|
return Ok(login_redirect(request, PROFILE_EDIT_PATH));
|
||||||
};
|
};
|
||||||
|
require_permission(&request, &UserPermission::EditOwnProfile)?;
|
||||||
let Ok(user) = user_admin::find_user(id).await else {
|
let Ok(user) = user_admin::find_user(id).await else {
|
||||||
return Err(ErrorPage::NotFound(Some(request)));
|
return Err(ErrorPage::NotFound(Some(request)));
|
||||||
};
|
};
|
||||||
|
|
@ -300,6 +270,7 @@ pub(crate) async fn profile_edit_post(
|
||||||
let Some(id) = current_user_id(&request) else {
|
let Some(id) = current_user_id(&request) else {
|
||||||
return Ok(login_redirect(request, PROFILE_EDIT_PATH));
|
return Ok(login_redirect(request, PROFILE_EDIT_PATH));
|
||||||
};
|
};
|
||||||
|
require_permission(&request, &UserPermission::EditOwnProfile)?;
|
||||||
let Ok(user) = user_admin::find_user(id).await else {
|
let Ok(user) = user_admin::find_user(id).await else {
|
||||||
return Err(ErrorPage::NotFound(Some(request)));
|
return Err(ErrorPage::NotFound(Some(request)));
|
||||||
};
|
};
|
||||||
|
|
@ -361,6 +332,7 @@ pub(crate) async fn password_get(request: HttpRequest) -> Result<Response, Error
|
||||||
if current_user_id(&request).is_none() {
|
if current_user_id(&request).is_none() {
|
||||||
return Ok(login_redirect(request, PROFILE_PASSWORD_PATH));
|
return Ok(login_redirect(request, PROFILE_PASSWORD_PATH));
|
||||||
}
|
}
|
||||||
|
require_permission(&request, &UserPermission::ChangeOwnPassword)?;
|
||||||
let title = Lc::t("title-profile-password", &LOCALES_USER);
|
let title = Lc::t("title-profile-password", &LOCALES_USER);
|
||||||
Ok(render_profile_page(request, title, ChangePasswordForm::new()).await)
|
Ok(render_profile_page(request, title, ChangePasswordForm::new()).await)
|
||||||
}
|
}
|
||||||
|
|
@ -381,6 +353,7 @@ pub(crate) async fn password_post(
|
||||||
let Some(id) = current_user_id(&request) else {
|
let Some(id) = current_user_id(&request) else {
|
||||||
return Ok(login_redirect(request, PROFILE_PASSWORD_PATH));
|
return Ok(login_redirect(request, PROFILE_PASSWORD_PATH));
|
||||||
};
|
};
|
||||||
|
require_permission(&request, &UserPermission::ChangeOwnPassword)?;
|
||||||
|
|
||||||
let sid = session::extract_sid(Some(request.headers()));
|
let sid = session::extract_sid(Some(request.headers()));
|
||||||
let result = match password::passwords_match(&form.password, &form.confirm_password) {
|
let result = match password::passwords_match(&form.password, &form.confirm_password) {
|
||||||
|
|
@ -413,6 +386,7 @@ pub(crate) async fn email_get(request: HttpRequest) -> Result<Response, ErrorPag
|
||||||
let Some(id) = current_user_id(&request) else {
|
let Some(id) = current_user_id(&request) else {
|
||||||
return Ok(login_redirect(request, EMAIL_PATH));
|
return Ok(login_redirect(request, EMAIL_PATH));
|
||||||
};
|
};
|
||||||
|
require_permission(&request, &UserPermission::EditOwnProfile)?;
|
||||||
let Ok(user) = user_admin::find_user(id).await else {
|
let Ok(user) = user_admin::find_user(id).await else {
|
||||||
return Err(ErrorPage::NotFound(Some(request)));
|
return Err(ErrorPage::NotFound(Some(request)));
|
||||||
};
|
};
|
||||||
|
|
@ -437,6 +411,7 @@ pub(crate) async fn email_post(
|
||||||
let Some(id) = current_user_id(&request) else {
|
let Some(id) = current_user_id(&request) else {
|
||||||
return Ok(login_redirect(request, EMAIL_PATH));
|
return Ok(login_redirect(request, EMAIL_PATH));
|
||||||
};
|
};
|
||||||
|
require_permission(&request, &UserPermission::EditOwnProfile)?;
|
||||||
|
|
||||||
let result = if throttle::allow(&request) {
|
let result = if throttle::allow(&request) {
|
||||||
auth::request_email_change(id, &form.current_password, &form.email).await
|
auth::request_email_change(id, &form.current_password, &form.email).await
|
||||||
|
|
@ -535,8 +510,11 @@ async fn render_profile_page(
|
||||||
title: Lc,
|
title: Lc,
|
||||||
form: impl Component + 'static,
|
form: impl Component + 'static,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let page = Page::new(request);
|
let mut page = Page::new(request);
|
||||||
let cancel = Button::anchor(Lc::t("btn-cancel", &LOCALES_USER), page.route(PROFILE_PATH));
|
let cancel = Button::anchor(
|
||||||
|
Lc::t("btn-cancel", &LOCALES_USER),
|
||||||
|
page.context().route(PROFILE_PATH),
|
||||||
|
);
|
||||||
page.with_title(title.clone())
|
page.with_title(title.clone())
|
||||||
.with_child(
|
.with_child(
|
||||||
Block::new()
|
Block::new()
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,26 @@
|
||||||
//! Handlers HTTP para el mantenimiento de usuarios, roles y permisos.
|
//! Handlers HTTP para el mantenimiento de usuarios, roles y permisos.
|
||||||
//!
|
//!
|
||||||
//! Las páginas de usuarios, roles y permisos se declaran en el panel de administración (ver
|
//! Las páginas de usuarios, roles y permisos se registran en el portal de `pagetop-admin` (ver
|
||||||
//! `declare_admin_pages()`), y sus rutas exigen el permiso de su página, que PageTop comprueba
|
//! `declare_admin_pages()`). Cada handler comprueba el permiso correspondiente con
|
||||||
//! antes de llegar al handler. Los handlers sólo comprueban los permisos más concretos (bloquear
|
//! [`require_permission()`](pagetop::auth::require_permission) antes de construir la página.
|
||||||
//! cuentas, asignar permisos a un rol).
|
|
||||||
|
|
||||||
pub(crate) mod permissions;
|
pub(crate) mod permissions;
|
||||||
pub(crate) mod roles;
|
pub(crate) mod roles;
|
||||||
pub(crate) mod users;
|
pub(crate) mod users;
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_admin::component::AdminFrame;
|
||||||
|
|
||||||
use crate::LOCALES_USER;
|
use crate::LOCALES_USER;
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
use crate::service::role_admin::ROLE_MACHINE_NAME_MAX_CHARS;
|
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
|
// 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.
|
// los errores de autenticación existentes como los nuevos de administración.
|
||||||
pub(crate) fn map_auth_error(err: &AuthError) -> Lc {
|
pub(crate) fn map_auth_error(err: &AuthError) -> Lc {
|
||||||
|
|
|
||||||
|
|
@ -7,16 +7,20 @@
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
use crate::LOCALES_USER;
|
use crate::LOCALES_USER;
|
||||||
|
use crate::handlers::admin::frame;
|
||||||
|
use crate::permission::{self, UserPermission};
|
||||||
|
|
||||||
/// GET /admin/user/permissions - Catálogo de permisos agrupado.
|
/// GET /admin/user/permissions - Catálogo de permisos agrupado.
|
||||||
pub(crate) async fn list_get(request: HttpRequest) -> Result<Response, ErrorPage> {
|
pub(crate) async fn list_get(request: HttpRequest) -> Result<Response, ErrorPage> {
|
||||||
let page = Page::admin(request);
|
require_permission(&request, &UserPermission::AdminPermissions)?;
|
||||||
|
|
||||||
let registry = PermissionRegistry::global();
|
let mut page = Page::admin(request);
|
||||||
let groups = registry.groups_sorted(page.context());
|
|
||||||
let mut page = page.with_title(Lc::t("title-admin-permissions", &LOCALES_USER));
|
|
||||||
|
|
||||||
for (group, group_label) in groups {
|
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()) {
|
||||||
let mut table = Table::new().with_prop(PropsOp::add_classes("user-admin-table"));
|
let mut table = Table::new().with_prop(PropsOp::add_classes("user-admin-table"));
|
||||||
for permission in registry.by_group(group) {
|
for permission in registry.by_group(group) {
|
||||||
table = table.with_row(
|
table = table.with_row(
|
||||||
|
|
@ -25,12 +29,17 @@ pub(crate) async fn list_get(request: HttpRequest) -> Result<Response, ErrorPage
|
||||||
.with_cell(permission.key().as_ref()),
|
.with_cell(permission.key().as_ref()),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
page = page.with_child(
|
content = content.with_child(
|
||||||
Block::new()
|
Block::new()
|
||||||
.with_title(group_label.clone())
|
.with_title(group_label.clone())
|
||||||
.with_child(table),
|
.with_child(table),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(page.render().await.into_response())
|
Ok(page
|
||||||
|
.with_title(title)
|
||||||
|
.with_child(content)
|
||||||
|
.render()
|
||||||
|
.await
|
||||||
|
.into_response())
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,8 +12,8 @@ use crate::component::admin::{
|
||||||
};
|
};
|
||||||
use crate::config::SETTINGS;
|
use crate::config::SETTINGS;
|
||||||
use crate::entity::role;
|
use crate::entity::role;
|
||||||
use crate::handlers::admin::{back_link, map_auth_error};
|
use crate::handlers::admin::{back_link, frame, map_auth_error};
|
||||||
use crate::permission::UserPermission;
|
use crate::permission::{self, UserPermission};
|
||||||
use crate::role_path;
|
use crate::role_path;
|
||||||
use crate::service::role_admin::{self, RolePageParams, RoleSortField};
|
use crate::service::role_admin::{self, RolePageParams, RoleSortField};
|
||||||
|
|
||||||
|
|
@ -34,6 +34,8 @@ pub(crate) async fn list_get(
|
||||||
request: HttpRequest,
|
request: HttpRequest,
|
||||||
web::Query(query): web::Query<RolesQuery>,
|
web::Query(query): web::Query<RolesQuery>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminRoles)?;
|
||||||
|
|
||||||
let params = RolePageParams {
|
let params = RolePageParams {
|
||||||
sort: RoleSortField::from_query(query.sort.as_deref()),
|
sort: RoleSortField::from_query(query.sort.as_deref()),
|
||||||
dir: SortDir::from_query(query.dir.as_deref()),
|
dir: SortDir::from_query(query.dir.as_deref()),
|
||||||
|
|
@ -60,8 +62,8 @@ pub(crate) async fn list_get(
|
||||||
} else {
|
} else {
|
||||||
let title = Lc::t("title-admin-roles", &LOCALES_USER);
|
let title = Lc::t("title-admin-roles", &LOCALES_USER);
|
||||||
Ok(Page::admin(request)
|
Ok(Page::admin(request)
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(table)
|
.with_child(frame(title).with_child(table))
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
@ -75,17 +77,21 @@ pub(crate) async fn new_get(
|
||||||
request: HttpRequest,
|
request: HttpRequest,
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
let page = Page::admin(request);
|
require_permission(&request, &UserPermission::AdminRoles)?;
|
||||||
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
|
let mut page = Page::admin(request);
|
||||||
|
let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH));
|
||||||
let title = Lc::t("title-admin-role-new", &LOCALES_USER);
|
let title = Lc::t("title-admin-role-new", &LOCALES_USER);
|
||||||
Ok(page
|
Ok(page
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(
|
.with_child(
|
||||||
RoleForm::new()
|
frame(title)
|
||||||
.with_mode(RoleFormMode::New)
|
.with_child(
|
||||||
.with_waypoint(waypoint),
|
RoleForm::new()
|
||||||
|
.with_mode(RoleFormMode::New)
|
||||||
|
.with_waypoint(waypoint),
|
||||||
|
)
|
||||||
|
.with_child(back_link(back_href)),
|
||||||
)
|
)
|
||||||
.with_child(back_link(back_href))
|
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
@ -107,6 +113,8 @@ pub(crate) async fn new_post(
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
web::Form(form): web::Form<NewRoleFormData>,
|
web::Form(form): web::Form<NewRoleFormData>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminRoles)?;
|
||||||
|
|
||||||
let weight: i32 = form.weight.trim().parse().unwrap_or(0);
|
let weight: i32 = form.weight.trim().parse().unwrap_or(0);
|
||||||
|
|
||||||
let result = role_admin::create_role(role_admin::NewRoleData {
|
let result = role_admin::create_role(role_admin::NewRoleData {
|
||||||
|
|
@ -120,12 +128,12 @@ pub(crate) async fn new_post(
|
||||||
match result {
|
match result {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
let cx = Context::admin(request);
|
let cx = Context::admin(request);
|
||||||
let target = waypoint.or(cx.route(ADMIN_ROLES_PATH.as_str()));
|
let target = waypoint.or(cx.route(ADMIN_ROLES_PATH));
|
||||||
Ok(Redirect::see_other(target).into_response())
|
Ok(Redirect::see_other(target).into_response())
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let page = Page::admin(request);
|
let mut page = Page::admin(request);
|
||||||
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
|
let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH));
|
||||||
let form_component = RoleForm::new()
|
let form_component = RoleForm::new()
|
||||||
.with_mode(RoleFormMode::New)
|
.with_mode(RoleFormMode::New)
|
||||||
.with_machine_name(form.machine_name)
|
.with_machine_name(form.machine_name)
|
||||||
|
|
@ -136,9 +144,12 @@ pub(crate) async fn new_post(
|
||||||
.with_waypoint(waypoint);
|
.with_waypoint(waypoint);
|
||||||
let title = Lc::t("title-admin-role-new", &LOCALES_USER);
|
let title = Lc::t("title-admin-role-new", &LOCALES_USER);
|
||||||
Ok(page
|
Ok(page
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(form_component)
|
.with_child(
|
||||||
.with_child(back_link(back_href))
|
frame(title)
|
||||||
|
.with_child(form_component)
|
||||||
|
.with_child(back_link(back_href)),
|
||||||
|
)
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
@ -154,6 +165,8 @@ pub(crate) async fn edit_get(
|
||||||
web::Path(id): web::Path<i32>,
|
web::Path(id): web::Path<i32>,
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminRoles)?;
|
||||||
|
|
||||||
let role = match role_admin::find_role(id).await {
|
let role = match role_admin::find_role(id).await {
|
||||||
Ok(role) => role,
|
Ok(role) => role,
|
||||||
Err(_) => return Err(ErrorPage::NotFound(Some(request))),
|
Err(_) => return Err(ErrorPage::NotFound(Some(request))),
|
||||||
|
|
@ -162,23 +175,26 @@ pub(crate) async fn edit_get(
|
||||||
return Err(ErrorPage::AccessDenied(Some(request)));
|
return Err(ErrorPage::AccessDenied(Some(request)));
|
||||||
}
|
}
|
||||||
|
|
||||||
let page = Page::admin(request);
|
let mut page = Page::admin(request);
|
||||||
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
|
let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH));
|
||||||
|
|
||||||
let title = Lc::t("title-admin-role-edit", &LOCALES_USER);
|
let title = Lc::t("title-admin-role-edit", &LOCALES_USER);
|
||||||
Ok(page
|
Ok(page
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(
|
.with_child(
|
||||||
RoleForm::new()
|
frame(title)
|
||||||
.with_mode(RoleFormMode::Edit)
|
.with_child(
|
||||||
.with_role_id(Some(id))
|
RoleForm::new()
|
||||||
.with_machine_name(role.machine_name)
|
.with_mode(RoleFormMode::Edit)
|
||||||
.with_label(role.label)
|
.with_role_id(Some(id))
|
||||||
.with_description(role.description.unwrap_or_default())
|
.with_machine_name(role.machine_name)
|
||||||
.with_weight(role.weight)
|
.with_label(role.label)
|
||||||
.with_waypoint(waypoint),
|
.with_description(role.description.unwrap_or_default())
|
||||||
|
.with_weight(role.weight)
|
||||||
|
.with_waypoint(waypoint),
|
||||||
|
)
|
||||||
|
.with_child(back_link(back_href)),
|
||||||
)
|
)
|
||||||
.with_child(back_link(back_href))
|
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
@ -200,6 +216,8 @@ pub(crate) async fn edit_post(
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
web::Form(form): web::Form<EditRoleFormData>,
|
web::Form(form): web::Form<EditRoleFormData>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminRoles)?;
|
||||||
|
|
||||||
let weight: i32 = form.weight.trim().parse().unwrap_or(0);
|
let weight: i32 = form.weight.trim().parse().unwrap_or(0);
|
||||||
|
|
||||||
let result = role_admin::update_role(
|
let result = role_admin::update_role(
|
||||||
|
|
@ -215,7 +233,7 @@ pub(crate) async fn edit_post(
|
||||||
match result {
|
match result {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
let cx = Context::admin(request);
|
let cx = Context::admin(request);
|
||||||
let target = waypoint.or(cx.route(ADMIN_ROLES_PATH.as_str()));
|
let target = waypoint.or(cx.route(ADMIN_ROLES_PATH));
|
||||||
Ok(Redirect::see_other(target).into_response())
|
Ok(Redirect::see_other(target).into_response())
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
|
|
@ -223,8 +241,8 @@ pub(crate) async fn edit_post(
|
||||||
.await
|
.await
|
||||||
.map(|role| role.machine_name)
|
.map(|role| role.machine_name)
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let page = Page::admin(request);
|
let mut page = Page::admin(request);
|
||||||
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
|
let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH));
|
||||||
let form_component = RoleForm::new()
|
let form_component = RoleForm::new()
|
||||||
.with_mode(RoleFormMode::Edit)
|
.with_mode(RoleFormMode::Edit)
|
||||||
.with_role_id(Some(id))
|
.with_role_id(Some(id))
|
||||||
|
|
@ -236,9 +254,12 @@ pub(crate) async fn edit_post(
|
||||||
.with_waypoint(waypoint);
|
.with_waypoint(waypoint);
|
||||||
let title = Lc::t("title-admin-role-edit", &LOCALES_USER);
|
let title = Lc::t("title-admin-role-edit", &LOCALES_USER);
|
||||||
Ok(page
|
Ok(page
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(form_component)
|
.with_child(
|
||||||
.with_child(back_link(back_href))
|
frame(title)
|
||||||
|
.with_child(form_component)
|
||||||
|
.with_child(back_link(back_href)),
|
||||||
|
)
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
@ -255,6 +276,8 @@ pub(crate) async fn view_get(
|
||||||
web::Path(id): web::Path<i32>,
|
web::Path(id): web::Path<i32>,
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminRoles)?;
|
||||||
|
|
||||||
let role = match role_admin::find_role(id).await {
|
let role = match role_admin::find_role(id).await {
|
||||||
Ok(role) => role,
|
Ok(role) => role,
|
||||||
Err(_) => return Err(ErrorPage::NotFound(Some(request))),
|
Err(_) => return Err(ErrorPage::NotFound(Some(request))),
|
||||||
|
|
@ -266,17 +289,19 @@ pub(crate) async fn view_get(
|
||||||
let mut page = Page::admin(request);
|
let mut page = Page::admin(request);
|
||||||
|
|
||||||
let groups = build_permission_groups(&selected, page.context());
|
let groups = build_permission_groups(&selected, page.context());
|
||||||
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
|
let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH));
|
||||||
let details_block = role_view_details(&role, page.context_mut()).await;
|
let details_block = role_view_details(&role, page.context()).await;
|
||||||
|
|
||||||
let title = Lc::t("title-admin-role-view", &LOCALES_USER);
|
let title = Lc::t("title-admin-role-view", &LOCALES_USER);
|
||||||
let mut page = page.with_title(title).with_child(details_block);
|
let mut content = frame(title.clone()).with_child(details_block);
|
||||||
for group_block in role_view_permissions(&groups) {
|
for group_block in role_view_permissions(&groups) {
|
||||||
page = page.with_child(group_block);
|
content = content.with_child(group_block);
|
||||||
}
|
}
|
||||||
|
content = content.with_child(back_link(back_href));
|
||||||
|
|
||||||
Ok(page
|
Ok(page
|
||||||
.with_child(back_link(back_href))
|
.with_title(title)
|
||||||
|
.with_child(content)
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
@ -364,6 +389,8 @@ pub(crate) async fn delete_post(
|
||||||
web::Path(id): web::Path<i32>,
|
web::Path(id): web::Path<i32>,
|
||||||
web::Query(query): web::Query<RolesQuery>,
|
web::Query(query): web::Query<RolesQuery>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminRoles)?;
|
||||||
|
|
||||||
let result = role_admin::delete_role(id).await;
|
let result = role_admin::delete_role(id).await;
|
||||||
|
|
||||||
if request.is_htmx() {
|
if request.is_htmx() {
|
||||||
|
|
@ -392,7 +419,7 @@ pub(crate) async fn delete_post(
|
||||||
match result {
|
match result {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
let target = cx
|
let target = cx
|
||||||
.route(ADMIN_ROLES_PATH.as_str())
|
.route(ADMIN_ROLES_PATH)
|
||||||
.alter_param(
|
.alter_param(
|
||||||
"sort",
|
"sort",
|
||||||
RoleSortField::from_query(query.sort.as_deref()).as_str(),
|
RoleSortField::from_query(query.sort.as_deref()).as_str(),
|
||||||
|
|
@ -421,6 +448,8 @@ pub(crate) async fn delete_confirm_get(
|
||||||
web::Path(id): web::Path<i32>,
|
web::Path(id): web::Path<i32>,
|
||||||
web::Query(query): web::Query<RolesQuery>,
|
web::Query(query): web::Query<RolesQuery>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminRoles)?;
|
||||||
|
|
||||||
let mut cx = Context::admin(request);
|
let mut cx = Context::admin(request);
|
||||||
let delete_href = cx
|
let delete_href = cx
|
||||||
.route(role_path(id, "delete"))
|
.route(role_path(id, "delete"))
|
||||||
|
|
@ -444,7 +473,7 @@ pub(crate) async fn delete_confirm_get(
|
||||||
// **< permissions_get / permissions_post >*********************************************************
|
// **< permissions_get / permissions_post >*********************************************************
|
||||||
|
|
||||||
fn build_permission_groups(selected: &[String], cx: &Context) -> PermissionGroups {
|
fn build_permission_groups(selected: &[String], cx: &Context) -> PermissionGroups {
|
||||||
let registry = PermissionRegistry::global();
|
let registry = permission::registry();
|
||||||
registry
|
registry
|
||||||
.groups_sorted(cx)
|
.groups_sorted(cx)
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
|
@ -469,6 +498,7 @@ pub(crate) async fn permissions_get(
|
||||||
web::Path(id): web::Path<i32>,
|
web::Path(id): web::Path<i32>,
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminRoles)?;
|
||||||
require_permission(&request, &UserPermission::AdminPermissions)?;
|
require_permission(&request, &UserPermission::AdminPermissions)?;
|
||||||
|
|
||||||
if role_admin::find_role(id).await.is_err() {
|
if role_admin::find_role(id).await.is_err() {
|
||||||
|
|
@ -478,21 +508,24 @@ pub(crate) async fn permissions_get(
|
||||||
Ok(keys) => keys,
|
Ok(keys) => keys,
|
||||||
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
|
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
|
||||||
};
|
};
|
||||||
let page = Page::admin(request);
|
let mut page = Page::admin(request);
|
||||||
|
|
||||||
let groups = build_permission_groups(&selected, page.context());
|
let groups = build_permission_groups(&selected, page.context());
|
||||||
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
|
let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH));
|
||||||
|
|
||||||
let title = Lc::t("title-admin-role-permissions", &LOCALES_USER);
|
let title = Lc::t("title-admin-role-permissions", &LOCALES_USER);
|
||||||
Ok(page
|
Ok(page
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(
|
.with_child(
|
||||||
RolePermissionsForm::new()
|
frame(title)
|
||||||
.with_role_id(id)
|
.with_child(
|
||||||
.with_groups(groups)
|
RolePermissionsForm::new()
|
||||||
.with_waypoint(waypoint),
|
.with_role_id(id)
|
||||||
|
.with_groups(groups)
|
||||||
|
.with_waypoint(waypoint),
|
||||||
|
)
|
||||||
|
.with_child(back_link(back_href)),
|
||||||
)
|
)
|
||||||
.with_child(back_link(back_href))
|
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
@ -514,6 +547,7 @@ pub(crate) async fn permissions_post(
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
raw: web::RawForm,
|
raw: web::RawForm,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminRoles)?;
|
||||||
require_permission(&request, &UserPermission::AdminPermissions)?;
|
require_permission(&request, &UserPermission::AdminPermissions)?;
|
||||||
|
|
||||||
let Ok(form) = serde_qs::from_bytes::<RolePermissionsFormData>(&raw.0) else {
|
let Ok(form) = serde_qs::from_bytes::<RolePermissionsFormData>(&raw.0) else {
|
||||||
|
|
@ -523,14 +557,14 @@ pub(crate) async fn permissions_post(
|
||||||
match role_admin::set_role_permissions(id, &form.permission_keys).await {
|
match role_admin::set_role_permissions(id, &form.permission_keys).await {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
let cx = Context::admin(request);
|
let cx = Context::admin(request);
|
||||||
let target = waypoint.or(cx.route(ADMIN_ROLES_PATH.as_str()));
|
let target = waypoint.or(cx.route(ADMIN_ROLES_PATH));
|
||||||
Ok(Redirect::see_other(target).into_response())
|
Ok(Redirect::see_other(target).into_response())
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let page = Page::admin(request);
|
let mut page = Page::admin(request);
|
||||||
|
|
||||||
let groups = build_permission_groups(&form.permission_keys, page.context());
|
let groups = build_permission_groups(&form.permission_keys, page.context());
|
||||||
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
|
let back_href = waypoint.or(page.context().route(ADMIN_ROLES_PATH));
|
||||||
let form_component = RolePermissionsForm::new()
|
let form_component = RolePermissionsForm::new()
|
||||||
.with_role_id(id)
|
.with_role_id(id)
|
||||||
.with_groups(groups)
|
.with_groups(groups)
|
||||||
|
|
@ -538,9 +572,12 @@ pub(crate) async fn permissions_post(
|
||||||
.with_waypoint(waypoint);
|
.with_waypoint(waypoint);
|
||||||
let title = Lc::t("title-admin-role-permissions", &LOCALES_USER);
|
let title = Lc::t("title-admin-role-permissions", &LOCALES_USER);
|
||||||
Ok(page
|
Ok(page
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(form_component)
|
.with_child(
|
||||||
.with_child(back_link(back_href))
|
frame(title)
|
||||||
|
.with_child(form_component)
|
||||||
|
.with_child(back_link(back_href)),
|
||||||
|
)
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ use crate::component::user_details;
|
||||||
use crate::config::SETTINGS;
|
use crate::config::SETTINGS;
|
||||||
use crate::entity::{role, user};
|
use crate::entity::{role, user};
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
use crate::handlers::admin::{back_link, map_auth_error};
|
use crate::handlers::admin::{back_link, frame, map_auth_error};
|
||||||
use crate::mail::{Notice, send_notice};
|
use crate::mail::{Notice, send_notice};
|
||||||
use crate::password;
|
use crate::password;
|
||||||
use crate::permission::UserPermission;
|
use crate::permission::UserPermission;
|
||||||
|
|
@ -43,6 +43,8 @@ pub(crate) async fn list_get(
|
||||||
request: HttpRequest,
|
request: HttpRequest,
|
||||||
web::Query(query): web::Query<UsersQuery>,
|
web::Query(query): web::Query<UsersQuery>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminUsers)?;
|
||||||
|
|
||||||
let params = UserListParams {
|
let params = UserListParams {
|
||||||
query: query.q.clone(),
|
query: query.q.clone(),
|
||||||
sort: UserSortField::from_query(query.sort.as_deref()),
|
sort: UserSortField::from_query(query.sort.as_deref()),
|
||||||
|
|
@ -71,9 +73,12 @@ pub(crate) async fn list_get(
|
||||||
} else {
|
} else {
|
||||||
let title = Lc::t("title-admin-users", &LOCALES_USER);
|
let title = Lc::t("title-admin-users", &LOCALES_USER);
|
||||||
Ok(Page::admin(request)
|
Ok(Page::admin(request)
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(search_bar(query.q))
|
.with_child(
|
||||||
.with_child(table)
|
frame(title)
|
||||||
|
.with_child(search_bar(query.q))
|
||||||
|
.with_child(table),
|
||||||
|
)
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
@ -93,7 +98,7 @@ fn search_bar(current_query: Option<String>) -> Html {
|
||||||
name="q"
|
name="q"
|
||||||
value=(value.as_str())
|
value=(value.as_str())
|
||||||
placeholder=[Lc::t("field-search-users", &LOCALES_USER).lookup(cx)]
|
placeholder=[Lc::t("field-search-users", &LOCALES_USER).lookup(cx)]
|
||||||
hx-get=(cx.route(ADMIN_USERS_PATH.as_str()).to_string())
|
hx-get=(cx.route(ADMIN_USERS_PATH).to_string())
|
||||||
hx-trigger="keyup changed delay:400ms, search"
|
hx-trigger="keyup changed delay:400ms, search"
|
||||||
hx-target="#user-table-wrapper"
|
hx-target="#user-table-wrapper"
|
||||||
hx-swap=(hx::swap::OUTER_HTML_SCROLL_TOP)
|
hx-swap=(hx::swap::OUTER_HTML_SCROLL_TOP)
|
||||||
|
|
@ -150,6 +155,7 @@ pub(crate) async fn new_get(
|
||||||
request: HttpRequest,
|
request: HttpRequest,
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminUsers)?;
|
||||||
let roles = match available_roles(&[]).await {
|
let roles = match available_roles(&[]).await {
|
||||||
Ok(roles) => roles,
|
Ok(roles) => roles,
|
||||||
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
|
Err(_) => return Err(ErrorPage::InternalError(Some(request))),
|
||||||
|
|
@ -157,19 +163,22 @@ pub(crate) async fn new_get(
|
||||||
// El campo "administrador" sólo se ofrece si quien da de alta ya es administrador: no es un
|
// 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`).
|
// permiso del catálogo (igual que conceder/revocar en la edición, ver `set_user_admin`).
|
||||||
let allow_admin_field = request.extension::<Account>().is_some_and(|a| a.is_admin());
|
let allow_admin_field = request.extension::<Account>().is_some_and(|a| a.is_admin());
|
||||||
let page = Page::admin(request);
|
let mut page = Page::admin(request);
|
||||||
let back_href = waypoint.or(page.route(ADMIN_USERS_PATH.as_str()));
|
let back_href = waypoint.or(page.context().route(ADMIN_USERS_PATH));
|
||||||
let title = Lc::t("title-admin-user-new", &LOCALES_USER);
|
let title = Lc::t("title-admin-user-new", &LOCALES_USER);
|
||||||
Ok(page
|
Ok(page
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(
|
.with_child(
|
||||||
UserForm::new()
|
frame(title)
|
||||||
.with_mode(UserFormMode::New)
|
.with_child(
|
||||||
.with_roles(roles)
|
UserForm::new()
|
||||||
.with_allow_admin_field(allow_admin_field)
|
.with_mode(UserFormMode::New)
|
||||||
.with_waypoint(waypoint),
|
.with_roles(roles)
|
||||||
|
.with_allow_admin_field(allow_admin_field)
|
||||||
|
.with_waypoint(waypoint),
|
||||||
|
)
|
||||||
|
.with_child(back_link(back_href)),
|
||||||
)
|
)
|
||||||
.with_child(back_link(back_href))
|
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
@ -204,6 +213,7 @@ pub(crate) async fn new_post(
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
raw: web::RawForm,
|
raw: web::RawForm,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminUsers)?;
|
||||||
let Ok(form) = serde_qs::from_bytes::<NewUserFormData>(&raw.0) else {
|
let Ok(form) = serde_qs::from_bytes::<NewUserFormData>(&raw.0) else {
|
||||||
return Err(ErrorPage::BadRequest(Some(request)));
|
return Err(ErrorPage::BadRequest(Some(request)));
|
||||||
};
|
};
|
||||||
|
|
@ -230,13 +240,13 @@ pub(crate) async fn new_post(
|
||||||
match result {
|
match result {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
let cx = Context::admin(request);
|
let cx = Context::admin(request);
|
||||||
let target = waypoint.or(cx.route(ADMIN_USERS_PATH.as_str()));
|
let target = waypoint.or(cx.route(ADMIN_USERS_PATH));
|
||||||
Ok(Redirect::see_other(target).into_response())
|
Ok(Redirect::see_other(target).into_response())
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let roles = available_roles(&role_ids).await.unwrap_or_default();
|
let roles = available_roles(&role_ids).await.unwrap_or_default();
|
||||||
let page = Page::admin(request);
|
let mut page = Page::admin(request);
|
||||||
let back_href = waypoint.or(page.route(ADMIN_USERS_PATH.as_str()));
|
let back_href = waypoint.or(page.context().route(ADMIN_USERS_PATH));
|
||||||
let form_component = UserForm::new()
|
let form_component = UserForm::new()
|
||||||
.with_mode(UserFormMode::New)
|
.with_mode(UserFormMode::New)
|
||||||
.with_username(form.username)
|
.with_username(form.username)
|
||||||
|
|
@ -252,9 +262,12 @@ pub(crate) async fn new_post(
|
||||||
.with_waypoint(waypoint);
|
.with_waypoint(waypoint);
|
||||||
let title = Lc::t("title-admin-user-new", &LOCALES_USER);
|
let title = Lc::t("title-admin-user-new", &LOCALES_USER);
|
||||||
Ok(page
|
Ok(page
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(form_component)
|
.with_child(
|
||||||
.with_child(back_link(back_href))
|
frame(title)
|
||||||
|
.with_child(form_component)
|
||||||
|
.with_child(back_link(back_href)),
|
||||||
|
)
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
@ -318,7 +331,7 @@ async fn render_edit_page(
|
||||||
// Bloquear y activar exige además `user:block_accounts` (ver `status_post`).
|
// Bloquear y activar exige además `user:block_accounts` (ver `status_post`).
|
||||||
let can_change_status = has_permission(&request, &UserPermission::BlockAccounts);
|
let can_change_status = has_permission(&request, &UserPermission::BlockAccounts);
|
||||||
let mut page = Page::admin(request);
|
let mut page = Page::admin(request);
|
||||||
let back_href = waypoint.or(page.route(ADMIN_USERS_PATH.as_str()));
|
let back_href = waypoint.or(page.context().route(ADMIN_USERS_PATH));
|
||||||
let title = Lc::t("title-admin-user-edit", &LOCALES_USER);
|
let title = Lc::t("title-admin-user-edit", &LOCALES_USER);
|
||||||
let actions = edit_actions(
|
let actions = edit_actions(
|
||||||
id,
|
id,
|
||||||
|
|
@ -327,17 +340,20 @@ async fn render_edit_page(
|
||||||
can_toggle_admin,
|
can_toggle_admin,
|
||||||
can_change_status,
|
can_change_status,
|
||||||
&waypoint,
|
&waypoint,
|
||||||
page.context_mut(),
|
page.context(),
|
||||||
);
|
);
|
||||||
|
|
||||||
page.with_title(title)
|
page.with_title(title.clone())
|
||||||
.with_child(
|
.with_child(
|
||||||
form.with_mode(UserFormMode::Edit)
|
frame(title)
|
||||||
.with_user_id(Some(id))
|
.with_child(
|
||||||
.with_waypoint(waypoint.clone()),
|
form.with_mode(UserFormMode::Edit)
|
||||||
|
.with_user_id(Some(id))
|
||||||
|
.with_waypoint(waypoint.clone()),
|
||||||
|
)
|
||||||
|
.with_child(actions)
|
||||||
|
.with_child(back_link(back_href)),
|
||||||
)
|
)
|
||||||
.with_child(actions)
|
|
||||||
.with_child(back_link(back_href))
|
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response()
|
.into_response()
|
||||||
|
|
@ -435,6 +451,7 @@ pub(crate) async fn edit_get(
|
||||||
web::Path(id): web::Path<i32>,
|
web::Path(id): web::Path<i32>,
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminUsers)?;
|
||||||
require_manageable(&request, id).await?;
|
require_manageable(&request, id).await?;
|
||||||
Ok(render_user_edit(request, id, None, waypoint).await)
|
Ok(render_user_edit(request, id, None, waypoint).await)
|
||||||
}
|
}
|
||||||
|
|
@ -466,6 +483,7 @@ pub(crate) async fn edit_post(
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
raw: web::RawForm,
|
raw: web::RawForm,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminUsers)?;
|
||||||
let user = require_manageable(&request, id).await?;
|
let user = require_manageable(&request, id).await?;
|
||||||
let Ok(form) = serde_qs::from_bytes::<EditUserFormData>(&raw.0) else {
|
let Ok(form) = serde_qs::from_bytes::<EditUserFormData>(&raw.0) else {
|
||||||
return Err(ErrorPage::BadRequest(Some(request)));
|
return Err(ErrorPage::BadRequest(Some(request)));
|
||||||
|
|
@ -492,7 +510,7 @@ pub(crate) async fn edit_post(
|
||||||
match result {
|
match result {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
let cx = Context::admin(request);
|
let cx = Context::admin(request);
|
||||||
let target = waypoint.or(cx.route(ADMIN_USERS_PATH.as_str()));
|
let target = waypoint.or(cx.route(ADMIN_USERS_PATH));
|
||||||
Ok(Redirect::see_other(target).into_response())
|
Ok(Redirect::see_other(target).into_response())
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
|
|
@ -522,6 +540,8 @@ pub(crate) async fn view_get(
|
||||||
web::Path(id): web::Path<i32>,
|
web::Path(id): web::Path<i32>,
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminUsers)?;
|
||||||
|
|
||||||
let user = match user_admin::find_user(id).await {
|
let user = match user_admin::find_user(id).await {
|
||||||
Ok(user) => user,
|
Ok(user) => user,
|
||||||
Err(_) => return Err(ErrorPage::NotFound(Some(request))),
|
Err(_) => return Err(ErrorPage::NotFound(Some(request))),
|
||||||
|
|
@ -532,16 +552,19 @@ pub(crate) async fn view_get(
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut page = Page::admin(request);
|
let mut page = Page::admin(request);
|
||||||
let back_href = waypoint.or(page.route(ADMIN_USERS_PATH.as_str()));
|
let back_href = waypoint.or(page.context().route(ADMIN_USERS_PATH));
|
||||||
let details_block = user_details(&user, page.context_mut()).await;
|
let details_block = user_details(&user, page.context()).await;
|
||||||
let roles_block = user_view_roles(&roles, user.is_admin, page.context_mut()).await;
|
let roles_block = user_view_roles(&roles, user.is_admin, page.context()).await;
|
||||||
|
|
||||||
let title = Lc::t("title-admin-user-view", &LOCALES_USER);
|
let title = Lc::t("title-admin-user-view", &LOCALES_USER);
|
||||||
Ok(page
|
Ok(page
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(details_block)
|
.with_child(
|
||||||
.with_child(roles_block)
|
frame(title)
|
||||||
.with_child(back_link(back_href))
|
.with_child(details_block)
|
||||||
|
.with_child(roles_block)
|
||||||
|
.with_child(back_link(back_href)),
|
||||||
|
)
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
@ -622,6 +645,7 @@ pub(crate) async fn status_post(
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
web::Form(form): web::Form<StatusFormData>,
|
web::Form(form): web::Form<StatusFormData>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminUsers)?;
|
||||||
require_permission(&request, &UserPermission::BlockAccounts)?;
|
require_permission(&request, &UserPermission::BlockAccounts)?;
|
||||||
require_manageable(&request, id).await?;
|
require_manageable(&request, id).await?;
|
||||||
let Some(account) = request.extension::<Account>().cloned() else {
|
let Some(account) = request.extension::<Account>().cloned() else {
|
||||||
|
|
@ -707,19 +731,23 @@ pub(crate) async fn password_get(
|
||||||
web::Path(id): web::Path<i32>,
|
web::Path(id): web::Path<i32>,
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminUsers)?;
|
||||||
let user = require_manageable(&request, id).await?;
|
let user = require_manageable(&request, id).await?;
|
||||||
let page = Page::admin(request);
|
let mut page = Page::admin(request);
|
||||||
let edit_href = waypoint.append_to(page.route(user_path(id, "edit")));
|
let edit_href = waypoint.append_to(page.context().route(user_path(id, "edit")));
|
||||||
let title = Lc::t("title-admin-user-password", &LOCALES_USER);
|
let title = Lc::t("title-admin-user-password", &LOCALES_USER);
|
||||||
Ok(page
|
Ok(page
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(user_summary(&user))
|
|
||||||
.with_child(
|
.with_child(
|
||||||
AdminPasswordForm::new()
|
frame(title)
|
||||||
.with_user_id(id)
|
.with_child(user_summary(&user))
|
||||||
.with_waypoint(waypoint),
|
.with_child(
|
||||||
|
AdminPasswordForm::new()
|
||||||
|
.with_user_id(id)
|
||||||
|
.with_waypoint(waypoint),
|
||||||
|
)
|
||||||
|
.with_child(back_link(edit_href)),
|
||||||
)
|
)
|
||||||
.with_child(back_link(edit_href))
|
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
@ -739,6 +767,7 @@ pub(crate) async fn password_post(
|
||||||
web::Query(waypoint): web::Query<Waypoint>,
|
web::Query(waypoint): web::Query<Waypoint>,
|
||||||
web::Form(form): web::Form<AdminPasswordFormData>,
|
web::Form(form): web::Form<AdminPasswordFormData>,
|
||||||
) -> Result<Response, ErrorPage> {
|
) -> Result<Response, ErrorPage> {
|
||||||
|
require_permission(&request, &UserPermission::AdminUsers)?;
|
||||||
let user = require_manageable(&request, id).await?;
|
let user = require_manageable(&request, id).await?;
|
||||||
|
|
||||||
let result = match password::passwords_match(&form.password, &form.confirm_password) {
|
let result = match password::passwords_match(&form.password, &form.confirm_password) {
|
||||||
|
|
@ -754,19 +783,22 @@ pub(crate) async fn password_post(
|
||||||
Ok(Redirect::see_other(edit_href).into_response())
|
Ok(Redirect::see_other(edit_href).into_response())
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let page = Page::admin(request);
|
let mut page = Page::admin(request);
|
||||||
let edit_href = waypoint.append_to(page.route(user_path(id, "edit")));
|
let edit_href = waypoint.append_to(page.context().route(user_path(id, "edit")));
|
||||||
let title = Lc::t("title-admin-user-password", &LOCALES_USER);
|
let title = Lc::t("title-admin-user-password", &LOCALES_USER);
|
||||||
Ok(page
|
Ok(page
|
||||||
.with_title(title)
|
.with_title(title.clone())
|
||||||
.with_child(user_summary(&user))
|
|
||||||
.with_child(
|
.with_child(
|
||||||
AdminPasswordForm::new()
|
frame(title)
|
||||||
.with_user_id(id)
|
.with_child(user_summary(&user))
|
||||||
.with_error(map_auth_error(&err))
|
.with_child(
|
||||||
.with_waypoint(waypoint),
|
AdminPasswordForm::new()
|
||||||
|
.with_user_id(id)
|
||||||
|
.with_error(map_auth_error(&err))
|
||||||
|
.with_waypoint(waypoint),
|
||||||
|
)
|
||||||
|
.with_child(back_link(edit_href)),
|
||||||
)
|
)
|
||||||
.with_child(back_link(edit_href))
|
|
||||||
.render()
|
.render()
|
||||||
.await
|
.await
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|
|
||||||
|
|
@ -15,8 +15,8 @@
|
||||||
Añade cuentas de usuario a una aplicación PageTop: registro, inicio de sesión con sesiones en la
|
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
|
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
|
control de acceso con roles y permisos. Incluye las páginas de administración de usuarios, roles y
|
||||||
permisos en el panel de administración del núcleo, hechas sólo con componentes del núcleo para que
|
permisos sobre `pagetop-admin`, hechas sólo con componentes del núcleo para que funcionen con
|
||||||
funcionen con cualquier tema.
|
cualquier tema.
|
||||||
|
|
||||||
## Sobre PageTop
|
## Sobre PageTop
|
||||||
|
|
||||||
|
|
@ -48,11 +48,9 @@ admin_email = "admin@example.com"
|
||||||
# Sin 'admin_password', se genera una aleatoria y se muestra una sola vez al crearlo.
|
# Sin 'admin_password', se genera una aleatoria y se muestra una sola vez al crearlo.
|
||||||
```
|
```
|
||||||
|
|
||||||
**Protege tus rutas** con su acceso (`Access`): PageTop lo comprueba antes de llegar al *handler*
|
**Comprueba los permisos** en tus *handlers*. El usuario actual se inyecta automáticamente en el
|
||||||
con los permisos que concede esta extensión, y a un usuario anónimo sin acceso le ofrece el inicio
|
contexto de cada [`Page`] al crearla con [`Page::new()`], y las funciones del núcleo, como
|
||||||
de sesión. Dentro del *handler*, el usuario actual está en el contexto de cada [`Page`] al crearla
|
[`has_permission()`], lo consultan:
|
||||||
con [`Page::new()`], y funciones del núcleo como [`has_permission()`] lo consultan para las
|
|
||||||
comprobaciones más concretas:
|
|
||||||
|
|
||||||
```rust,no_run
|
```rust,no_run
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
@ -79,16 +77,15 @@ impl Extension for MyApp {
|
||||||
vec![&pagetop_user::User]
|
vec![&pagetop_user::User]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.route(
|
router.route("/dashboard", web::get(dashboard))
|
||||||
"/dashboard",
|
|
||||||
Access::Permission(&MyPermission::SeeDashboard),
|
|
||||||
web::get(dashboard),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn dashboard(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
async fn dashboard(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
|
if !has_permission(&request, &MyPermission::SeeDashboard) {
|
||||||
|
return Err(ErrorPage::NotFound(Some(request)));
|
||||||
|
}
|
||||||
Page::new(request)
|
Page::new(request)
|
||||||
.with_child(Html::with(|_| html! { h1 { "Panel" } }))
|
.with_child(Html::with(|_| html! { h1 { "Panel" } }))
|
||||||
.render().await
|
.render().await
|
||||||
|
|
@ -162,10 +159,9 @@ ninguna. Detrás de un *proxy* inverso, los límites por IP requieren configurar
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_admin::prelude::*;
|
||||||
use pagetop_seaorm::install_migrations;
|
use pagetop_seaorm::install_migrations;
|
||||||
|
|
||||||
use std::sync::LazyLock;
|
|
||||||
|
|
||||||
pub mod account;
|
pub mod account;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
|
@ -191,6 +187,7 @@ pub mod component;
|
||||||
include_locales!(LOCALES_USER);
|
include_locales!(LOCALES_USER);
|
||||||
|
|
||||||
pub use account::{Account, UserStatus};
|
pub use account::{Account, UserStatus};
|
||||||
|
pub use permission::{DeclarePermissions, PermissionRegistry};
|
||||||
|
|
||||||
/// Prelude de `pagetop-user`.
|
/// Prelude de `pagetop-user`.
|
||||||
pub mod prelude {
|
pub mod prelude {
|
||||||
|
|
@ -198,7 +195,7 @@ pub mod prelude {
|
||||||
pub use crate::component::UserName;
|
pub use crate::component::UserName;
|
||||||
pub use crate::component::{AccountMenu, account_menu};
|
pub use crate::component::{AccountMenu, account_menu};
|
||||||
pub use crate::error::AuthError;
|
pub use crate::error::AuthError;
|
||||||
pub use crate::{Account, UserStatus};
|
pub use crate::{Account, DeclarePermissions, UserStatus};
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< Rutas HTTP (fijas) >*************************************************************************
|
// **< Rutas HTTP (fijas) >*************************************************************************
|
||||||
|
|
@ -239,20 +236,15 @@ const PASSWORD_RESET_PATH: &str = "/user/password/reset";
|
||||||
// POST - la confirma.
|
// POST - la confirma.
|
||||||
const VERIFY_PATH: &str = "/user/verify";
|
const VERIFY_PATH: &str = "/user/verify";
|
||||||
|
|
||||||
// **< Rutas de administración >********************************************************************
|
// **< Rutas de administración (fijas) >************************************************************
|
||||||
|
|
||||||
// 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
|
// Listado, alta, edición, asignación de roles, bloqueo/activación y restablecimiento de contraseña
|
||||||
// de usuarios.
|
// de usuarios.
|
||||||
const ADMIN_USERS: &str = "user/users";
|
const ADMIN_USERS_PATH: &str = "/admin/user/users";
|
||||||
static ADMIN_USERS_PATH: LazyLock<String> = LazyLock::new(|| admin_path(ADMIN_USERS));
|
|
||||||
// Listado, alta, edición, eliminación y asignación de permisos de roles.
|
// Listado, alta, edición, eliminación y asignación de permisos de roles.
|
||||||
const ADMIN_ROLES: &str = "user/roles";
|
const ADMIN_ROLES_PATH: &str = "/admin/user/roles";
|
||||||
static ADMIN_ROLES_PATH: LazyLock<String> = LazyLock::new(|| admin_path(ADMIN_ROLES));
|
|
||||||
// Catálogo de permisos registrados, agrupado por extensión (solo lectura).
|
// Catálogo de permisos registrados, agrupado por extensión (solo lectura).
|
||||||
const ADMIN_PERMISSIONS: &str = "user/permissions";
|
const ADMIN_PERMISSIONS_PATH: &str = "/admin/user/permissions";
|
||||||
|
|
||||||
// Ruta del perfil público del usuario `id`: `{PROFILE_PATH}/{id}`.
|
// Ruta del perfil público del usuario `id`: `{PROFILE_PATH}/{id}`.
|
||||||
fn profile_path(id: i32) -> String {
|
fn profile_path(id: i32) -> String {
|
||||||
|
|
@ -261,49 +253,48 @@ fn profile_path(id: i32) -> String {
|
||||||
|
|
||||||
// Ruta de una acción sobre el usuario `id`: `{ADMIN_USERS_PATH}/{id}/{tail}`.
|
// Ruta de una acción sobre el usuario `id`: `{ADMIN_USERS_PATH}/{id}/{tail}`.
|
||||||
fn user_path(id: i32, tail: &str) -> String {
|
fn user_path(id: i32, tail: &str) -> String {
|
||||||
util::join!(ADMIN_USERS_PATH.as_str(), "/", id.to_string(), "/", tail)
|
util::join!(ADMIN_USERS_PATH, "/", id.to_string(), "/", tail)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ruta de una acción sobre el rol `id`: `{ADMIN_ROLES_PATH}/{id}/{tail}`.
|
// Ruta de una acción sobre el rol `id`: `{ADMIN_ROLES_PATH}/{id}/{tail}`.
|
||||||
fn role_path(id: i32, tail: &str) -> String {
|
fn role_path(id: i32, tail: &str) -> String {
|
||||||
util::join!(ADMIN_ROLES_PATH.as_str(), "/", id.to_string(), "/", tail)
|
util::join!(ADMIN_ROLES_PATH, "/", id.to_string(), "/", tail)
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< Páginas del panel de administración >********************************************************
|
// **< Registro en pagetop-admin (fijo) >***********************************************************
|
||||||
|
|
||||||
// Declara las páginas de usuarios, roles y permisos en el panel de administración, bajo la sección
|
// Registra las páginas de usuarios, roles y permisos en el portal de `pagetop-admin`, bajo la
|
||||||
// integrada "people". Las rutas y sus handlers ya están registrados en `configure_router()`; esta
|
// sección integrada "people". Las rutas y sus handlers ya están registrados en
|
||||||
// declaración sólo aporta el metadato (título, sección, permiso) para que aparezcan en el panel.
|
// `configure_router()`; este registro sólo aporta el metadato (título, sección, permiso) para que
|
||||||
fn declare_admin_pages(bag: &mut AdminPageBag) {
|
// aparezcan en la portada `/admin`.
|
||||||
bag.add(
|
fn declare_admin_pages(bag: &mut PageBag) {
|
||||||
AdminPage::new(
|
bag.add(AdminPage {
|
||||||
ADMIN_USERS,
|
path: ADMIN_USERS_PATH.to_owned(),
|
||||||
"people",
|
section: "people".to_owned(),
|
||||||
Lc::t("title-admin-users", &LOCALES_USER),
|
title: Lc::t("title-admin-users", &LOCALES_USER),
|
||||||
&permission::UserPermission::AdminUsers,
|
description: Some(Lc::t("description-admin-users", &LOCALES_USER)),
|
||||||
)
|
weight: 0,
|
||||||
.with_description(Lc::t("description-admin-users", &LOCALES_USER)),
|
permission: &permission::UserPermission::AdminUsers,
|
||||||
);
|
kind: AdminPageKind::View,
|
||||||
bag.add(
|
});
|
||||||
AdminPage::new(
|
bag.add(AdminPage {
|
||||||
ADMIN_ROLES,
|
path: ADMIN_ROLES_PATH.to_owned(),
|
||||||
"people",
|
section: "people".to_owned(),
|
||||||
Lc::t("title-admin-roles", &LOCALES_USER),
|
title: Lc::t("title-admin-roles", &LOCALES_USER),
|
||||||
&permission::UserPermission::AdminRoles,
|
description: Some(Lc::t("description-admin-roles", &LOCALES_USER)),
|
||||||
)
|
weight: 10,
|
||||||
.with_description(Lc::t("description-admin-roles", &LOCALES_USER))
|
permission: &permission::UserPermission::AdminRoles,
|
||||||
.with_weight(10),
|
kind: AdminPageKind::View,
|
||||||
);
|
});
|
||||||
bag.add(
|
bag.add(AdminPage {
|
||||||
AdminPage::new(
|
path: ADMIN_PERMISSIONS_PATH.to_owned(),
|
||||||
ADMIN_PERMISSIONS,
|
section: "people".to_owned(),
|
||||||
"people",
|
title: Lc::t("title-admin-permissions", &LOCALES_USER),
|
||||||
Lc::t("title-admin-permissions", &LOCALES_USER),
|
description: Some(Lc::t("description-admin-permissions", &LOCALES_USER)),
|
||||||
&permission::UserPermission::AdminPermissions,
|
weight: 20,
|
||||||
)
|
permission: &permission::UserPermission::AdminPermissions,
|
||||||
.with_description(Lc::t("description-admin-permissions", &LOCALES_USER))
|
kind: AdminPageKind::View,
|
||||||
.with_weight(20),
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< Roles de sistema (fijos) >*******************************************************************
|
// **< Roles de sistema (fijos) >*******************************************************************
|
||||||
|
|
@ -353,6 +344,7 @@ impl Extension for User {
|
||||||
|
|
||||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
vec![
|
vec![
|
||||||
|
&pagetop_admin::Admin,
|
||||||
&pagetop_seaorm::SeaORM,
|
&pagetop_seaorm::SeaORM,
|
||||||
&pagetop_htmx::Htmx,
|
&pagetop_htmx::Htmx,
|
||||||
&pagetop_mail::Mail,
|
&pagetop_mail::Mail,
|
||||||
|
|
@ -362,13 +354,11 @@ impl Extension for User {
|
||||||
fn actions(&self) -> Vec<ActionBox> {
|
fn actions(&self) -> Vec<ActionBox> {
|
||||||
actions![
|
actions![
|
||||||
// Comprueba permisos mediante el modelo RBAC almacenado en BD.
|
// Comprueba permisos mediante el modelo RBAC almacenado en BD.
|
||||||
action::auth::CheckPermission::new(middleware::check_rbac_permission),
|
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.
|
// Registra los permisos propios de pagetop-user.
|
||||||
action::auth::DeclarePermissions::new(permission::declare_builtin_permissions),
|
DeclarePermissions::new(permission::declare_builtin_permissions),
|
||||||
// Declara las páginas de usuarios, roles y permisos en el panel de administración.
|
// Registra las páginas de usuarios, roles y permisos en el portal de pagetop-admin.
|
||||||
action::admin::DeclareAdminPages::new(declare_admin_pages),
|
DeclareAdminPages::new(declare_admin_pages),
|
||||||
// Declara las vistas previas de los correos de recuperación y verificación.
|
// Declara las vistas previas de los correos de recuperación y verificación.
|
||||||
pagetop_mail::DeclareMailPreviews::new(mail::declare_previews),
|
pagetop_mail::DeclareMailPreviews::new(mail::declare_previews),
|
||||||
]
|
]
|
||||||
|
|
@ -383,6 +373,7 @@ impl Extension for User {
|
||||||
m20260629_000005_create_sessions,
|
m20260629_000005_create_sessions,
|
||||||
m20260629_000006_create_user_tokens,
|
m20260629_000006_create_user_tokens,
|
||||||
)?;
|
)?;
|
||||||
|
permission::build_registry();
|
||||||
// Los permisos de "anonymous" en memoria sobreviven a una nueva preparación en el mismo
|
// 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.
|
// proceso (las pruebas lo hacen), que puede usar otra base de datos.
|
||||||
session::invalidate_anonymous_permissions();
|
session::invalidate_anonymous_permissions();
|
||||||
|
|
@ -392,123 +383,113 @@ impl Extension for User {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
let edit_own_profile = Access::Permission(&permission::UserPermission::EditOwnProfile);
|
router
|
||||||
let change_own_password =
|
.route(
|
||||||
Access::Permission(&permission::UserPermission::ChangeOwnPassword);
|
|
||||||
routes
|
|
||||||
.public_route(
|
|
||||||
LOGIN_PATH,
|
LOGIN_PATH,
|
||||||
web::get(handlers::auth::login_get).post(handlers::auth::login_post),
|
web::get(handlers::auth::login_get).post(handlers::auth::login_post),
|
||||||
)
|
)
|
||||||
.public_route(LOGOUT_PATH, web::post(handlers::auth::logout_post))
|
.route(LOGOUT_PATH, web::post(handlers::auth::logout_post))
|
||||||
.public_route(
|
.route(
|
||||||
REGISTER_PATH,
|
REGISTER_PATH,
|
||||||
web::get(handlers::auth::register_get).post(handlers::auth::register_post),
|
web::get(handlers::auth::register_get).post(handlers::auth::register_post),
|
||||||
)
|
)
|
||||||
|
.route(PROFILE_PATH, web::get(handlers::account::profile_get))
|
||||||
.route(
|
.route(
|
||||||
PROFILE_PATH,
|
|
||||||
Access::Authenticated,
|
|
||||||
web::get(handlers::account::profile_get),
|
|
||||||
)
|
|
||||||
.public_route(
|
|
||||||
&format!("{}/{{id}}", PROFILE_PATH),
|
&format!("{}/{{id}}", PROFILE_PATH),
|
||||||
web::get(handlers::account::public_profile_get),
|
web::get(handlers::account::public_profile_get),
|
||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
PROFILE_EDIT_PATH,
|
PROFILE_EDIT_PATH,
|
||||||
edit_own_profile,
|
|
||||||
web::get(handlers::account::profile_edit_get)
|
web::get(handlers::account::profile_edit_get)
|
||||||
.post(handlers::account::profile_edit_post),
|
.post(handlers::account::profile_edit_post),
|
||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
PROFILE_PASSWORD_PATH,
|
PROFILE_PASSWORD_PATH,
|
||||||
change_own_password,
|
|
||||||
web::get(handlers::account::password_get).post(handlers::account::password_post),
|
web::get(handlers::account::password_get).post(handlers::account::password_post),
|
||||||
)
|
)
|
||||||
.route(
|
.route(
|
||||||
EMAIL_PATH,
|
EMAIL_PATH,
|
||||||
edit_own_profile,
|
|
||||||
web::get(handlers::account::email_get).post(handlers::account::email_post),
|
web::get(handlers::account::email_get).post(handlers::account::email_post),
|
||||||
)
|
)
|
||||||
.public_route(
|
.route(
|
||||||
&format!("{}/{{uid}}/{{token}}", EMAIL_PATH),
|
&format!("{}/{{uid}}/{{token}}", EMAIL_PATH),
|
||||||
web::get(handlers::account::email_confirm_get)
|
web::get(handlers::account::email_confirm_get)
|
||||||
.post(handlers::account::email_confirm_post),
|
.post(handlers::account::email_confirm_post),
|
||||||
)
|
)
|
||||||
.public_route(
|
.route(
|
||||||
PASSWORD_RESET_PATH,
|
PASSWORD_RESET_PATH,
|
||||||
web::get(handlers::auth::password_reset_get)
|
web::get(handlers::auth::password_reset_get)
|
||||||
.post(handlers::auth::password_reset_post),
|
.post(handlers::auth::password_reset_post),
|
||||||
)
|
)
|
||||||
.public_route(
|
.route(
|
||||||
&format!("{}/{{uid}}/{{token}}", PASSWORD_RESET_PATH),
|
&format!("{}/{{uid}}/{{token}}", PASSWORD_RESET_PATH),
|
||||||
web::get(handlers::auth::password_reset_confirm_get)
|
web::get(handlers::auth::password_reset_confirm_get)
|
||||||
.post(handlers::auth::password_reset_confirm_post),
|
.post(handlers::auth::password_reset_confirm_post),
|
||||||
)
|
)
|
||||||
.public_route(
|
.route(
|
||||||
&format!("{}/{{uid}}/{{token}}", VERIFY_PATH),
|
&format!("{}/{{uid}}/{{token}}", VERIFY_PATH),
|
||||||
web::get(handlers::auth::verify_email_get).post(handlers::auth::verify_email_post),
|
web::get(handlers::auth::verify_email_get).post(handlers::auth::verify_email_post),
|
||||||
)
|
)
|
||||||
.admin_route(ADMIN_USERS, web::get(handlers::admin::users::list_get))
|
.route(ADMIN_USERS_PATH, web::get(handlers::admin::users::list_get))
|
||||||
.admin_route(
|
.route(
|
||||||
&format!("{ADMIN_USERS}/new"),
|
&format!("{}/new", ADMIN_USERS_PATH),
|
||||||
web::get(handlers::admin::users::new_get).post(handlers::admin::users::new_post),
|
web::get(handlers::admin::users::new_get).post(handlers::admin::users::new_post),
|
||||||
)
|
)
|
||||||
.admin_route(
|
.route(
|
||||||
&format!("{ADMIN_USERS}/{{id}}/edit"),
|
&format!("{}/{{id}}/edit", ADMIN_USERS_PATH),
|
||||||
web::get(handlers::admin::users::edit_get).post(handlers::admin::users::edit_post),
|
web::get(handlers::admin::users::edit_get).post(handlers::admin::users::edit_post),
|
||||||
)
|
)
|
||||||
.admin_route(
|
.route(
|
||||||
&format!("{ADMIN_USERS}/{{id}}/view"),
|
&format!("{}/{{id}}/view", ADMIN_USERS_PATH),
|
||||||
web::get(handlers::admin::users::view_get),
|
web::get(handlers::admin::users::view_get),
|
||||||
)
|
)
|
||||||
.admin_route(
|
.route(
|
||||||
&format!("{ADMIN_USERS}/{{id}}/status"),
|
&format!("{}/{{id}}/status", ADMIN_USERS_PATH),
|
||||||
web::post(handlers::admin::users::status_post),
|
web::post(handlers::admin::users::status_post),
|
||||||
)
|
)
|
||||||
.admin_route(
|
.route(
|
||||||
&format!("{ADMIN_USERS}/{{id}}/admin"),
|
&format!("{}/{{id}}/admin", ADMIN_USERS_PATH),
|
||||||
web::post(handlers::admin::users::admin_post),
|
web::post(handlers::admin::users::admin_post),
|
||||||
)
|
)
|
||||||
.admin_route(
|
.route(
|
||||||
&format!("{ADMIN_USERS}/{{id}}/password"),
|
&format!("{}/{{id}}/password", ADMIN_USERS_PATH),
|
||||||
web::get(handlers::admin::users::password_get)
|
web::get(handlers::admin::users::password_get)
|
||||||
.post(handlers::admin::users::password_post),
|
.post(handlers::admin::users::password_post),
|
||||||
)
|
)
|
||||||
.admin_route(ADMIN_ROLES, web::get(handlers::admin::roles::list_get))
|
.route(ADMIN_ROLES_PATH, web::get(handlers::admin::roles::list_get))
|
||||||
.admin_route(
|
.route(
|
||||||
&format!("{ADMIN_ROLES}/new"),
|
&format!("{}/new", ADMIN_ROLES_PATH),
|
||||||
web::get(handlers::admin::roles::new_get).post(handlers::admin::roles::new_post),
|
web::get(handlers::admin::roles::new_get).post(handlers::admin::roles::new_post),
|
||||||
)
|
)
|
||||||
.admin_route(
|
.route(
|
||||||
&format!("{ADMIN_ROLES}/{{id}}/edit"),
|
&format!("{}/{{id}}/edit", ADMIN_ROLES_PATH),
|
||||||
web::get(handlers::admin::roles::edit_get).post(handlers::admin::roles::edit_post),
|
web::get(handlers::admin::roles::edit_get).post(handlers::admin::roles::edit_post),
|
||||||
)
|
)
|
||||||
.admin_route(
|
.route(
|
||||||
&format!("{ADMIN_ROLES}/{{id}}/view"),
|
&format!("{}/{{id}}/view", ADMIN_ROLES_PATH),
|
||||||
web::get(handlers::admin::roles::view_get),
|
web::get(handlers::admin::roles::view_get),
|
||||||
)
|
)
|
||||||
.admin_route(
|
.route(
|
||||||
&format!("{ADMIN_ROLES}/{{id}}/delete"),
|
&format!("{}/{{id}}/delete", ADMIN_ROLES_PATH),
|
||||||
web::post(handlers::admin::roles::delete_post),
|
web::post(handlers::admin::roles::delete_post),
|
||||||
)
|
)
|
||||||
.admin_route(
|
.route(
|
||||||
&format!("{ADMIN_ROLES}/{{id}}/delete/confirm"),
|
&format!("{}/{{id}}/delete/confirm", ADMIN_ROLES_PATH),
|
||||||
web::get(handlers::admin::roles::delete_confirm_get),
|
web::get(handlers::admin::roles::delete_confirm_get),
|
||||||
)
|
)
|
||||||
.admin_route(
|
.route(
|
||||||
&format!("{ADMIN_ROLES}/{{id}}/permissions"),
|
&format!("{}/{{id}}/permissions", ADMIN_ROLES_PATH),
|
||||||
web::get(handlers::admin::roles::permissions_get)
|
web::get(handlers::admin::roles::permissions_get)
|
||||||
.post(handlers::admin::roles::permissions_post),
|
.post(handlers::admin::roles::permissions_post),
|
||||||
)
|
)
|
||||||
.admin_route(
|
.route(
|
||||||
ADMIN_PERMISSIONS,
|
ADMIN_PERMISSIONS_PATH,
|
||||||
web::get(handlers::admin::permissions::list_get),
|
web::get(handlers::admin::permissions::list_get),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_middleware(&self, layers: Layers) -> Layers {
|
fn configure_middleware(&self, router: Router) -> Router {
|
||||||
layers.layer(web::middleware::from_fn(middleware::session_middleware))
|
router.layer(web::middleware::from_fn(middleware::session_middleware))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -67,8 +67,7 @@ pub(crate) async fn session_middleware(
|
||||||
|
|
||||||
// **< check_rbac_permission >**********************************************************************
|
// **< check_rbac_permission >**********************************************************************
|
||||||
|
|
||||||
/// Handler de la acción [`CheckPermission`](pagetop::base::action::auth::CheckPermission) para el
|
/// Handler de la acción [`pagetop::auth::CheckPermission`] para el modelo RBAC de `pagetop-user`.
|
||||||
/// modelo RBAC de `pagetop-user`.
|
|
||||||
///
|
///
|
||||||
/// Lee el [`Account`] inyectado por el middleware de sesión desde las extensiones de la petición
|
/// 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,
|
/// HTTP y concede el permiso si el account lo tiene (un administrador lo tiene concedido siempre,
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,161 @@
|
||||||
//! Permisos propios de `pagetop-user`.
|
//! Catálogo de permisos en memoria y acción `DeclarePermissions`.
|
||||||
//!
|
//!
|
||||||
//! Se declaran en el catálogo de permisos de PageTop ([`PermissionRegistry`]) como los de cualquier
|
//! El catálogo se construye una sola vez durante `Extension::initialize()` a partir de
|
||||||
//! otra extensión. Los permisos concedidos a cada rol se guardan en la tabla `role_permissions`.
|
//! 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;
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
use crate::LOCALES_USER;
|
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<PermissionRef>,
|
||||||
|
/// `(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<Item = PermissionRef> + '_ {
|
||||||
|
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<Item = PermissionRef> + 'a {
|
||||||
|
self.permissions
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.filter(move |p| p.group() == group)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< Catálogo global >****************************************************************************
|
||||||
|
|
||||||
|
static PERMISSIONS: OnceLock<PermissionRegistry> = 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 integrados de pagetop-user >********************************************************
|
||||||
|
|
||||||
/// Permisos propios de `pagetop-user`.
|
/// Permisos propios de `pagetop-user`.
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ use pagetop_seaorm::db::{
|
||||||
|
|
||||||
use crate::entity::{role, role_permission, user_role};
|
use crate::entity::{role, role_permission, user_role};
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
|
use crate::permission;
|
||||||
use crate::session;
|
use crate::session;
|
||||||
|
|
||||||
// **< listado >************************************************************************************
|
// **< listado >************************************************************************************
|
||||||
|
|
@ -282,7 +283,7 @@ pub(crate) async fn set_role_permissions(
|
||||||
) -> Result<(), AuthError> {
|
) -> Result<(), AuthError> {
|
||||||
find_role(role_id).await?;
|
find_role(role_id).await?;
|
||||||
|
|
||||||
let registry = PermissionRegistry::global();
|
let registry = permission::registry();
|
||||||
for key in permission_keys {
|
for key in permission_keys {
|
||||||
if !registry.has_key(key) {
|
if !registry.has_key(key) {
|
||||||
return Err(AuthError::UnknownPermission(key.clone()));
|
return Err(AuthError::UnknownPermission(key.clone()));
|
||||||
|
|
|
||||||
|
|
@ -197,7 +197,6 @@ async fn account_flows() {
|
||||||
password_resets_are_limited_by_account(&client).await;
|
password_resets_are_limited_by_account(&client).await;
|
||||||
requests_are_limited_by_address(&client).await;
|
requests_are_limited_by_address(&client).await;
|
||||||
failed_logins_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) {
|
async fn registration_requires_confirming_the_address(client: &Client) {
|
||||||
|
|
@ -798,34 +797,3 @@ async fn failed_logins_are_limited_by_address(client: &Client) {
|
||||||
.await;
|
.await;
|
||||||
assert_eq!(reply.status, Status::SEE_OTHER);
|
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"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -98,9 +98,9 @@ pub struct MyExtension;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for MyExtension {
|
impl Extension for MyExtension {
|
||||||
fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
fn configure_static_files(&self, router: Router) -> Router {
|
||||||
serve_static_files!(files, ["./static/css", app_css] => "/public/css");
|
serve_static_files!(router, ["./static/css", app_css] => "/public/css");
|
||||||
files
|
router
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
|
||||||
|
|
@ -99,9 +99,9 @@ pub struct MyExtension;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for MyExtension {
|
impl Extension for MyExtension {
|
||||||
fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
fn configure_static_files(&self, router: Router) -> Router {
|
||||||
serve_static_files!(files, ["./static/css", app_css] => "/public/css");
|
serve_static_files!(router, ["./static/css", app_css] => "/public/css");
|
||||||
files
|
router
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
|
||||||
138
src/admin.rs
138
src/admin.rs
|
|
@ -1,138 +0,0 @@
|
||||||
//! 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<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()
|
|
||||||
.iter()
|
|
||||||
.any(|page| registry.section(page.section()).is_some() && page.is_accessible(cx))
|
|
||||||
}
|
|
||||||
|
|
@ -1,57 +0,0 @@
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,119 +0,0 @@
|
||||||
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<Container> {
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
|
@ -1,755 +0,0 @@
|
||||||
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<String>, 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<String>) -> 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<String>,
|
|
||||||
section: impl Into<String>,
|
|
||||||
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<PermissionRef>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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<String>, parent_path: impl Into<String>, 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<PermissionRef>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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<String>, for_path: impl Into<String>, 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<AdminSection>,
|
|
||||||
// Agrupadas por clave de sección y, en cada una, por peso.
|
|
||||||
pages: Vec<AdminPage>,
|
|
||||||
// Posición en `pages` de cada página, por su ruta.
|
|
||||||
page_index: BTreeMap<String, usize>,
|
|
||||||
// Páginas de cada sección en `pages`, por clave de sección.
|
|
||||||
section_pages: BTreeMap<String, Range<usize>>,
|
|
||||||
// Por ruta de la página padre y, en cada una, por peso.
|
|
||||||
tasks: BTreeMap<String, Vec<AdminTask>>,
|
|
||||||
// Por ruta de la página y, en cada una, por peso.
|
|
||||||
actions: BTreeMap<String, Vec<AdminAction>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
static REGISTRY: OnceLock<AdminRegistry> = 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<AdminSection>,
|
|
||||||
pages: Vec<AdminPage>,
|
|
||||||
tasks: Vec<AdminTask>,
|
|
||||||
actions: Vec<AdminAction>,
|
|
||||||
) -> (Self, Vec<String>) {
|
|
||||||
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<String, Range<usize>> = 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<T>(
|
|
||||||
items: Vec<T>,
|
|
||||||
key: impl Fn(&T) -> &String,
|
|
||||||
weight: impl Fn(&T) -> Weight,
|
|
||||||
) -> BTreeMap<String, Vec<T>> {
|
|
||||||
let mut groups: BTreeMap<String, Vec<T>> = 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<String> {
|
|
||||||
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<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);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
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<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::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::<Vec<_>>();
|
|
||||||
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\""));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
26
src/app.rs
26
src/app.rs
|
|
@ -2,7 +2,6 @@
|
||||||
|
|
||||||
mod figfont;
|
mod figfont;
|
||||||
|
|
||||||
use crate::admin;
|
|
||||||
use crate::core::extension;
|
use crate::core::extension;
|
||||||
use crate::core::extension::ExtensionRef;
|
use crate::core::extension::ExtensionRef;
|
||||||
use crate::core::extension::all::StartupError;
|
use crate::core::extension::all::StartupError;
|
||||||
|
|
@ -222,10 +221,7 @@ impl Application {
|
||||||
let std_listener = std::net::TcpListener::bind(&addr)?;
|
let std_listener = std::net::TcpListener::bind(&addr)?;
|
||||||
std_listener.set_nonblocking(true)?;
|
std_listener.set_nonblocking(true)?;
|
||||||
|
|
||||||
let router = match Self::build_router() {
|
let router = 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.
|
// Con el puerto ya enlazado, arranca los servicios en segundo plano de las extensiones.
|
||||||
if let Err(err) = extension::all::start_extensions().await {
|
if let Err(err) = extension::all::start_extensions().await {
|
||||||
|
|
@ -246,13 +242,8 @@ impl Application {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Devuelve el servidor web configurado para usarlo en pruebas de integración.
|
/// 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 {
|
pub fn test(self) -> Router {
|
||||||
Self::build_router().unwrap_or_else(|err| panic!("{err}"))
|
Self::build_router()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Construye el router con las rutas, el middleware y los archivos estáticos de todas las
|
// Construye el router con las rutas, el middleware y los archivos estáticos de todas las
|
||||||
|
|
@ -265,10 +256,6 @@ impl Application {
|
||||||
// cambio, se registra antes: la página 404 debe ver lo que el middleware añade a la petición
|
// 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).
|
// (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
|
// 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.
|
// extensiones, también antes de los archivos estáticos, que no los muestran.
|
||||||
//
|
//
|
||||||
|
|
@ -281,17 +268,16 @@ impl Application {
|
||||||
// Las capas de páginas de error y `CatchPanicLayer` cubren todo, porque se añaden al final. Con
|
// 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
|
// `CatchPanicLayer` en la última capa se capturan incluso los `panic!` que se produzcan dentro
|
||||||
// del propio renderizado de una página de error.
|
// del propio renderizado de una página de error.
|
||||||
fn build_router() -> Result<Router, StartupError> {
|
fn build_router() -> Router {
|
||||||
let router = extension::all::configure_routes(Router::new())?;
|
let router = extension::all::configure_routes(Router::new()).fallback(route_not_found);
|
||||||
let router = admin::configure_routes(router).fallback(route_not_found);
|
|
||||||
let router = extension::all::configure_middleware(router)
|
let router = extension::all::configure_middleware(router)
|
||||||
.layer(axum::middleware::from_fn(keep_flash_messages));
|
.layer(axum::middleware::from_fn(keep_flash_messages));
|
||||||
let router = extension::all::configure_static_files(router);
|
let router = extension::all::configure_static_files(router);
|
||||||
Ok(router
|
router
|
||||||
.layer(axum::middleware::from_fn(reject_cross_origin))
|
.layer(axum::middleware::from_fn(reject_cross_origin))
|
||||||
.layer(axum::middleware::from_fn(limit_body))
|
.layer(axum::middleware::from_fn(limit_body))
|
||||||
.layer(axum::middleware::from_fn(render_error_pages))
|
.layer(axum::middleware::from_fn(render_error_pages))
|
||||||
.layer(CatchPanicLayer::custom(response_for_panic)))
|
.layer(CatchPanicLayer::custom(response_for_panic))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
275
src/auth.rs
275
src/auth.rs
|
|
@ -3,19 +3,10 @@
|
||||||
//! Define el tipo [`CurrentUser`] que PageTop inyecta en el [`Context`] con la información mínima
|
//! 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`]).
|
//! sobre el usuario que ejecuta la petición actual ([`HttpRequest`]).
|
||||||
//!
|
//!
|
||||||
//! Las extensiones se conectan con este sistema mediante las acciones de [`action::auth`]: con
|
//! Incluye la acción [`CheckPermission`] para que las extensiones puedan implementar sus propios
|
||||||
//! [`CheckPermission`] implementan su propio modelo de permisos. Define también [`Access`], el
|
//! modelos de permisos. Y también las funciones auxiliares [`has_permission()`] y
|
||||||
//! acceso con el que se monta cada ruta: PageTop lo comprueba antes de llegar al *handler* y
|
//! [`require_permission()`] para validar en el comienzo de cada handler, antes de construir ni
|
||||||
//! responde a quien no lo cumple con [`deny_access()`], la página de acceso denegado (403). A un
|
//! ejecutar nada, si la petición está autorizada.
|
||||||
//! 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
|
//! 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
|
//! (RBAC, grupos LDAP, ...) son responsabilidad de las extensiones de autenticación. Un concepto
|
||||||
|
|
@ -24,18 +15,16 @@
|
||||||
//! [`CheckPermission`].
|
//! [`CheckPermission`].
|
||||||
//!
|
//!
|
||||||
//! [`Context`]: crate::core::component::Context
|
//! [`Context`]: crate::core::component::Context
|
||||||
//! [`action::auth`]: crate::base::action::auth
|
|
||||||
|
|
||||||
use crate::base::action::auth::{AnonymousDenied, CheckPermission, DeclarePermissions};
|
use crate::core::action::{ActionDispatcher, try_dispatch_actions};
|
||||||
use crate::core::component::Context;
|
|
||||||
use crate::core::theme::{ThemeRef, theme_by_short_name};
|
use crate::core::theme::{ThemeRef, theme_by_short_name};
|
||||||
use crate::datetime::{Timezone, Tz};
|
use crate::datetime::{Timezone, Tz};
|
||||||
use crate::locale::{LanguageIdentifier, Lc, Locale};
|
use crate::locale::{LanguageIdentifier, Lc, Locale};
|
||||||
use crate::response::ErrorPage;
|
use crate::response::ErrorPage;
|
||||||
use crate::web::{HttpRequest, IntoResponse, Response};
|
use crate::web::HttpRequest;
|
||||||
use crate::{AutoDefault, CowStr, Getters, builder_impl, global};
|
use crate::{AutoDefault, CowStr, Getters, Weight, builder_impl, global};
|
||||||
|
|
||||||
use std::sync::OnceLock;
|
use std::ops::ControlFlow;
|
||||||
|
|
||||||
// **< CurrentUser >********************************************************************************
|
// **< CurrentUser >********************************************************************************
|
||||||
|
|
||||||
|
|
@ -213,8 +202,8 @@ pub trait Permission: Send + Sync {
|
||||||
|
|
||||||
/// Descripción breve para humanos (p. ej. en una pantalla de asignación de permisos a roles).
|
/// 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 declare sus permisos en el catálogo
|
/// Por defecto devuelve la propia clave; una extensión que registre sus permisos en un catálogo
|
||||||
/// ([`DeclarePermissions`]) debería sobrescribirlo con un texto traducible.
|
/// visible debería sobrescribirlo con un texto traducible.
|
||||||
fn label(&self) -> Lc {
|
fn label(&self) -> Lc {
|
||||||
Lc::n(self.key())
|
Lc::n(self.key())
|
||||||
}
|
}
|
||||||
|
|
@ -239,6 +228,68 @@ pub trait Permission: Send + Sync {
|
||||||
/// [`require_permission()`] o [`CheckPermission`]).
|
/// [`require_permission()`] o [`CheckPermission`]).
|
||||||
pub type PermissionRef = &'static dyn Permission;
|
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<ActionBox> {
|
||||||
|
/// 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 >*****************************************************************************
|
// **< has_permission >*****************************************************************************
|
||||||
|
|
||||||
/// Comprueba si el usuario actual tiene el permiso indicado.
|
/// Comprueba si el usuario actual tiene el permiso indicado.
|
||||||
|
|
@ -267,18 +318,26 @@ pub type PermissionRef = &'static dyn Permission;
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
pub fn has_permission(request: &HttpRequest, perm: PermissionRef) -> bool {
|
pub fn has_permission(request: &HttpRequest, perm: PermissionRef) -> bool {
|
||||||
CheckPermission::dispatch(request, perm)
|
// 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
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< require_permission >*************************************************************************
|
// **< require_permission >*************************************************************************
|
||||||
|
|
||||||
/// Comprueba un permiso y devuelve `Err(ErrorPage::AccessDenied)` si se deniega.
|
/// Comprueba un permiso y devuelve `Err(ErrorPage::AccessDenied)` si se deniega.
|
||||||
///
|
///
|
||||||
/// Ejecuta [`has_permission()`] para detener un *handler* con una respuesta 403 en cuanto falta el
|
/// Ejecuta [`has_permission()`] para el caso más habitual: detener un handler con una respuesta 403
|
||||||
/// permiso, sin repetir el `if`/`return` en cada punto de comprobación. El acceso de la ruta
|
/// en cuanto falta el permiso, sin repetir el `if`/`return` en cada punto de comprobación. Se hace
|
||||||
/// ([`Access`]) ya se ha comprobado antes de llegar al *handler*; esta función es para un permiso
|
/// directamente sobre la petición, antes de construir ni ejecutar nada (`Context`, `Page`,
|
||||||
/// 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.
|
/// 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
|
/// Si la aplicación necesita ocultar la existencia del recurso a quien no tiene permiso (devolver
|
||||||
|
|
@ -295,7 +354,7 @@ pub fn has_permission(request: &HttpRequest, perm: PermissionRef) -> bool {
|
||||||
/// # fn key(&self) -> CowStr { "myapp:edit".into() }
|
/// # fn key(&self) -> CowStr { "myapp:edit".into() }
|
||||||
/// # }
|
/// # }
|
||||||
/// async fn my_handler(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
/// async fn my_handler(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
/// // La ruta ya exige su acceso; este permiso es más concreto.
|
/// // Comprueba si la petición está autorizada.
|
||||||
/// require_permission(&request, &MyPermission::Edit)?;
|
/// require_permission(&request, &MyPermission::Edit)?;
|
||||||
///
|
///
|
||||||
/// // Ejecuta las instrucciones propias de la petición.
|
/// // Ejecuta las instrucciones propias de la petición.
|
||||||
|
|
@ -312,163 +371,3 @@ pub fn require_permission(request: &HttpRequest, perm: PermissionRef) -> Result<
|
||||||
Err(ErrorPage::AccessDenied(Some(request.clone())))
|
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::<CurrentUser>()
|
|
||||||
.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<PermissionRef>,
|
|
||||||
// `(identificador de grupo, título traducible)`, en orden de primer registro.
|
|
||||||
groups: Vec<(&'static str, Lc)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
static PERMISSIONS: OnceLock<PermissionRegistry> = 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<Item = PermissionRef> + '_ {
|
|
||||||
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<Item = PermissionRef> + '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
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,5 @@
|
||||||
//! Acciones predefinidas para intervenir en el funcionamiento de PageTop.
|
//! Acciones predefinidas para alterar el funcionamiento interno 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 component;
|
||||||
|
|
||||||
pub mod page;
|
pub mod page;
|
||||||
|
|
||||||
pub mod auth;
|
|
||||||
|
|
||||||
pub mod admin;
|
|
||||||
|
|
|
||||||
|
|
@ -1,32 +0,0 @@
|
||||||
//! 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::*;
|
|
||||||
|
|
@ -1,47 +0,0 @@
|
||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,48 +0,0 @@
|
||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,49 +0,0 @@
|
||||||
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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
//! 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<Response>;
|
|
||||||
|
|
||||||
mod check_permission;
|
|
||||||
pub use check_permission::*;
|
|
||||||
|
|
||||||
mod declare_permissions;
|
|
||||||
pub use declare_permissions::*;
|
|
||||||
|
|
||||||
mod anonymous_denied;
|
|
||||||
pub use anonymous_denied::*;
|
|
||||||
|
|
@ -1,69 +0,0 @@
|
||||||
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<Response> {
|
|
||||||
/// // 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<ActionBox> {
|
|
||||||
/// 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<Response> {
|
|
||||||
let mut response = None;
|
|
||||||
try_dispatch_actions(|action: &Self| {
|
|
||||||
response = (action.f)(request);
|
|
||||||
if response.is_some() {
|
|
||||||
ControlFlow::Break(())
|
|
||||||
} else {
|
|
||||||
ControlFlow::Continue(())
|
|
||||||
}
|
|
||||||
});
|
|
||||||
response
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,70 +0,0 @@
|
||||||
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<ActionBox> {
|
|
||||||
/// 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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,85 +0,0 @@
|
||||||
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<ActionBox> {
|
|
||||||
/// 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));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -2,12 +2,6 @@
|
||||||
|
|
||||||
pub mod layout;
|
pub mod layout;
|
||||||
|
|
||||||
mod admin_frame;
|
|
||||||
pub use admin_frame::AdminFrame;
|
|
||||||
|
|
||||||
mod admin_menu;
|
|
||||||
pub use admin_menu::AdminMenu;
|
|
||||||
|
|
||||||
mod badge;
|
mod badge;
|
||||||
pub use badge::Badge;
|
pub use badge::Badge;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,170 +0,0 @@
|
||||||
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().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))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
@ -1,60 +0,0 @@
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -10,10 +10,6 @@ use std::fmt;
|
||||||
/// su gusto (por ejemplo, usando CSS Grid, para que `Aside` se muestre como columna lateral junto a
|
/// 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.
|
/// `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
|
/// No incluye las regiones reservadas ([`ReservedRegions::PageTop`] y
|
||||||
/// [`ReservedRegions::PageBottom`]) porque el propio [`Page::render()`] las añade antes y después
|
/// [`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,
|
/// del resultado de [`Theme::render_page_body()`] para que se rendericen siempre,
|
||||||
|
|
@ -69,25 +65,11 @@ impl Component for Template {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
let admin = matches!(
|
let body = html! {
|
||||||
self.template().downcast_ref::<CoreTemplates>(),
|
(layout::Region::header().render(cx).await)
|
||||||
Some(CoreTemplates::Admin)
|
(layout::Region::aside().render(cx).await)
|
||||||
);
|
(layout::Region::content().render(cx).await)
|
||||||
let body = if admin {
|
(layout::Region::footer().render(cx).await)
|
||||||
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() {
|
if body.is_empty() {
|
||||||
|
|
@ -95,7 +77,7 @@ impl Component for Template {
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(html! {
|
Ok(html! {
|
||||||
div class="wrapper" .wrapper-admin[admin] {
|
div class="wrapper" {
|
||||||
(body)
|
(body)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@ use crate::prelude::*;
|
||||||
/// Componente que muestra los **mensajes de usuario** acumulados en el contexto.
|
/// 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
|
/// No recibe ningún contenido de quien lo construye. Lo obtiene directamente del [`Context`] (ver
|
||||||
/// [`push_message()`](Contextual::push_message)) en el momento de renderizarse, y retira los
|
/// [`Context::push_message()`](Context::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.
|
/// 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
|
/// [`Region`] añade uno al inicio de la región [`CoreRegions::Content`], así que no hace falta
|
||||||
|
|
@ -36,7 +36,8 @@ use crate::prelude::*;
|
||||||
///
|
///
|
||||||
/// async fn homepage(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
/// async fn homepage(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
/// let mut page = Page::new(request);
|
/// let mut page = Page::new(request);
|
||||||
/// page.push_message(MessageLevel::Info, Lc::n("Settings saved."));
|
/// page.context()
|
||||||
|
/// .push_message(MessageLevel::Info, Lc::n("Settings saved."));
|
||||||
/// page.with_child(Html::with(|_| html! { p { "..." } }))
|
/// page.with_child(Html::with(|_| html! { p { "..." } }))
|
||||||
/// .render()
|
/// .render()
|
||||||
/// .await
|
/// .await
|
||||||
|
|
|
||||||
|
|
@ -21,8 +21,8 @@ impl Extension for Welcome {
|
||||||
Lc::l("welcome_extension_description")
|
Lc::l("welcome_extension_description")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/", web::get(home))
|
router.route("/", web::get(home))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,15 +1,16 @@
|
||||||
use crate::auth::CurrentUser;
|
use crate::auth::CurrentUser;
|
||||||
use crate::core::component::{Component, StatusMessage};
|
use crate::core::TypeInfo;
|
||||||
use crate::core::theme::{ChildrenInRegions, CoreTemplates, default_theme};
|
use crate::core::component::{ChildOp, Component, MessageLevel, StatusMessage};
|
||||||
|
use crate::core::theme::{ChildrenInRegions, CoreRegions, CoreTemplates, default_theme};
|
||||||
use crate::core::theme::{RegionRef, TemplateRef, ThemeRef};
|
use crate::core::theme::{RegionRef, TemplateRef, ThemeRef};
|
||||||
use crate::datetime::Tz;
|
use crate::datetime::Tz;
|
||||||
use crate::html::{Assets, Favicon, JavaScript, Preload, ResponsiveStyles, StyleSheet};
|
use crate::html::{Assets, Favicon, JavaScript, Preload, ResponsiveStyles, StyleSheet};
|
||||||
use crate::html::{Markup, PreEscaped, Props, html};
|
use crate::html::{Markup, PreEscaped, Props, PropsOp, RoutePath, html};
|
||||||
use crate::locale::Lc;
|
use crate::locale::Lc;
|
||||||
use crate::locale::RequestLocale;
|
use crate::locale::{LangId, LanguageIdentifier, RequestLocale};
|
||||||
use crate::response::read_flash_messages;
|
use crate::response::read_flash_messages;
|
||||||
use crate::web::HttpRequest;
|
use crate::web::HttpRequest;
|
||||||
use crate::{CowStr, util};
|
use crate::{builder_impl, util};
|
||||||
|
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
|
||||||
|
|
@ -28,18 +29,25 @@ pub use contextual::Contextual;
|
||||||
/// Implementa un **contexto de renderizado** para un documento HTML.
|
/// 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
|
/// Se crea una sola vez por petición usando [`Context::new()`] (típicamente a través de
|
||||||
/// [`Page::new()`] o [`Page::admin()`]), y es la única vía por la que un componente, una acción o
|
/// [`Page::new()`](crate::response::Page::new) o [`Page::admin()`](crate::response::Page::admin)),
|
||||||
/// el tema activo conocen la petición HTTP de origen, el idioma negociado y la zona horaria
|
/// y es la única vía por la que un componente, una acción o el tema activo conocen: la petición
|
||||||
/// efectiva, el usuario autenticado ([`current_user()`]), el tema y la plantilla en uso, y los
|
/// HTTP de origen, el idioma negociado y la zona horaria efectiva, el usuario autenticado
|
||||||
/// recursos (favicon, hojas de estilo, scripts) acumulados hasta ese momento. Otros datos que los
|
/// ([`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
|
||||||
/// componentes necesiten durante el renderizado pueden ser parámetros dinámicos tipados con
|
/// componentes necesiten durante el renderizado pueden ser parámetros dinámicos tipados con
|
||||||
/// [`with_param()`]/[`param()`].
|
/// [`with_param()`](Contextual::with_param)/[`param()`](Contextual::param).
|
||||||
///
|
///
|
||||||
/// Su interfaz la aporta [`Contextual`]: los métodos *builder* (`with_*`), los *getters* y las
|
/// La implementación extiende [`Contextual`], que aporta los métodos *builder* (`with_*`) y los
|
||||||
/// utilidades como [`route()`], [`build_id()`] o [`push_message()`]. Como también lo implementa
|
/// *getters* comunes a cualquier estructura que gestione un contexto de renderizado (también los
|
||||||
/// [`Page`], sobre el contexto que contiene, ambos se usan exactamente igual. Además de sus
|
/// implementa [`Page`](crate::response::Page)). Además, `Context` añade:
|
||||||
/// 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.
|
/// - [`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.
|
||||||
///
|
///
|
||||||
/// # Ejemplos
|
/// # Ejemplos
|
||||||
///
|
///
|
||||||
|
|
@ -85,18 +93,6 @@ pub use contextual::Contextual;
|
||||||
/// let _unique_id = cx.build_id::<Menu>(1); // => "menu-1" si es el primero
|
/// 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]
|
#[rustfmt::skip]
|
||||||
pub struct Context {
|
pub struct Context {
|
||||||
request : Option<HttpRequest>, // Petición HTTP de origen.
|
request : Option<HttpRequest>, // Petición HTTP de origen.
|
||||||
|
|
@ -110,10 +106,6 @@ pub struct Context {
|
||||||
stylesheets : Assets<StyleSheet>, // Hojas de estilo CSS.
|
stylesheets : Assets<StyleSheet>, // Hojas de estilo CSS.
|
||||||
javascripts : Assets<JavaScript>, // Scripts JavaScript.
|
javascripts : Assets<JavaScript>, // Scripts JavaScript.
|
||||||
responsives : ResponsiveStyles, // Estilos *responsive*.
|
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>.
|
body_props : Props, // Id, clases CSS y atributos del <body>.
|
||||||
regions : ChildrenInRegions, // Regiones de componentes para renderizar.
|
regions : ChildrenInRegions, // Regiones de componentes para renderizar.
|
||||||
deferred : Option<Deferred>, // Componentes de renderizado aplazado.
|
deferred : Option<Deferred>, // Componentes de renderizado aplazado.
|
||||||
|
|
@ -138,7 +130,7 @@ impl Default for Context {
|
||||||
|
|
||||||
impl Context {
|
impl Context {
|
||||||
// Construye el `Context` compartido por `new()`, `admin()` y `Default::default()`, evitando
|
// Construye el `Context` compartido por `new()`, `admin()` y `Default::default()`, evitando
|
||||||
// duplicar la lista de campos entre ellos (y la recursión que tendría `new()` llamando a
|
// duplicar la lista de campos entre ambos (y la recursión que tendría `new()` llamando a
|
||||||
// `Default::default()`, o viceversa). Recibe la plantilla para que `admin()` no tenga que
|
// `Default::default()`, o viceversa). Recibe la plantilla para que `admin()` no tenga que
|
||||||
// construir con la plantilla estándar y sobrescribirla después.
|
// construir con la plantilla estándar y sobrescribirla después.
|
||||||
#[rustfmt::skip]
|
#[rustfmt::skip]
|
||||||
|
|
@ -163,10 +155,6 @@ impl Context {
|
||||||
stylesheets: Assets::<StyleSheet>::new(),
|
stylesheets: Assets::<StyleSheet>::new(),
|
||||||
javascripts: Assets::<JavaScript>::new(),
|
javascripts: Assets::<JavaScript>::new(),
|
||||||
responsives: ResponsiveStyles::new(),
|
responsives: ResponsiveStyles::new(),
|
||||||
title : Lc::none(),
|
|
||||||
description: Lc::none(),
|
|
||||||
metadata : Vec::new(),
|
|
||||||
properties : Vec::new(),
|
|
||||||
body_props : Props::default(),
|
body_props : Props::default(),
|
||||||
regions : ChildrenInRegions::default(),
|
regions : ChildrenInRegions::default(),
|
||||||
deferred : None,
|
deferred : None,
|
||||||
|
|
@ -259,8 +247,6 @@ impl Context {
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< Context HELPERS >************************************************************************
|
|
||||||
|
|
||||||
// Empieza a aplazar los componentes que lo pidan (`Component::is_deferred()`), mientras
|
// Empieza a aplazar los componentes que lo pidan (`Component::is_deferred()`), mientras
|
||||||
// `Page::render()` renderiza el `<body>`.
|
// `Page::render()` renderiza el `<body>`.
|
||||||
pub(crate) fn start_deferring(&mut self) {
|
pub(crate) fn start_deferring(&mut self) {
|
||||||
|
|
@ -321,20 +307,293 @@ impl Context {
|
||||||
PreEscaped(body)
|
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.
|
// Retira los mensajes acumulados, para que el componente `Messages` los muestre una sola vez.
|
||||||
pub(crate) fn take_messages(&mut self) -> Vec<StatusMessage> {
|
pub(crate) fn take_messages(&mut self) -> Vec<StatusMessage> {
|
||||||
std::mem::take(&mut self.messages)
|
std::mem::take(&mut self.messages)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Contextual for Context {
|
/// 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]
|
#[inline]
|
||||||
fn context(&self) -> &Context {
|
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);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
fn with_langid(mut self, language: &impl LangId) -> Self {
|
||||||
fn context_mut(&mut self) -> &mut Context {
|
self.locale.with_langid(language);
|
||||||
self
|
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()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,14 @@
|
||||||
use super::{AssetsOp, Context, ContextError};
|
use super::{AssetsOp, ContextError};
|
||||||
|
|
||||||
use crate::auth::CurrentUser;
|
use crate::auth::CurrentUser;
|
||||||
use crate::core::TypeInfo;
|
use crate::builder_impl;
|
||||||
use crate::core::component::{ChildOp, Component, MessageLevel, StatusMessage};
|
use crate::core::component::ChildOp;
|
||||||
use crate::core::theme::{CoreRegions, RegionRef, TemplateRef, ThemeRef, default_theme};
|
use crate::core::theme::{RegionRef, TemplateRef, ThemeRef};
|
||||||
use crate::datetime::{DateFormat, DatePrecision, RelativeFormat, TimeFormat};
|
use crate::datetime::{DateFormat, DatePrecision, RelativeFormat, TimeFormat};
|
||||||
use crate::datetime::{DateInputError, DateTime, NaiveDate, NaiveTime, Tz, Utc};
|
use crate::datetime::{DateInputError, DateTime, NaiveDate, NaiveTime, Tz, Utc};
|
||||||
use crate::html::StyleSheet;
|
use crate::html::{Assets, Favicon, JavaScript, Props, PropsOp, ResponsiveStyles, StyleSheet};
|
||||||
use crate::html::{Assets, Favicon, JavaScript, Props, PropsOp, ResponsiveStyles, RoutePath};
|
use crate::locale::{LangId, Lc};
|
||||||
use crate::locale::{LangId, LanguageIdentifier, Lc, RequestLocale};
|
|
||||||
use crate::response::read_flash_messages;
|
|
||||||
use crate::web::HttpRequest;
|
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
|
// 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()`.
|
// es una clave Fluent. Usado sólo por `format_iso_datetime()`.
|
||||||
|
|
@ -21,31 +16,22 @@ const ISO_DATETIME: &str = "%Y-%m-%dT%H:%M:%S%:z";
|
||||||
|
|
||||||
/// Interfaz para gestionar el **contexto de renderizado** de un documento HTML.
|
/// Interfaz para gestionar el **contexto de renderizado** de un documento HTML.
|
||||||
///
|
///
|
||||||
/// Todo lo que implementa `Contextual` es también proveedor de idioma ([`LangId`]), con el idioma
|
/// `Contextual` extiende [`LangId`] para establecer el idioma del documento y añade métodos para:
|
||||||
/// del documento, así que puede usarse directamente en [`Lc::lookup()`] o [`Lc::using()`]. Además,
|
|
||||||
/// ofrece métodos para:
|
|
||||||
///
|
///
|
||||||
/// - Establecer el **idioma** del documento ([`with_langid()`](Self::with_langid)).
|
/// - Almacenar la **petición HTTP** de origen.
|
||||||
/// - 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
|
/// - Conocer la **identidad del usuario actual** ([`current_user()`](Self::current_user)) y la
|
||||||
/// **zona horaria efectiva** del documento ([`timezone()`](Self::timezone)).
|
/// **zona horaria efectiva** del documento ([`timezone()`](Self::timezone)).
|
||||||
/// - Seleccionar el **tema** y la **plantilla** de renderizado.
|
/// - 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
|
/// - Administrar **recursos** del documento como el icono [`Favicon`], las hojas de estilo
|
||||||
/// [`StyleSheet`] o los scripts [`JavaScript`], directamente o mediante una operación
|
/// [`StyleSheet`] o los scripts [`JavaScript`], directamente o mediante una operación
|
||||||
/// [`AssetsOp`].
|
/// [`AssetsOp`].
|
||||||
/// - Leer y mantener **parámetros dinámicos tipados** de contexto.
|
/// - 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),
|
/// - Formatear **fechas y horas** ([`format_date()`](Self::format_date),
|
||||||
/// [`format_time()`](Self::format_time), [`format_datetime()`](Self::format_datetime) y demás)
|
/// [`format_time()`](Self::format_time), [`format_datetime()`](Self::format_datetime) y demás)
|
||||||
/// para la zona horaria e idioma del documento.
|
/// para la zona horaria e idioma del documento.
|
||||||
///
|
///
|
||||||
/// Todos los métodos actúan sobre el [`Context`] que devuelven [`context()`](Self::context) y
|
/// Lo implementan, típicamente, estructuras que manejan el contexto de renderizado, como
|
||||||
/// [`context_mut()`](Self::context_mut), los únicos que hay que implementar. Lo implementan
|
/// [`Context`](crate::core::component::Context) o [`Page`](crate::response::Page).
|
||||||
/// [`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
|
/// # Ejemplo
|
||||||
///
|
///
|
||||||
|
|
@ -63,23 +49,11 @@ const ISO_DATETIME: &str = "%Y-%m-%dT%H:%M:%S%:z";
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
#[builder_impl]
|
#[builder_impl]
|
||||||
pub trait Contextual {
|
pub trait Contextual: LangId {
|
||||||
/// 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 >*********************************************************************
|
// **< Contextual BUILDER >*********************************************************************
|
||||||
|
|
||||||
/// Establece el idioma del documento.
|
/// 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.
|
/// Fuerza la zona horaria que se utilizará para mostrar fechas y horas en el documento.
|
||||||
///
|
///
|
||||||
|
|
@ -87,10 +61,7 @@ pub trait Contextual {
|
||||||
/// aplicación) por otra explícita. Ver [`CurrentUser::timezone()`].
|
/// aplicación) por otra explícita. Ver [`CurrentUser::timezone()`].
|
||||||
///
|
///
|
||||||
/// [`CurrentUser::timezone()`]: crate::auth::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.
|
/// Almacena la petición HTTP de origen en el contexto.
|
||||||
///
|
///
|
||||||
|
|
@ -106,36 +77,13 @@ pub trait Contextual {
|
||||||
/// [`current_user()`]: Self::current_user
|
/// [`current_user()`]: Self::current_user
|
||||||
/// [`timezone()`]: Self::timezone
|
/// [`timezone()`]: Self::timezone
|
||||||
/// [`theme()`]: Self::theme
|
/// [`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.
|
/// 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.
|
/// 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.
|
/// Añade o modifica un parámetro dinámico del contexto.
|
||||||
///
|
///
|
||||||
|
|
@ -152,122 +100,28 @@ pub trait Contextual {
|
||||||
/// .with_param("title", "Hello".to_string())
|
/// .with_param("title", "Hello".to_string())
|
||||||
/// .with_param("flags", vec!["a", "b"]);
|
/// .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
|
/// Añade un recurso ([`Favicon`], [`StyleSheet`], [`JavaScript`] o
|
||||||
/// [`Preload`](crate::html::Preload)) directamente, o aplica una operación [`AssetsOp`] sobre
|
/// [`Preload`](crate::html::Preload)) directamente, o aplica una operación [`AssetsOp`] sobre
|
||||||
/// los recursos del contexto.
|
/// 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>`.
|
/// 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
|
/// Añade un componente o aplica una operación [`ChildOp`] en la región por defecto del
|
||||||
/// documento.
|
/// 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
|
/// Añade un componente o aplica una operación [`ChildOp`] en una región específica del
|
||||||
/// documento.
|
/// 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 >*********************************************************************
|
// **< Contextual GETTERS >*********************************************************************
|
||||||
|
|
||||||
/// Devuelve una referencia a la petición HTTP asociada, si existe.
|
/// 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.
|
/// Devuelve la identidad del usuario actual.
|
||||||
///
|
///
|
||||||
|
|
@ -287,9 +141,7 @@ pub trait Contextual {
|
||||||
/// page.render().await
|
/// 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.
|
/// Devuelve la zona horaria efectiva para mostrar fechas y horas en el documento.
|
||||||
///
|
///
|
||||||
|
|
@ -302,19 +154,13 @@ pub trait Contextual {
|
||||||
///
|
///
|
||||||
/// [`with_request()`]: Self::with_request
|
/// [`with_request()`]: Self::with_request
|
||||||
/// [`CurrentUser::timezone()`]: crate::auth::CurrentUser::timezone
|
/// [`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.
|
/// 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.
|
/// 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.
|
/// Recupera una *referencia tipada* al parámetro solicitado.
|
||||||
///
|
///
|
||||||
|
|
@ -338,19 +184,7 @@ pub trait Contextual {
|
||||||
/// // Error de tipo:
|
/// // Error de tipo:
|
||||||
/// assert!(cx.param::<String>("user_id").is_err());
|
/// 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()`).
|
/// 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 {
|
fn param_or_default<T: Clone + Default + 'static>(&self, key: &'static str) -> T {
|
||||||
|
|
@ -368,164 +202,22 @@ pub trait Contextual {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Devuelve el Favicon de los recursos del contexto.
|
/// 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.
|
/// 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.
|
/// 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.
|
/// 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>`.
|
/// 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 >*********************************************************************
|
// **< 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
|
/// Formatea una fecha y hora completas en la zona horaria efectiva del documento
|
||||||
/// ([`timezone()`](Self::timezone)), combinando un [`DateFormat`] y un [`TimeFormat`]
|
/// ([`timezone()`](Self::timezone)), combinando un [`DateFormat`] y un [`TimeFormat`]
|
||||||
/// independientes (posiblemente distintos entre sí, como una fecha larga con la hora corta),
|
/// independientes (posiblemente distintos entre sí, como una fecha larga con la hora corta),
|
||||||
|
|
@ -779,19 +471,16 @@ pub trait Contextual {
|
||||||
{
|
{
|
||||||
crate::datetime::input::parse_datetime(text, self, self.timezone())
|
crate::datetime::input::parse_datetime(text, self, self.timezone())
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/// Cualquier contexto de renderizado es proveedor de idioma, con el idioma del documento.
|
/// Elimina un parámetro del contexto. Devuelve `true` si la clave existía y se eliminó.
|
||||||
///
|
///
|
||||||
/// El idioma lo resuelve [`RequestLocale`], que tiene en cuenta la petición HTTP (parámetro `?lang`
|
/// # Ejemplo
|
||||||
/// 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
|
/// ```rust
|
||||||
/// [`global::SETTINGS.app.lang_negotiation`].
|
/// # use pagetop::prelude::*;
|
||||||
///
|
/// let mut cx = Context::default().with_param("temp", 1u8);
|
||||||
/// [`global::SETTINGS.app.lang_negotiation`]: crate::global::AppSettings::lang_negotiation
|
/// assert!(cx.remove_param("temp"));
|
||||||
impl<T: Contextual> LangId for T {
|
/// assert!(!cx.remove_param("temp")); // ya no existe
|
||||||
#[inline]
|
/// ```
|
||||||
fn langid(&self) -> &'static LanguageIdentifier {
|
fn remove_param(&mut self, key: &'static str) -> bool;
|
||||||
self.context().locale.langid()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
use crate::core::component::{Context, Contextual};
|
use crate::core::component::Context;
|
||||||
use crate::html::RoutePath;
|
use crate::html::RoutePath;
|
||||||
use crate::util;
|
use crate::util;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,8 @@
|
||||||
use crate::admin::build_admin_registry;
|
|
||||||
use crate::auth::build_permission_registry;
|
|
||||||
use crate::core::action::publish_actions;
|
use crate::core::action::publish_actions;
|
||||||
use crate::core::extension::ExtensionRef;
|
use crate::core::extension::ExtensionRef;
|
||||||
use crate::core::theme::ThemeRef;
|
use crate::core::theme::ThemeRef;
|
||||||
use crate::core::theme::all::register_theme;
|
use crate::core::theme::all::register_theme;
|
||||||
use crate::web::{Layers, Router, Routes, StaticFiles};
|
use crate::web::Router;
|
||||||
use crate::{BoxError, config, global, serve_static_files, trace, web};
|
use crate::{BoxError, config, global, serve_static_files, trace, web};
|
||||||
|
|
||||||
use std::sync::OnceLock;
|
use std::sync::OnceLock;
|
||||||
|
|
@ -44,14 +42,6 @@ pub enum StartupError {
|
||||||
#[source]
|
#[source]
|
||||||
source: BoxError,
|
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 >****************************************************************
|
// **< REGISTRO DE LAS EXTENSIONES >****************************************************************
|
||||||
|
|
@ -137,12 +127,6 @@ pub fn register_actions() {
|
||||||
.flat_map(|extension| extension.actions())
|
.flat_map(|extension| extension.actions())
|
||||||
.collect()
|
.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 >**************************************************************************
|
// **< CARGA LOS AJUSTES >**************************************************************************
|
||||||
|
|
@ -240,11 +224,7 @@ pub async fn shutdown_extensions() {
|
||||||
|
|
||||||
// **< CONFIGURA LAS RUTAS >************************************************************************
|
// **< CONFIGURA LAS RUTAS >************************************************************************
|
||||||
|
|
||||||
/// Añade las rutas de todas las extensiones, cada una con su acceso.
|
pub fn configure_routes(router: Router) -> Router {
|
||||||
///
|
|
||||||
/// 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.
|
// Sólo compila durante el desarrollo, para evitar errores 400 en la traza de eventos.
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
let router = router.route(
|
let router = router.route(
|
||||||
|
|
@ -256,9 +236,7 @@ pub fn configure_routes(router: Router) -> Result<Router, StartupError> {
|
||||||
.get()
|
.get()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
.fold(Routes::new(router), |r, e| e.configure_router(r))
|
.fold(router, |r, e| e.configure_router(r))
|
||||||
.into_router()
|
|
||||||
.map_err(StartupError::InvalidAdminRoutes)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< CONFIGURA EL MIDDLEWARE GLOBAL >*************************************************************
|
// **< CONFIGURA EL MIDDLEWARE GLOBAL >*************************************************************
|
||||||
|
|
@ -273,8 +251,7 @@ pub fn configure_middleware(router: Router) -> Router {
|
||||||
.get()
|
.get()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
.fold(Layers::new(router), |l, e| e.configure_middleware(l))
|
.fold(router, |r, e| e.configure_middleware(r))
|
||||||
.into_router()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< CONFIGURA LOS ARCHIVOS ESTÁTICOS >***********************************************************
|
// **< CONFIGURA LOS ARCHIVOS ESTÁTICOS >***********************************************************
|
||||||
|
|
@ -284,15 +261,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
|
/// Se llama después de [`configure_middleware`], para que estas rutas no pasen por las capas de
|
||||||
/// middleware de las extensiones.
|
/// middleware de las extensiones.
|
||||||
pub fn configure_static_files(router: Router) -> Router {
|
pub fn configure_static_files(router: Router) -> Router {
|
||||||
let files = EXTENSIONS
|
let router = EXTENSIONS
|
||||||
.get()
|
.get()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
.fold(StaticFiles::new(router), |f, e| e.configure_static_files(f));
|
.fold(router, |r, e| e.configure_static_files(r));
|
||||||
|
|
||||||
serve_static_files!(files, [&global::SETTINGS.dev.pagetop_static_dir, assets] => "/pagetop");
|
serve_static_files!(router, [&global::SETTINGS.dev.pagetop_static_dir, assets] => "/pagetop");
|
||||||
|
|
||||||
files.into_router()
|
router
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ use crate::core::AnyInfo;
|
||||||
use crate::core::action::ActionBox;
|
use crate::core::action::ActionBox;
|
||||||
use crate::core::theme::ThemeRef;
|
use crate::core::theme::ThemeRef;
|
||||||
use crate::locale::Lc;
|
use crate::locale::Lc;
|
||||||
use crate::web::{Layers, Routes, StaticFiles};
|
use crate::web::Router;
|
||||||
|
|
||||||
/// Interfaz común que debe implementar cualquier extensión de PageTop.
|
/// Interfaz común que debe implementar cualquier extensión de PageTop.
|
||||||
///
|
///
|
||||||
|
|
@ -246,30 +246,29 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Registra las rutas de la extensión en el servidor web de la aplicación.
|
/// Registra rutas, servicios y capas de la extensión en el servidor web de la aplicación.
|
||||||
///
|
///
|
||||||
/// Recibe las rutas acumuladas hasta ese momento, añade las de la extensión y las devuelve. La
|
/// Recibe las rutas acumuladas hasta ese momento, añade lo que la extensión necesite y retorna
|
||||||
/// implementación por defecto las devuelve sin cambios.
|
/// las rutas con las nuevas modificaciones. La implementación por defecto devuelve las rutas
|
||||||
|
/// sin cambios.
|
||||||
///
|
///
|
||||||
/// Cada ruta se monta con su acceso ([`Access`]): quién puede llegar a su *handler*, que
|
/// # Operaciones disponibles
|
||||||
/// 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.
|
|
||||||
///
|
///
|
||||||
/// Los archivos estáticos se registran en [`configure_static_files`], donde no pasan por el
|
/// | Operación | Llamada sobre `router` |
|
||||||
/// middleware de las extensiones.
|
/// |----------------------------------|----------------------------------------------------|
|
||||||
|
/// | 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.
|
||||||
///
|
///
|
||||||
/// # Ejemplos
|
/// # Ejemplos
|
||||||
///
|
///
|
||||||
/// ## Rutas con su acceso
|
/// ## Rutas HTTP básicas
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use pagetop::prelude::*;
|
/// # 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 list_posts() -> &'static str { "" }
|
||||||
/// # async fn view_post() -> &'static str { "" }
|
/// # async fn view_post() -> &'static str { "" }
|
||||||
/// # async fn create_post() -> &'static str { "" }
|
/// # async fn create_post() -> &'static str { "" }
|
||||||
|
|
@ -277,20 +276,45 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
///
|
///
|
||||||
/// #[async_trait]
|
/// #[async_trait]
|
||||||
/// impl Extension for Blog {
|
/// impl Extension for Blog {
|
||||||
/// fn configure_router(&self, routes: Routes) -> Routes {
|
/// fn configure_router(&self, router: Router) -> Router {
|
||||||
/// let publish = Access::Permission(&BlogPermission::Publish);
|
/// router
|
||||||
/// routes
|
/// .route("/posts", web::get(list_posts))
|
||||||
/// .public_route("/posts", web::get(list_posts))
|
/// .route("/posts/{id}", web::get(view_post))
|
||||||
/// .public_route("/posts/{id}", web::get(view_post))
|
/// .route("/posts/new", web::post(create_post))
|
||||||
/// .route("/posts/new", publish, web::post(create_post))
|
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// ## Rutas agrupadas con su propio middleware
|
/// ## Rutas agrupadas bajo un prefijo
|
||||||
///
|
///
|
||||||
/// Un `Router::new()` aparte, con sus capas, se añade bajo un prefijo con
|
/// ```rust,no_run
|
||||||
/// [`Routes::nest()`]: sus capas sólo envuelven sus rutas, y todas comparten el mismo acceso.
|
/// # 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.
|
||||||
///
|
///
|
||||||
/// ```rust,ignore
|
/// ```rust,ignore
|
||||||
/// # use pagetop::prelude::*;
|
/// # use pagetop::prelude::*;
|
||||||
|
|
@ -298,11 +322,11 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
///
|
///
|
||||||
/// #[async_trait]
|
/// #[async_trait]
|
||||||
/// impl Extension for Api {
|
/// impl Extension for Api {
|
||||||
/// fn configure_router(&self, routes: Routes) -> Routes {
|
/// fn configure_router(&self, router: Router) -> Router {
|
||||||
/// let api = Router::new()
|
/// let api = Router::new()
|
||||||
/// .route("/data", web::get(get_data))
|
/// .route("/api/data", web::get(get_data))
|
||||||
/// .layer(api_key_layer());
|
/// .layer(auth_layer());
|
||||||
/// routes.nest("/api", Access::Public, api)
|
/// router.merge(api)
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
|
|
@ -310,15 +334,10 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
/// Para el middleware que deba cubrir las rutas de **todas** las extensiones, usar
|
/// Para el middleware que deba cubrir las rutas de **todas** las extensiones, usar
|
||||||
/// [`configure_middleware`].
|
/// [`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_static_files`]: Self::configure_static_files
|
||||||
/// [`configure_middleware`]: Self::configure_middleware
|
/// [`configure_middleware`]: Self::configure_middleware
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes
|
router
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Añade capas de middleware globales a las rutas de la aplicación.
|
/// Añade capas de middleware globales a las rutas de la aplicación.
|
||||||
|
|
@ -345,16 +364,13 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
///
|
///
|
||||||
/// #[async_trait]
|
/// #[async_trait]
|
||||||
/// impl Extension for MyAuth {
|
/// impl Extension for MyAuth {
|
||||||
/// fn configure_middleware(&self, layers: Layers) -> Layers {
|
/// fn configure_middleware(&self, router: Router) -> Router {
|
||||||
/// layers.layer(web::middleware::from_fn(session_middleware))
|
/// router.layer(web::middleware::from_fn(session_middleware))
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
fn configure_middleware(&self, router: Router) -> Router {
|
||||||
/// Sólo admite capas ([`Layers`](crate::web::Layers)): las rutas se registran en
|
router
|
||||||
/// [`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,
|
/// Registra los archivos estáticos de la extensión (hojas de estilo, *scripts*, fuentes,
|
||||||
|
|
@ -365,13 +381,12 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
/// **después** de [`configure_middleware`](Self::configure_middleware), así que estas rutas
|
/// **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
|
/// **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
|
/// sesión). Una página carga muchos recursos; sin esta separación, cada uno repetiría ese
|
||||||
/// trabajo, que no necesita. Por eso son siempre públicos. La implementación por defecto los
|
/// trabajo, que no necesita. La implementación por defecto devuelve las rutas sin cambios.
|
||||||
/// devuelve sin cambios.
|
|
||||||
///
|
///
|
||||||
/// Si algún archivo debe pasar por el middleware o exigir un acceso (p. ej. descargas que
|
/// Si algún archivo sí debe pasar por el middleware (p. ej. descargas que requieran una sesión
|
||||||
/// requieran una sesión iniciada), se registra en [`configure_router`](Self::configure_router).
|
/// iniciada), se registra en [`configure_router`](Self::configure_router).
|
||||||
///
|
///
|
||||||
/// La macro [`serve_static_files!`](crate::serve_static_files) sombrea `files` internamente,
|
/// La macro [`serve_static_files!`](crate::serve_static_files) sombrea `router` internamente,
|
||||||
/// por lo que el parámetro no necesita `mut`. Sí es necesario devolverlo al final.
|
/// por lo que el parámetro no necesita `mut`. Sí es necesario devolverlo al final.
|
||||||
///
|
///
|
||||||
/// # Ejemplo
|
/// # Ejemplo
|
||||||
|
|
@ -382,14 +397,14 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
///
|
///
|
||||||
/// #[async_trait]
|
/// #[async_trait]
|
||||||
/// impl Extension for MyExtension {
|
/// impl Extension for MyExtension {
|
||||||
/// fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
/// fn configure_static_files(&self, router: Router) -> Router {
|
||||||
/// serve_static_files!(files, [assets] => "/static");
|
/// serve_static_files!(router, [assets] => "/static");
|
||||||
/// files
|
/// router
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
fn configure_static_files(&self, router: Router) -> Router {
|
||||||
files
|
router
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -192,9 +192,7 @@ pub trait Theme: Extension + Send + Sync {
|
||||||
parent.render_page_body(page).await
|
parent.render_page_body(page).await
|
||||||
} else {
|
} else {
|
||||||
let template = page.template();
|
let template = page.template();
|
||||||
layout::Template::of(template)
|
layout::Template::of(template).render(page.context()).await
|
||||||
.render(page.context_mut())
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -242,13 +240,13 @@ pub trait Theme: Extension + Send + Sync {
|
||||||
html! {
|
html! {
|
||||||
meta charset="utf-8";
|
meta charset="utf-8";
|
||||||
|
|
||||||
@if let Some(title) = page.title().lookup(page) {
|
@if let Some(title) = page.title() {
|
||||||
title { (global::SETTINGS.app.name) (" | ") (title) }
|
title { (global::SETTINGS.app.name) (" | ") (title) }
|
||||||
} @else {
|
} @else {
|
||||||
title { (global::SETTINGS.app.name) }
|
title { (global::SETTINGS.app.name) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@if let Some(description) = page.description().lookup(page) {
|
@if let Some(description) = page.description() {
|
||||||
meta name="description" content=(description);
|
meta name="description" content=(description);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -262,7 +260,7 @@ pub trait Theme: Extension + Send + Sync {
|
||||||
meta property=(property) content=(content) {}
|
meta property=(property) content=(content) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
(page.context_mut().render_assets())
|
(page.context().render_assets())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -103,7 +103,7 @@ pub enum CoreRegions {
|
||||||
/// [`Messages`]: crate::base::component::Messages
|
/// [`Messages`]: crate::base::component::Messages
|
||||||
/// [`Messages::with_deferred()`]: crate::base::component::Messages::with_deferred
|
/// [`Messages::with_deferred()`]: crate::base::component::Messages::with_deferred
|
||||||
/// [`Context`]: crate::core::component::Context
|
/// [`Context`]: crate::core::component::Context
|
||||||
/// [`Context::push_message()`]: crate::core::component::Contextual::push_message
|
/// [`Context::push_message()`]: crate::core::component::Context::push_message
|
||||||
/// [`ResponseExt::with_message()`]: crate::response::ResponseExt::with_message
|
/// [`ResponseExt::with_message()`]: crate::response::ResponseExt::with_message
|
||||||
#[default]
|
#[default]
|
||||||
Content,
|
Content,
|
||||||
|
|
@ -177,13 +177,7 @@ pub enum CoreTemplates {
|
||||||
|
|
||||||
/// Plantilla para la **interfaz de administración**, de nombre `"admin"`.
|
/// Plantilla para la **interfaz de administración**, de nombre `"admin"`.
|
||||||
///
|
///
|
||||||
/// Se utiliza para las páginas del panel de administración ([`Page::admin()`]): además de las
|
/// Se utiliza para páginas de administración o paneles de control.
|
||||||
/// 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,
|
Admin,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -199,8 +193,8 @@ impl TemplateName for CoreTemplates {
|
||||||
#[inline]
|
#[inline]
|
||||||
fn label(&self) -> Lc {
|
fn label(&self) -> Lc {
|
||||||
match self {
|
match self {
|
||||||
Self::Standard => Lc::l("template_standard"),
|
Self::Standard => Lc::l("template-standard"),
|
||||||
Self::Admin => Lc::l("template_admin"),
|
Self::Admin => Lc::l("template-admin"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -169,15 +169,6 @@ pub struct AppSettings {
|
||||||
/// [`CurrentUser::timezone()`]: crate::auth::CurrentUser::timezone
|
/// [`CurrentUser::timezone()`]: crate::auth::CurrentUser::timezone
|
||||||
#[default = true]
|
#[default = true]
|
||||||
pub timezone_per_user: bool,
|
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
|
/// Banner ASCII mostrado al inicio: *"Off"* (desactivado), *"Slant"*, *"Small"*, *"Speed"* o
|
||||||
/// *"Starwars"*.
|
/// *"Starwars"*.
|
||||||
#[default(StartupBanner::Slant)]
|
#[default(StartupBanner::Slant)]
|
||||||
|
|
@ -317,29 +308,6 @@ fn origins<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<String>, D:
|
||||||
.collect()
|
.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
|
// 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
|
// 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.
|
// `HttpRequest::client_ip()` devolvería siempre `None` sin que nada lo indicase.
|
||||||
|
|
@ -441,30 +409,6 @@ mod tests {
|
||||||
assert!(load("Forwarded").is_err());
|
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]
|
#[test]
|
||||||
fn trusted_origins_are_normalized_and_validated() {
|
fn trusted_origins_are_normalized_and_validated() {
|
||||||
let load = |value: &str| {
|
let load = |value: &str| {
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ use serde::{Deserialize, Deserializer};
|
||||||
///
|
///
|
||||||
/// [`global::SETTINGS.app.lang_negotiation`]: crate::global::AppSettings::lang_negotiation
|
/// [`global::SETTINGS.app.lang_negotiation`]: crate::global::AppSettings::lang_negotiation
|
||||||
/// [`RequestLocale`]: crate::locale::RequestLocale
|
/// [`RequestLocale`]: crate::locale::RequestLocale
|
||||||
/// [`Context::route()`]: crate::core::component::Contextual::route
|
/// [`Context::route()`]: crate::core::component::Context::route
|
||||||
#[derive(AutoDefault, Clone, Copy, Debug, Eq, PartialEq)]
|
#[derive(AutoDefault, Clone, Copy, Debug, Eq, PartialEq)]
|
||||||
pub enum LangNegotiation {
|
pub enum LangNegotiation {
|
||||||
/// Usa todas las fuentes disponibles para determinar el idioma, en este orden: comprueba el
|
/// Usa todas las fuentes disponibles para determinar el idioma, en este orden: comprueba el
|
||||||
|
|
|
||||||
|
|
@ -54,8 +54,8 @@ struct HelloWorld;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for HelloWorld {
|
impl Extension for HelloWorld {
|
||||||
fn configure_router(&self, routes: Routes) -> Routes {
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
routes.public_route("/", web::get(hello_world))
|
router.route("/", web::get(hello_world))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -219,8 +219,6 @@ pub mod datetime;
|
||||||
pub mod core;
|
pub mod core;
|
||||||
// Identidad del usuario y sistema de autorización extensible.
|
// Identidad del usuario y sistema de autorización extensible.
|
||||||
pub mod auth;
|
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.
|
// Respuestas a peticiones web en sus diferentes formatos.
|
||||||
pub mod response;
|
pub mod response;
|
||||||
// Gestión del servidor y rutas web.
|
// Gestión del servidor y rutas web.
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue