✨ 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.
This commit is contained in:
parent
e41e71cc78
commit
1a41a456d4
80 changed files with 14112 additions and 1218 deletions
351
doc/v0.6/es/src/how-to/users.md
Normal file
351
doc/v0.6/es/src/how-to/users.md
Normal file
|
|
@ -0,0 +1,351 @@
|
|||
# Añadir usuarios y permisos
|
||||
|
||||
**Objetivo:** que los visitantes puedan iniciar sesión y que algunas páginas o acciones sólo estén
|
||||
al alcance de quien tenga el permiso adecuado.
|
||||
|
||||
La extensión `pagetop-user` aporta las cuentas, el inicio de sesión, las sesiones (guardadas en la
|
||||
base de datos), las contraseñas cifradas con Argon2 y el control de acceso por roles, con su
|
||||
interfaz de administración en `/admin`. Necesita una base de datos: mira antes [Conectar una base
|
||||
de datos](database.md).
|
||||
|
||||
## 1. Añade la extensión
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
pagetop-user = { git = "https://git.cillero.es/manuelcillero/pagetop" }
|
||||
pagetop-seaorm = { git = "https://git.cillero.es/manuelcillero/pagetop", features = ["sqlite"] }
|
||||
```
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
pub struct Board;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Board {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_user::User]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`User` declara por su cuenta lo que necesita: `pagetop-seaorm`, `pagetop-htmx` y el panel
|
||||
`pagetop-admin`. Al arrancar crea sus tablas y registra sus rutas, entre ellas `/user/login`,
|
||||
`/user/register` y `/user` (el perfil).
|
||||
|
||||
## 2. Configura la base de datos y el primer administrador
|
||||
|
||||
```toml
|
||||
# config/common.toml
|
||||
[database]
|
||||
db_type = "sqlite"
|
||||
db_name = "board.db?mode=rwc"
|
||||
```
|
||||
|
||||
```toml
|
||||
# config/local.toml (not versioned)
|
||||
[user.seed]
|
||||
admin_password = "choose-a-long-one"
|
||||
```
|
||||
|
||||
Con la base de datos vacía, el primer arranque crea la cuenta `admin` con esa contraseña. Si no la
|
||||
indicas, genera una aleatoria y la muestra **una sola vez** en el terminal:
|
||||
|
||||
```text
|
||||
pagetop-user: admin account created.
|
||||
username: admin
|
||||
password: ...
|
||||
```
|
||||
|
||||
Las demás opciones (registro abierto, bloqueo tras intentos fallidos, duración de las sesiones...)
|
||||
están en la [referencia de configuración](../reference/configuration.md#user).
|
||||
|
||||
## 3. Pon el menú de cuenta en la cabecera
|
||||
|
||||
`account_menu(cx)` construye el menú: «Iniciar sesión» para los anónimos, y el nombre del usuario
|
||||
con su perfil, la administración (si tiene acceso) y «Cerrar sesión» para los demás. Depende de
|
||||
quién pide la página, así que se construye al renderizar, dentro de un componente:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
use pagetop_user::prelude::*;
|
||||
|
||||
#[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("Garden board"))
|
||||
.with_route(Route::from("/"));
|
||||
Ok(Navbar::brand_left(brand)
|
||||
.with_item(navbar::Item::nav(account_menu(cx)))
|
||||
.render(cx)
|
||||
.await)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Regístralo una vez en `initialize()`, para todas las páginas:
|
||||
|
||||
```rust,ignore
|
||||
InRegion::Global(&CoreRegions::Header).add(TopBar::new());
|
||||
```
|
||||
|
||||
## 4. Define tus permisos
|
||||
|
||||
Un permiso es un valor de un `enum` propio con una clave única. Su nombre y su grupo son los que
|
||||
verá el administrador al asignarlo:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum BoardPermission {
|
||||
PostNotices,
|
||||
}
|
||||
|
||||
impl Permission for BoardPermission {
|
||||
fn key(&self) -> CowStr {
|
||||
match self {
|
||||
Self::PostNotices => "board.post_notices".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn label(&self) -> Lc {
|
||||
Lc::n("Post notices on the board")
|
||||
}
|
||||
|
||||
fn group(&self) -> &'static str {
|
||||
"board"
|
||||
}
|
||||
|
||||
fn group_label(&self) -> Lc {
|
||||
Lc::n("Garden board")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Para que aparezca en la pantalla de roles, regístralo con la acción `DeclarePermissions`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# #[derive(Clone, Copy, Debug)]
|
||||
# enum BoardPermission { PostNotices }
|
||||
# impl Permission for BoardPermission {
|
||||
# fn key(&self) -> CowStr { "board.post_notices".into() }
|
||||
# }
|
||||
use pagetop_user::PermissionRegistry;
|
||||
use pagetop_user::prelude::*;
|
||||
|
||||
fn declare_permissions(registry: &mut PermissionRegistry) {
|
||||
registry.register(&BoardPermission::PostNotices);
|
||||
}
|
||||
|
||||
pub struct Board;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Board {
|
||||
fn actions(&self) -> Vec<ActionBox> {
|
||||
actions![DeclarePermissions::new(declare_permissions)]
|
||||
}
|
||||
|
||||
// ... dependencies(), initialize() and configure_router() ...
|
||||
}
|
||||
```
|
||||
|
||||
## 5. Protege rutas y adapta la interfaz
|
||||
|
||||
`require_permission()` corta la petición con un error 403 si falta el permiso. Va al principio del
|
||||
*handler*, con `?`:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# #[derive(Clone, Copy, Debug)]
|
||||
# enum BoardPermission { PostNotices }
|
||||
# impl Permission for BoardPermission {
|
||||
# fn key(&self) -> CowStr { "board.post_notices".into() }
|
||||
# }
|
||||
async fn new_notice(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
require_permission(&request, &BoardPermission::PostNotices)?;
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("New notice"))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
```
|
||||
|
||||
`has_permission()` devuelve un `bool`, para mostrar u ocultar lo que no se puede usar:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# #[derive(Clone, Copy, Debug)]
|
||||
# enum BoardPermission { PostNotices }
|
||||
# impl Permission for BoardPermission {
|
||||
# fn key(&self) -> CowStr { "board.post_notices".into() }
|
||||
# }
|
||||
async fn board(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let can_post = has_permission(&request, &BoardPermission::PostNotices);
|
||||
let mut page = Page::new(request)
|
||||
.with_title(Lc::n("Garden board"))
|
||||
.with_child(Html::with(|_| html! { p { "The water tank is full." } }));
|
||||
if can_post {
|
||||
page = page.with_child(Button::anchor(Lc::n("Post a notice"), "/notices/new"));
|
||||
}
|
||||
page.render().await
|
||||
}
|
||||
```
|
||||
|
||||
Y dentro de un componente, `cx.current_user()` dice quién está viendo la página:
|
||||
|
||||
```rust,no_run
|
||||
# use pagetop::prelude::*;
|
||||
# fn f() -> Html {
|
||||
Html::with(|cx| {
|
||||
let user = cx.current_user();
|
||||
html! {
|
||||
@if let Some(name) = user.display_name() {
|
||||
p { "Hello, " (name) "." }
|
||||
}
|
||||
}
|
||||
})
|
||||
# }
|
||||
```
|
||||
|
||||
Ocultar el botón no basta: la ruta debe comprobar el permiso igualmente, porque cualquiera puede
|
||||
escribir la URL.
|
||||
|
||||
## 6. Asigna el permiso
|
||||
|
||||
Inicia sesión como `admin` y entra en **Administración** desde el menú de cuenta. En la lista de
|
||||
roles, abre los permisos de uno de ellos: verás el grupo «Garden board» con su permiso. Puedes
|
||||
concederlo:
|
||||
|
||||
- al rol **authenticated**, para todos los usuarios que inicien sesión;
|
||||
- o a un rol nuevo («Gardeners», por ejemplo), y asignar ese rol a las cuentas que quieras.
|
||||
|
||||
Los administradores tienen todos los permisos sin necesidad de asignarlos.
|
||||
|
||||
## El ejemplo completo
|
||||
|
||||
```rust,no_run
|
||||
use pagetop::prelude::*;
|
||||
use pagetop_user::PermissionRegistry;
|
||||
use pagetop_user::prelude::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum BoardPermission {
|
||||
PostNotices,
|
||||
}
|
||||
|
||||
impl Permission for BoardPermission {
|
||||
fn key(&self) -> CowStr {
|
||||
match self {
|
||||
Self::PostNotices => "board.post_notices".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn label(&self) -> Lc {
|
||||
Lc::n("Post notices on the board")
|
||||
}
|
||||
|
||||
fn group(&self) -> &'static str {
|
||||
"board"
|
||||
}
|
||||
|
||||
fn group_label(&self) -> Lc {
|
||||
Lc::n("Garden board")
|
||||
}
|
||||
}
|
||||
|
||||
fn declare_permissions(registry: &mut PermissionRegistry) {
|
||||
registry.register(&BoardPermission::PostNotices);
|
||||
}
|
||||
|
||||
struct Board;
|
||||
|
||||
#[async_trait]
|
||||
impl Extension for Board {
|
||||
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||
vec![&pagetop_user::User]
|
||||
}
|
||||
|
||||
fn actions(&self) -> Vec<ActionBox> {
|
||||
actions![DeclarePermissions::new(declare_permissions)]
|
||||
}
|
||||
|
||||
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(board))
|
||||
.route("/notices/new", web::get(new_notice))
|
||||
}
|
||||
}
|
||||
|
||||
#[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("Garden board"))
|
||||
.with_route(Route::from("/"));
|
||||
Ok(Navbar::brand_left(brand)
|
||||
.with_item(navbar::Item::nav(account_menu(cx)))
|
||||
.render(cx)
|
||||
.await)
|
||||
}
|
||||
}
|
||||
|
||||
async fn board(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
let can_post = has_permission(&request, &BoardPermission::PostNotices);
|
||||
let mut page = Page::new(request)
|
||||
.with_title(Lc::n("Garden board"))
|
||||
.with_child(Html::with(|_| html! { p { "The water tank is full." } }));
|
||||
if can_post {
|
||||
page = page.with_child(Button::anchor(Lc::n("Post a notice"), "/notices/new"));
|
||||
}
|
||||
page.render().await
|
||||
}
|
||||
|
||||
async fn new_notice(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||
require_permission(&request, &BoardPermission::PostNotices)?;
|
||||
Page::new(request)
|
||||
.with_title(Lc::n("New notice"))
|
||||
.with_child(Html::with(|_| html! { p { "Write your notice here." } }))
|
||||
.render()
|
||||
.await
|
||||
}
|
||||
|
||||
#[pagetop::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
Application::prepare(&Board).await.run().await
|
||||
}
|
||||
```
|
||||
|
||||
## Comprueba
|
||||
|
||||
1. Sin iniciar sesión, la portada no muestra *Post a notice*, y <http://localhost:8080/notices/new>
|
||||
responde con la página de acceso denegado (403).
|
||||
2. Inicia sesión como `admin`: aparece el botón y la página se abre.
|
||||
3. Crea una cuenta con el enlace «Crear una cuenta» del menú, concede el permiso al rol
|
||||
**authenticated** e inicia sesión con ella: también puede publicar.
|
||||
|
||||
## Siguiente
|
||||
|
||||
- [Opciones de configuración](../reference/configuration.md#user): registro, sesiones y
|
||||
contraseñas.
|
||||
- [Extensiones oficiales](../reference/extensions.md): lo que aportan `pagetop-user` y
|
||||
`pagetop-admin`.
|
||||
Loading…
Add table
Add a link
Reference in a new issue