📝 Document route access and custom authentication
Adapt the guides to the current PageTop API: Routes with the access of each route, Layers, StaticFiles and the administration panel in the core, with pagetop-admin reduced to the settings forms. Add the "Connect your own authentication" guide, the mail test page and the admin_path setting, and explain route access in the architecture page. Mount the books with their access through pagetop-mdbook.
This commit is contained in:
parent
f42f5e9b89
commit
345bd26974
41 changed files with 869 additions and 368 deletions
|
|
@ -3,10 +3,11 @@
|
|||
**Objetivo:** dar a tu extensión su sitio en el panel `/admin`: una página de ajustes que el panel
|
||||
construye y guarda por ti, y una página propia con tu contenido, cada una protegida por su permiso.
|
||||
|
||||
El panel lo aporta `pagetop-admin`. No tienes que montarlo: llega con
|
||||
[`pagetop-user`](users.md), que lo necesita para administrar usuarios y roles. Tu extensión sólo
|
||||
**declara** sus páginas, y el panel las coloca en su sección, las enlaza desde el inicio del panel
|
||||
(*dashboard*) y las muestra sólo a quien tenga permiso.
|
||||
El panel es de PageTop: las páginas se **declaran** con acciones, y el panel las coloca en su
|
||||
sección, las enlaza desde su página de inicio (*dashboard*) y las muestra sólo a quien tenga
|
||||
permiso. Los permisos los concede [`pagetop-user`](users.md), que además declara en el panel la
|
||||
gestión de usuarios y roles. Los formularios de ajustes que se guardan en la base de datos los
|
||||
aporta `pagetop-admin`.
|
||||
|
||||
## 1. Añade la dependencia
|
||||
|
||||
|
|
@ -17,8 +18,9 @@ pagetop-user = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
|||
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop", features = ["sqlite"] }
|
||||
```
|
||||
|
||||
Tu extensión sigue dependiendo sólo de `pagetop_user::User`, como en [Añadir usuarios y
|
||||
permisos](users.md); el *crate* `pagetop-admin` hace falta para usar sus tipos.
|
||||
Tu extensión depende de `pagetop_user::User`, como en [Añadir usuarios y permisos](users.md), y de
|
||||
`pagetop_admin::Admin`, que monta las páginas de ajustes. Una extensión que sólo aporte páginas
|
||||
propias, sin ajustes, no necesita `pagetop-admin`.
|
||||
|
||||
Ese es el `Cargo.toml` de la **aplicación**, la única que elige el motor de base de datos (aquí
|
||||
SQLite) para todas sus extensiones. Si escribes una extensión aparte, declara `pagetop-admin` y
|
||||
|
|
@ -61,15 +63,15 @@ impl Permission for GardenPermission {
|
|||
}
|
||||
```
|
||||
|
||||
Regístralo con `DeclarePermissions` para que aparezca en la pantalla de roles (lo verás en el
|
||||
Decláralo con `DeclarePermissions` para que aparezca en la pantalla de roles (lo verás en el
|
||||
ejemplo completo).
|
||||
|
||||
## 3. Deja que el panel construya tus ajustes
|
||||
|
||||
Para una página de ajustes no necesitas ni *handler* ni ruta. Describe los campos con un
|
||||
`SettingsSchema` y declara la página con `AdminPageKind::ConfigForm`. El panel registra la ruta,
|
||||
pinta el formulario con los valores actuales, comprueba que llegan los obligatorios y guarda lo
|
||||
que se envía:
|
||||
`SettingsSchema` y declara la página junto a su esquema con la acción `DeclareConfigForms` de
|
||||
`pagetop-admin`. El panel registra la ruta, pinta el formulario con los valores actuales y guarda
|
||||
lo que se envía, salvo que falte algún campo obligatorio o llegue vacío:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
|
|
@ -82,32 +84,38 @@ que se envía:
|
|||
fn garden_settings() -> SettingsSchema {
|
||||
SettingsSchema::new("garden")
|
||||
.with_field(
|
||||
SettingField::text("notice", "Notice for the gardeners")
|
||||
.with_help("Shown on the home page. Leave it empty to hide it."),
|
||||
SettingField::text("notice", Lc::n("Notice for the gardeners"))
|
||||
.with_help(Lc::n("Shown on the home page. Leave it empty to hide it.")),
|
||||
)
|
||||
.with_field(SettingField::number("plots", "Number of plots").with_required(true))
|
||||
.with_field(SettingField::boolean("open", "Open to new gardeners"))
|
||||
.with_field(SettingField::number("plots", Lc::n("Number of plots")).with_required(true))
|
||||
.with_field(SettingField::boolean("open", Lc::n("Open to new gardeners")))
|
||||
}
|
||||
|
||||
fn declare_pages(bag: &mut PageBag) {
|
||||
bag.add(AdminPage {
|
||||
path: "/admin/config/garden".to_owned(),
|
||||
section: "config".to_owned(),
|
||||
title: Lc::n("Garden"),
|
||||
description: Some(Lc::n("Notice, plots and new gardeners.")),
|
||||
weight: 0,
|
||||
permission: &GardenPermission::Configure,
|
||||
kind: AdminPageKind::ConfigForm(garden_settings()),
|
||||
fn declare_forms(bag: &mut ConfigFormBag) {
|
||||
bag.add(ConfigFormPage {
|
||||
page: AdminPage::new(
|
||||
"config/garden",
|
||||
"config",
|
||||
Lc::n("Garden"),
|
||||
&GardenPermission::Configure,
|
||||
)
|
||||
.with_description(Lc::n("Notice, plots and new gardeners.")),
|
||||
schema: garden_settings(),
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Regístrala en tu extensión con `actions![DeclareConfigForms::new(declare_forms)]`.
|
||||
|
||||
Los campos pueden ser `text`, `number`, `boolean` o `select` (con sus opciones), y admiten
|
||||
`with_required()`, `with_help()` y `with_default()`.
|
||||
`with_required()`, `with_help()` y `with_default()`. Las etiquetas, la ayuda y las opciones son
|
||||
`Lc`, como cualquier texto visible: con `Lc::t()` salen traducidas al idioma de quien administra.
|
||||
|
||||
Las páginas se agrupan en las secciones del panel: `people` (personas), `structure` (estructura),
|
||||
`config` (configuración), `reports` (informes) y `help` (ayuda). El campo `path` es la ruta de la
|
||||
página, que suele colgar de la de su sección (`/admin/config/...`).
|
||||
`config` (configuración), `reports` (informes) y `help` (ayuda). El primer argumento de
|
||||
`AdminPage::new()` es la ruta de la página **relativa a la raíz del panel**, que suele colgar de la
|
||||
de su sección: `"config/garden"` es `/admin/config/garden` con la raíz por defecto (el ajuste
|
||||
[`admin_path`](../reference/configuration.md) de `[app]`).
|
||||
|
||||
## 4. Lee los ajustes guardados
|
||||
|
||||
|
|
@ -141,54 +149,58 @@ El formulario guarda todos los valores **como texto**, también los números y l
|
|||
|
||||
## 5. Añade una página con tu propio contenido
|
||||
|
||||
Cuando la página no es un formulario de ajustes, declárala con `AdminPageKind::View` y registra tú
|
||||
la ruta. El *handler* crea la página con `Page::admin()` y envuelve el contenido en un
|
||||
`AdminFrame`, que añade la ruta de migas, el título y las pestañas y botones del panel:
|
||||
Cuando la página no es un formulario de ajustes, declárala con la acción `DeclareAdminPages` y
|
||||
registra tú su ruta con `routes.admin_route()`. El *handler* crea la página con
|
||||
`Page::admin()`, le da título y añade su contenido. La plantilla de administración añade el resto:
|
||||
la navegación del panel, la ruta de migas, el título y las pestañas y botones de la página:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_admin::prelude::*;
|
||||
# #[derive(Clone, Copy, Debug)]
|
||||
# enum GardenPermission { SeeHarvest }
|
||||
# impl Permission for GardenPermission {
|
||||
# fn key(&self) -> CowStr { "garden.see_harvest".into() }
|
||||
# }
|
||||
fn declare_report(bag: &mut PageBag) {
|
||||
bag.add(AdminPage {
|
||||
path: "/admin/reports/harvest".to_owned(),
|
||||
section: "reports".to_owned(),
|
||||
title: Lc::n("Harvest"),
|
||||
description: Some(Lc::n("Kilos harvested by crop.")),
|
||||
weight: 0,
|
||||
permission: &GardenPermission::SeeHarvest,
|
||||
kind: AdminPageKind::View,
|
||||
});
|
||||
fn declare_report(bag: &mut AdminPageBag) {
|
||||
bag.add(
|
||||
AdminPage::new(
|
||||
"reports/harvest",
|
||||
"reports",
|
||||
Lc::n("Harvest"),
|
||||
&GardenPermission::SeeHarvest,
|
||||
)
|
||||
.with_description(Lc::n("Kilos harvested by crop.")),
|
||||
);
|
||||
}
|
||||
|
||||
async fn harvest(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
require_permission(&request, &GardenPermission::SeeHarvest)?;
|
||||
|
||||
let rows = [("Tomatoes", 42), ("Lettuces", 18), ("Courgettes", 27)];
|
||||
Page::admin(request)
|
||||
.with_title(Lc::n("Harvest"))
|
||||
.with_child(
|
||||
AdminFrame::new().with_title(Lc::n("Harvest")).with_child(Html::with(move |_| {
|
||||
html! {
|
||||
ul {
|
||||
@for (crop, kilos) in rows {
|
||||
li { (crop) ": " (kilos) " kg" }
|
||||
}
|
||||
.with_child(Html::with(move |_| {
|
||||
html! {
|
||||
ul {
|
||||
@for (crop, kilos) in rows {
|
||||
li { (crop) ": " (kilos) " kg" }
|
||||
}
|
||||
}
|
||||
})),
|
||||
)
|
||||
}
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
Declarar la página no protege la ruta: el `require_permission()` del principio sigue haciendo
|
||||
falta, porque cualquiera puede escribir la URL.
|
||||
La ruta se monta en `configure_router()` con `routes.admin_route("reports/harvest",
|
||||
web::get(harvest))`, relativa a la raíz del panel como la página. No lleva permiso: exige el de la
|
||||
página de la que cuelga, que se declara sólo una vez, en la página. PageTop lo comprueba antes de
|
||||
llegar a `harvest()`, así que el *handler* no tiene que hacerlo.
|
||||
|
||||
Una ruta cuelga de la página más cercana que se encuentra quitándole tramos por el final:
|
||||
`reports/harvest/{year}` cuelga de `reports/harvest` y exige su mismo permiso. Una ruta del panel
|
||||
que no cuelgue de ninguna página, o que se monte con `routes.route()` en vez de con
|
||||
`admin_route()`, impide arrancar la aplicación. Sólo hace falta `require_permission()` para un
|
||||
permiso más concreto que el de la página, como el de una acción que no todos pueden hacer.
|
||||
|
||||
## 6. Crea una sección propia (opcional)
|
||||
|
||||
|
|
@ -197,27 +209,21 @@ cuanto tenga alguna página que el usuario pueda abrir:
|
|||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# use pagetop_admin::prelude::*;
|
||||
fn declare_sections(bag: &mut SectionBag) {
|
||||
bag.add(AdminSection {
|
||||
key: "garden".to_owned(),
|
||||
path: "/admin/garden".to_owned(),
|
||||
title: Lc::n("Garden"),
|
||||
weight: 25,
|
||||
});
|
||||
fn declare_sections(bag: &mut AdminSectionBag) {
|
||||
bag.add(AdminSection::new("garden", Lc::n("Garden")).with_weight(25));
|
||||
}
|
||||
```
|
||||
|
||||
Regístrala junto a las páginas: `actions![DeclareAdminSections::new(declare_sections), ...]`. El
|
||||
peso decide su posición entre las demás (las de serie usan 10, 20, 30...). Con
|
||||
`DeclareAdminTasks` y `DeclareAdminActions` puedes añadir también pestañas y botones a una página.
|
||||
Regístrala junto a las páginas:
|
||||
`actions![action::admin::DeclareAdminSections::new(declare_sections), ...]`. El peso decide su
|
||||
posición entre las demás (las de serie usan 10, 20, 30...). Con `DeclareAdminTasks` y
|
||||
`DeclareAdminActions` puedes añadir también pestañas y botones a una página.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_admin::prelude::*;
|
||||
use pagetop_user::PermissionRegistry;
|
||||
use pagetop_user::prelude::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
|
|
@ -258,46 +264,51 @@ fn declare_permissions(registry: &mut PermissionRegistry) {
|
|||
fn garden_settings() -> SettingsSchema {
|
||||
SettingsSchema::new("garden")
|
||||
.with_field(
|
||||
SettingField::text("notice", "Notice for the gardeners")
|
||||
.with_help("Shown on the home page. Leave it empty to hide it."),
|
||||
SettingField::text("notice", Lc::n("Notice for the gardeners"))
|
||||
.with_help(Lc::n("Shown on the home page. Leave it empty to hide it.")),
|
||||
)
|
||||
.with_field(SettingField::number("plots", "Number of plots").with_required(true))
|
||||
.with_field(SettingField::boolean("open", "Open to new gardeners"))
|
||||
.with_field(SettingField::number("plots", Lc::n("Number of plots")).with_required(true))
|
||||
.with_field(SettingField::boolean("open", Lc::n("Open to new gardeners")))
|
||||
}
|
||||
|
||||
fn declare_pages(bag: &mut PageBag) {
|
||||
bag.add(AdminPage {
|
||||
path: "/admin/config/garden".to_owned(),
|
||||
section: "config".to_owned(),
|
||||
title: Lc::n("Garden"),
|
||||
description: Some(Lc::n("Notice, plots and new gardeners.")),
|
||||
weight: 0,
|
||||
permission: &GardenPermission::Configure,
|
||||
kind: AdminPageKind::ConfigForm(garden_settings()),
|
||||
});
|
||||
bag.add(AdminPage {
|
||||
path: "/admin/reports/harvest".to_owned(),
|
||||
section: "reports".to_owned(),
|
||||
title: Lc::n("Harvest"),
|
||||
description: Some(Lc::n("Kilos harvested by crop.")),
|
||||
weight: 0,
|
||||
permission: &GardenPermission::SeeHarvest,
|
||||
kind: AdminPageKind::View,
|
||||
fn declare_forms(bag: &mut ConfigFormBag) {
|
||||
bag.add(ConfigFormPage {
|
||||
page: AdminPage::new(
|
||||
"config/garden",
|
||||
"config",
|
||||
Lc::n("Garden"),
|
||||
&GardenPermission::Configure,
|
||||
)
|
||||
.with_description(Lc::n("Notice, plots and new gardeners.")),
|
||||
schema: garden_settings(),
|
||||
});
|
||||
}
|
||||
|
||||
fn declare_pages(bag: &mut AdminPageBag) {
|
||||
bag.add(
|
||||
AdminPage::new(
|
||||
"reports/harvest",
|
||||
"reports",
|
||||
Lc::n("Harvest"),
|
||||
&GardenPermission::SeeHarvest,
|
||||
)
|
||||
.with_description(Lc::n("Kilos harvested by crop.")),
|
||||
);
|
||||
}
|
||||
|
||||
struct Garden;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Garden {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_user::User]
|
||||
vec![&pagetop_user::User, &pagetop_admin::Admin]
|
||||
}
|
||||
|
||||
fn actions(&self) -> Vec<ActionBox> {
|
||||
actions![
|
||||
DeclarePermissions::new(declare_permissions),
|
||||
DeclareAdminPages::new(declare_pages),
|
||||
action::auth::DeclarePermissions::new(declare_permissions),
|
||||
DeclareConfigForms::new(declare_forms),
|
||||
action::admin::DeclareAdminPages::new(declare_pages),
|
||||
]
|
||||
}
|
||||
|
||||
|
|
@ -306,10 +317,10 @@ impl Extension for Garden {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
fn configure_router(&self, router: Router) -> Router {
|
||||
router
|
||||
.route("/", web::get(home))
|
||||
.route("/admin/reports/harvest", web::get(harvest))
|
||||
fn configure_router(&self, routes: Routes) -> Routes {
|
||||
routes
|
||||
.public_route("/", web::get(home))
|
||||
.admin_route("reports/harvest", web::get(harvest))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -352,22 +363,18 @@ async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
|||
}
|
||||
|
||||
async fn harvest(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
require_permission(&request, &GardenPermission::SeeHarvest)?;
|
||||
|
||||
let rows = [("Tomatoes", 42), ("Lettuces", 18), ("Courgettes", 27)];
|
||||
Page::admin(request)
|
||||
.with_title(Lc::n("Harvest"))
|
||||
.with_child(
|
||||
AdminFrame::new().with_title(Lc::n("Harvest")).with_child(Html::with(move |_| {
|
||||
html! {
|
||||
ul {
|
||||
@for (crop, kilos) in rows {
|
||||
li { (crop) ": " (kilos) " kg" }
|
||||
}
|
||||
.with_child(Html::with(move |_| {
|
||||
html! {
|
||||
ul {
|
||||
@for (crop, kilos) in rows {
|
||||
li { (crop) ": " (kilos) " kg" }
|
||||
}
|
||||
}
|
||||
})),
|
||||
)
|
||||
}
|
||||
}))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
|
@ -383,8 +390,8 @@ permisos](users.md#2-configura-la-base-de-datos-y-el-primer-administrador).
|
|||
|
||||
## Comprueba
|
||||
|
||||
1. Sin iniciar sesión, <http://localhost:8080/admin/reports/harvest> responde con la página de
|
||||
acceso denegado (403).
|
||||
1. Sin iniciar sesión, <http://localhost:8080/admin/reports/harvest> te lleva al formulario de
|
||||
inicio de sesión.
|
||||
2. Inicia sesión como `admin` y entra en **Administración** desde el menú de cuenta. El inicio del
|
||||
panel muestra «Garden» en Configuración y «Harvest» en Informes.
|
||||
3. Abre «Garden», escribe un aviso, marca «Open to new gardeners» y guarda. La portada muestra el
|
||||
|
|
@ -397,4 +404,5 @@ permisos](users.md#2-configura-la-base-de-datos-y-el-primer-administrador).
|
|||
- [Añadir usuarios y permisos](users.md): roles, permisos y el menú de cuenta.
|
||||
- [Extensiones oficiales](../reference/extensions.md#administración): lo que aporta
|
||||
`pagetop-admin`.
|
||||
- [Intervenir con acciones](actions.md): `DeclareAdminPages` y compañía son acciones.
|
||||
- [Intervenir con acciones](actions.md): `DeclareAdminPages`, `DeclareConfigForms` y compañía son
|
||||
acciones.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue