pagetop-website/doc/v0.6/es/src/how-to/admin.md
Manuel Cillero 1a41a456d4 ✨ Serve the PageTop guides with pagetop-mdbook
Rebuild the website on the current PageTop API, with Bootsier as its
theme and edition 2024. Add the first Spanish guide (doc/v0.6/es) as an
mdBook book, built in build.rs and served with pagetop-mdbook, and the
/doc/latest/{lang} redirect.

Add `tools/doccheck.sh` to check the links of the guides and to compile,
run and test their examples against PageTop.

Move the configuration to config/common.toml and translate the README
to English.
2026-10-17 08:06:02 +02:00

400 lines
13 KiB
Markdown

# Añadir páginas al panel de administración
**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.
## 1. Añade la dependencia
```toml
[dependencies]
pagetop-admin = { git = "https://git.cillero.es/manuelcillero/pagetop" }
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.
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
`pagetop-user` igual, pero sin `pagetop-seaorm` (ve [Elige el motor](database.md#1-elige-el-motor)).
## 2. Define el permiso de cada página
Cada página del panel exige un permiso. Decláralo como cualquier otro:
```rust,no_run
# use pagetop::prelude::*;
#[derive(Clone, Copy, Debug)]
enum GardenPermission {
Configure,
SeeHarvest,
}
impl Permission for GardenPermission {
fn key(&self) -> CowStr {
match self {
Self::Configure => "garden.configure".into(),
Self::SeeHarvest => "garden.see_harvest".into(),
}
}
fn label(&self) -> Lc {
match self {
Self::Configure => Lc::n("Configure the garden"),
Self::SeeHarvest => Lc::n("See the harvest report"),
}
}
fn group(&self) -> &'static str {
"garden"
}
fn group_label(&self) -> Lc {
Lc::n("Community garden")
}
}
```
Regístralo 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:
```rust,no_run
# use pagetop::prelude::*;
# use pagetop_admin::prelude::*;
# #[derive(Clone, Copy, Debug)]
# enum GardenPermission { Configure }
# impl Permission for GardenPermission {
# fn key(&self) -> CowStr { "garden.configure".into() }
# }
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."),
)
.with_field(SettingField::number("plots", "Number of plots").with_required(true))
.with_field(SettingField::boolean("open", "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()),
});
}
```
Los campos pueden ser `text`, `number`, `boolean` o `select` (con sus opciones), y admiten
`with_required()`, `with_help()` y `with_default()`.
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/...`).
## 4. Lee los ajustes guardados
Cada campo se guarda con la clave `<ámbito>.<campo>`: aquí, `garden.notice`, `garden.plots` y
`garden.open`. Léelos con `pagetop_admin::settings::get_or()`, con el valor que quieras mientras
nadie los haya guardado:
```rust,no_run
# use pagetop::prelude::*;
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
let notice: String = pagetop_admin::settings::get_or("garden.notice", String::new()).await;
let open = pagetop_admin::settings::get_or("garden.open", String::new()).await == "true";
Page::new(request)
.with_title(Lc::n("Community garden"))
.with_child(Html::with(move |_| {
html! {
@if !notice.is_empty() {
p class="garden-notice" { (notice) }
}
p { @if open { "We are open to new gardeners." } @else { "No free plots now." } }
}
}))
.render()
.await
}
```
El formulario guarda todos los valores **como texto**, también los números y las casillas
(`"true"` o `"false"`): conviértelos al leerlos.
## 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:
```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,
});
}
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" }
}
}
}
})),
)
.render()
.await
}
```
Declarar la página no protege la ruta: el `require_permission()` del principio sigue haciendo
falta, porque cualquiera puede escribir la URL.
## 6. Crea una sección propia (opcional)
Si ninguna sección encaja, declara la tuya con `DeclareAdminSections`. Aparece en el panel en
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,
});
}
```
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.
## 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)]
enum GardenPermission {
Configure,
SeeHarvest,
}
impl Permission for GardenPermission {
fn key(&self) -> CowStr {
match self {
Self::Configure => "garden.configure".into(),
Self::SeeHarvest => "garden.see_harvest".into(),
}
}
fn label(&self) -> Lc {
match self {
Self::Configure => Lc::n("Configure the garden"),
Self::SeeHarvest => Lc::n("See the harvest report"),
}
}
fn group(&self) -> &'static str {
"garden"
}
fn group_label(&self) -> Lc {
Lc::n("Community garden")
}
}
fn declare_permissions(registry: &mut PermissionRegistry) {
registry.register(&GardenPermission::Configure);
registry.register(&GardenPermission::SeeHarvest);
}
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."),
)
.with_field(SettingField::number("plots", "Number of plots").with_required(true))
.with_field(SettingField::boolean("open", "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,
});
}
struct Garden;
#[async_trait]
impl Extension for Garden {
fn dependencies(&self) -> Vec<ExtensionRef> {
vec![&pagetop_user::User]
}
fn actions(&self) -> Vec<ActionBox> {
actions![
DeclarePermissions::new(declare_permissions),
DeclareAdminPages::new(declare_pages),
]
}
async fn initialize(&self) -> Result<(), BoxError> {
InRegion::Global(&CoreRegions::Header).add(TopBar::new());
Ok(())
}
fn configure_router(&self, router: Router) -> Router {
router
.route("/", web::get(home))
.route("/admin/reports/harvest", web::get(harvest))
}
}
#[derive(AutoDefault, Clone, Debug)]
struct TopBar;
#[async_trait]
impl Component for TopBar {
fn new() -> Self {
Self
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let brand = Brand::new()
.with_title(Lc::n("Community garden"))
.with_route(Route::from("/"));
Ok(Navbar::brand_left(brand)
.with_item(navbar::Item::nav(account_menu(cx)))
.render(cx)
.await)
}
}
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
let notice: String = pagetop_admin::settings::get_or("garden.notice", String::new()).await;
let open = pagetop_admin::settings::get_or("garden.open", String::new()).await == "true";
Page::new(request)
.with_title(Lc::n("Community garden"))
.with_child(Html::with(move |_| {
html! {
@if !notice.is_empty() {
p class="garden-notice" { (notice) }
}
p { @if open { "We are open to new gardeners." } @else { "No free plots now." } }
}
}))
.render()
.await
}
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" }
}
}
}
})),
)
.render()
.await
}
#[pagetop::main]
async fn main() -> std::io::Result<()> {
Application::prepare(&Garden).await.run().await
}
```
Usa la misma configuración de base de datos y del administrador que en [Añadir usuarios y
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).
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
aviso y «We are open to new gardeners.».
4. En la pantalla de roles aparece el grupo «Community garden» con sus dos permisos. Concede «See
the harvest report» a otro rol: sus usuarios verán el informe, pero no los ajustes.
## Siguiente
- [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.