Compare commits

..

2 commits

Author SHA1 Message Date
c940403869 ✨ (base): Oculta separadores en menús sin opciones
`Dropdown::items()` devuelve `dropdown::Items`, cuyo `render()` sólo
pinta un encabezado si su grupo tiene algún elemento visible, y un
separador sólo entre elementos visibles. Lo aprovecha cualquier tema
que pinte el menú con `items().render()`.
2026-11-08 10:11:42 +01:00
e2e2ccb31e ✨ (pagetop): Oculta enlaces sin acceso con Endpoint
Las rutas se declaran con su acceso en un enum que implementa Endpoint y
se montan con `routes.endpoint()`. Convertidas en Route, `nav::Item`,
`dropdown::Item` y `Button::anchor()` no se muestran a quien no cumple
el acceso, sin repetir el permiso. `to()` rellena el parámetro de la
ruta.
2026-11-08 08:56:57 +01:00
20 changed files with 967 additions and 18 deletions

View file

@ -15,7 +15,7 @@ mod props;
pub use props::{AutoClose, Direction, MenuAlign, MenuPosition}; pub use props::{AutoClose, Direction, MenuAlign, MenuPosition};
pub use pagetop::base::component::Dropdown; pub use pagetop::base::component::Dropdown;
pub use pagetop::base::component::dropdown::{Item, ItemKind}; pub use pagetop::base::component::dropdown::{Item, ItemKind, Items};
const EXTRA_BUTTON_GROUPED: &str = "bootsier.dropdown.button_grouped"; const EXTRA_BUTTON_GROUPED: &str = "bootsier.dropdown.button_grouped";
const EXTRA_AUTO_CLOSE: &str = "bootsier.dropdown.auto_close"; const EXTRA_AUTO_CLOSE: &str = "bootsier.dropdown.auto_close";

View file

@ -0,0 +1,143 @@
// Verifies that the links to a route declared with `Endpoint` are hidden as well in the menus and
// buttons that the theme renders on its own.
use pagetop::prelude::*;
use pagetop_bootsier::theme::*;
struct Granted;
impl Permission for Granted {
fn key(&self) -> CowStr {
"test:granted".into()
}
}
struct Denied;
impl Permission for Denied {
fn key(&self) -> CowStr {
"test:denied".into()
}
}
fn grant(_: &HttpRequest, perm: PermissionRef, granted: &mut bool) {
if perm.key() == "test:granted" {
*granted = true;
}
}
#[derive(Clone, Copy)]
enum TestRoute {
Allowed,
Forbidden,
}
impl Endpoint for TestRoute {
fn path(&self) -> CowStr {
match self {
Self::Allowed => "/allowed".into(),
Self::Forbidden => "/forbidden".into(),
}
}
fn access(&self) -> Access {
match self {
Self::Allowed => Access::Permission(&Granted),
Self::Forbidden => Access::Permission(&Denied),
}
}
}
fn menu() -> Nav {
Nav::new()
.with_item(bs::nav::Item::link(
Lc::n("nav-allowed"),
TestRoute::Allowed,
))
.with_item(bs::nav::Item::link(
Lc::n("nav-forbidden"),
TestRoute::Forbidden,
))
.with_item(bs::nav::Item::dropdown(
Dropdown::new()
.with_title(Lc::n("dropdown-empty"))
.with_item(dropdown::Item::link(Lc::n("x"), TestRoute::Forbidden)),
))
.with_item(bs::nav::Item::dropdown(
Dropdown::new()
.with_title(Lc::n("dropdown-partial"))
.with_item(dropdown::Item::header(Lc::n("header-empty")))
.with_item(dropdown::Item::link(Lc::n("x"), TestRoute::Forbidden))
.with_item(dropdown::Item::divider())
.with_item(dropdown::Item::link(
Lc::n("in-allowed"),
TestRoute::Allowed,
))
.with_item(dropdown::Item::link(
Lc::n("in-forbidden"),
TestRoute::Forbidden,
)),
))
}
struct Ext;
#[async_trait]
impl Extension for Ext {
fn actions(&self) -> Vec<ActionBox> {
actions![action::auth::CheckPermission::new(grant)]
}
}
async fn render(mut component: impl Component + 'static) -> String {
let _app = Application::prepare(&Ext).await.test();
let mut cx = Context::new(web::test::TestRequest::get().to_http_request())
.with_theme(&pagetop_bootsier::Bootsier);
component.render(&mut cx).await.into_string()
}
fn assert_only_allowed_links(html: &str) {
for shown in ["nav-allowed", "dropdown-partial", "in-allowed"] {
assert!(html.contains(shown), "`{shown}` is missing in {html}");
}
for hidden in [
"nav-forbidden",
"dropdown-empty",
"in-forbidden",
"header-empty",
] {
assert!(!html.contains(hidden), "`{hidden}` is shown in {html}");
}
assert!(
!html.contains("dropdown-divider"),
"a divider is shown in {html}"
);
}
#[pagetop::test]
async fn nav_only_shows_the_allowed_links() {
assert_only_allowed_links(&render(menu()).await);
}
#[pagetop::test]
async fn navbar_only_shows_the_allowed_links() {
let navbar = Navbar::simple().with_item(bs::navbar::Item::nav(menu()));
let html = render(navbar).await;
assert!(
html.contains("navbar-nav"),
"not rendered by the theme: {html}"
);
assert_only_allowed_links(&html);
}
#[pagetop::test]
async fn buttons_only_show_the_allowed_links() {
let html = render(Button::anchor(Lc::n("button-allowed"), TestRoute::Allowed)).await;
assert!(html.contains("button-allowed"), "{html}");
let html = render(Button::anchor(
Lc::n("button-forbidden"),
TestRoute::Forbidden,
))
.await;
assert!(html.is_empty(), "{html}");
}

View file

@ -250,6 +250,11 @@ pub type PermissionRef = &'static dyn Permission;
/// La decisión de conceder o denegar permisos al usuario anónimo también es responsabilidad de cada /// La decisión de conceder o denegar permisos al usuario anónimo también es responsabilidad de cada
/// extensión. /// extensión.
/// ///
/// Sirve para mostrar u ocultar lo que no se puede usar. Una ruta se protege con el acceso que se
/// indica al montarla ([`Access`]), y un enlace a ella se oculta solo si se declara con
/// [`Endpoint`](crate::web::Endpoint); para un permiso más concreto dentro del *handler* está
/// [`require_permission()`].
///
/// # Ejemplo /// # Ejemplo
/// ///
/// ```rust,no_run /// ```rust,no_run
@ -260,10 +265,12 @@ pub type PermissionRef = &'static dyn Permission;
/// # 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> {
/// if !has_permission(&request, &MyPermission::Edit) { /// let can_edit = has_permission(&request, &MyPermission::Edit);
/// return Err(ErrorPage::NotFound(Some(request))); /// let mut page = Page::new(request);
/// if can_edit {
/// page.push_message(MessageLevel::Info, Lc::n("You can edit this page."));
/// } /// }
/// Page::new(request).render().await /// page.render().await
/// } /// }
/// ``` /// ```
pub fn has_permission(request: &HttpRequest, perm: PermissionRef) -> bool { pub fn has_permission(request: &HttpRequest, perm: PermissionRef) -> bool {
@ -321,6 +328,9 @@ pub fn require_permission(request: &HttpRequest, perm: PermissionRef) -> Result<
/// comprueba antes de llegar al *handler*, que sólo comprueba permisos más concretos, si los hay /// 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 /// (p. ej. que el usuario sea el autor de lo que edita). A quien no tiene acceso se le responde
/// con [`deny_access()`]. /// con [`deny_access()`].
///
/// El acceso con el que se monta una ruta no se puede consultar después. Para que sus enlaces lo
/// conozcan sin repetirlo, ruta y acceso se declaran juntos con [`Endpoint`](crate::web::Endpoint).
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub enum Access { pub enum Access {
/// Cualquiera, también un usuario anónimo. /// Cualquiera, también un usuario anónimo.

View file

@ -78,6 +78,10 @@ impl Component for Button {
self.props.get_id() self.props.get_id()
} }
fn is_renderable(&self, cx: &Context) -> bool {
self.href().is_accessible(cx)
}
fn setup(&mut self, cx: &mut Context) { fn setup(&mut self, cx: &mut Context) {
use button::{Size, Style}; use button::{Size, Style};
@ -182,6 +186,8 @@ impl Button {
/// [`with_style()`](Self::with_style)), por lo que el tema activo puede mostrarlo igual que /// [`with_style()`](Self::with_style)), por lo que el tema activo puede mostrarlo igual que
/// cualquier otra variante de `Button`. No confundir con [`button::Style::Link`], que es sólo /// cualquier otra variante de `Button`. No confundir con [`button::Style::Link`], que es sólo
/// un estilo visual sobre un `<button>`. /// un estilo visual sobre un `<button>`.
///
/// No se renderiza si el usuario actual no puede acceder a la ruta (ver [`Endpoint`]).
pub fn anchor(label: Lc, route: impl Into<Route>) -> Self { pub fn anchor(label: Lc, route: impl Into<Route>) -> Self {
Self { Self {
label, label,

View file

@ -5,3 +5,6 @@ pub use component::Dropdown;
mod item; mod item;
pub use item::{Item, ItemKind}; pub use item::{Item, ItemKind};
mod items;
pub use items::Items;

View file

@ -2,13 +2,15 @@ use crate::prelude::*;
/// Componente para crear un **menú desplegable**. /// Componente para crear un **menú desplegable**.
/// ///
/// Renderiza un botón (único o desdoblado, ver [`with_button_split()`](Self::with_button_split)) /// Renderiza un botón (único o desdoblado, ver [`with_button_split()`]) que despliega u oculta una
/// que despliega u oculta una lista de elementos [`dropdown::Item`](super::Item). /// lista de elementos [`dropdown::Item`].
/// ///
/// Sin título (ver [`with_title()`](Self::with_title)), se muestra únicamente la lista de /// Sin título (ver [`with_title()`]), se muestra únicamente la lista de elementos, sin ningún botón
/// elementos, sin ningún botón para interactuar, sólo un menú contextual estático. /// para interactuar, sólo un menú contextual estático.
/// ///
/// Si no contiene elementos, el componente **no se renderiza**. /// Un encabezado sólo se muestra si su grupo tiene algún elemento visible, y un separador sólo
/// entre elementos visibles (ver [`dropdown::Items`]). Si no quedan elementos para mostrar, el
/// componente **no se renderiza**.
/// ///
/// # Ejemplo /// # Ejemplo
/// ///
@ -23,6 +25,11 @@ use crate::prelude::*;
/// .with_item(dropdown::Item::header(Lc::n("User session"))) /// .with_item(dropdown::Item::header(Lc::n("User session")))
/// .with_item(dropdown::Item::button(Lc::n("Sign out"))); /// .with_item(dropdown::Item::button(Lc::n("Sign out")));
/// ``` /// ```
///
/// [`with_title()`]: Self::with_title
/// [`with_button_split()`]: Self::with_button_split
/// [`dropdown::Item`]: super::Item
/// [`dropdown::Items`]: super::Items
#[derive(AutoDefault, Clone, Debug, Getters)] #[derive(AutoDefault, Clone, Debug, Getters)]
pub struct Dropdown { pub struct Dropdown {
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente. /// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
@ -40,7 +47,7 @@ pub struct Dropdown {
/// Devuelve si el menú se alinea al final del botón (por defecto, al inicio). /// Devuelve si el menú se alinea al final del botón (por defecto, al inicio).
menu_end: bool, menu_end: bool,
/// Devuelve la lista de elementos del menú. /// Devuelve la lista de elementos del menú.
items: Children, items: dropdown::Items,
} }
#[async_trait] #[async_trait]
@ -210,7 +217,7 @@ impl Dropdown {
/// ])); /// ]));
/// ``` /// ```
pub fn with_item(mut self, op: impl Into<TypedOp<dropdown::Item>>) -> Self { pub fn with_item(mut self, op: impl Into<TypedOp<dropdown::Item>>) -> Self {
self.items.alter_child(op.into()); self.items.alter_item(op.into());
self self
} }
} }

View file

@ -40,6 +40,10 @@ pub enum ItemKind {
/// ///
/// Permite definir el identificador, las clases de estilo adicionales y el tipo de interacción /// Permite definir el identificador, las clases de estilo adicionales y el tipo de interacción
/// asociada, manteniendo una interfaz común para renderizar todos los elementos del menú. /// asociada, manteniendo una interfaz común para renderizar todos los elementos del menú.
///
/// Un enlace no se renderiza si el usuario actual no puede acceder a su ruta (ver [`Endpoint`]).
/// Tampoco se muestra un encabezado si su grupo no tiene ningún elemento visible, ni un separador
/// que no quede entre elementos visibles (ver [`dropdown::Items`](super::Items)).
#[derive(AutoDefault, Clone, Debug, Getters)] #[derive(AutoDefault, Clone, Debug, Getters)]
pub struct Item { pub struct Item {
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente. /// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
@ -58,6 +62,13 @@ impl Component for Item {
self.props.get_id() self.props.get_id()
} }
fn is_renderable(&self, cx: &Context) -> bool {
match self.item_kind() {
ItemKind::Link { route, .. } => route.is_accessible(cx),
_ => true,
}
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> { async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
Ok(match self.item_kind() { Ok(match self.item_kind() {
ItemKind::Void => html! {}, ItemKind::Void => html! {},

View file

@ -0,0 +1,68 @@
use crate::prelude::*;
use super::{Item, ItemKind};
/// Lista de elementos [`Item`] de un menú desplegable [`Dropdown`](super::Dropdown).
///
/// Se renderiza sin los encabezados ni los separadores que no separan nada (ver
/// [`render()`](Self::render)), así que cualquier tema que pinte el menú con `items().render(cx)`
/// aprovecha la limpieza sin hacer nada más.
#[derive(AutoDefault, Clone, Debug)]
pub struct Items(Children);
impl Items {
/// Devuelve el número de elementos de la lista, también los que no se mostrarán.
pub fn len(&self) -> usize {
self.0.len()
}
/// Indica si la lista está vacía.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Renderiza los elementos sin los encabezados ni los separadores que no separan nada.
///
/// Un encabezado sólo se muestra si le sigue algún elemento visible antes del siguiente
/// encabezado o separador, y un separador sólo entre dos elementos visibles, una sola vez.
/// Así, si se ocultan todos los enlaces de un grupo (por ejemplo, porque el usuario no tiene
/// acceso a sus rutas, ver [`Endpoint`]), su encabezado desaparece con ellos. Un elemento es
/// visible si su renderizado no queda vacío. Cada uno se renderiza como mucho una vez: los
/// encabezados y separadores, sólo si se muestran.
pub async fn render(&self, cx: &mut Context) -> Markup {
let mut shown: Vec<Markup> = Vec::with_capacity(self.0.len());
// Encabezado y separador a la espera de un elemento visible que los justifique.
let mut header = None;
let mut divider = None;
for item in self.0.iter() {
match item.downcast_ref::<Item>().map(Item::item_kind) {
Some(ItemKind::Header(_)) => header = Some(item),
Some(ItemKind::Divider) => {
header = None;
if !shown.is_empty() {
divider = Some(item);
}
}
_ => {
let markup = item.render(cx).await;
if markup.is_empty() {
continue;
}
if let Some(divider) = divider.take() {
shown.push(divider.render(cx).await);
}
if let Some(header) = header.take() {
shown.push(header.render(cx).await);
}
shown.push(markup);
}
}
}
html! { @for markup in &shown { (markup) } }
}
// Añade un elemento o modifica la lista con una operación `TypedOp`.
pub(crate) fn alter_item(&mut self, op: TypedOp<Item>) {
self.0.alter_child(op);
}
}

View file

@ -5,7 +5,8 @@ use crate::prelude::*;
/// Presenta una lista de elementos [`nav::Item`](super::Item), donde alguno puede desplegar un /// Presenta una lista de elementos [`nav::Item`](super::Item), donde alguno puede desplegar un
/// [`Dropdown`](super::super::Dropdown) embebido. /// [`Dropdown`](super::super::Dropdown) embebido.
/// ///
/// Si no contiene elementos, el componente **no se renderiza**. /// Si no contiene elementos, o si ninguno se muestra (ver [`Endpoint`]), el componente **no se
/// renderiza**.
/// ///
/// # Ejemplo /// # Ejemplo
/// ///

View file

@ -52,6 +52,8 @@ impl ItemKind {
/// ///
/// Permite definir el identificador, las clases de estilo adicionales y el tipo de interacción /// Permite definir el identificador, las clases de estilo adicionales y el tipo de interacción
/// asociada, manteniendo una interfaz común para renderizar todos los elementos del menú. /// asociada, manteniendo una interfaz común para renderizar todos los elementos del menú.
///
/// Un enlace no se renderiza si el usuario actual no puede acceder a su ruta (ver [`Endpoint`]).
#[derive(AutoDefault, Clone, Debug, Getters)] #[derive(AutoDefault, Clone, Debug, Getters)]
pub struct Item { pub struct Item {
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente. /// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
@ -77,6 +79,13 @@ impl Component for Item {
self.props.get_id() self.props.get_id()
} }
fn is_renderable(&self, cx: &Context) -> bool {
match self.item_kind() {
ItemKind::Link { route, .. } => route.is_accessible(cx),
_ => true,
}
}
fn setup(&mut self, _cx: &mut Context) { fn setup(&mut self, _cx: &mut Context) {
self.alter_prop(PropsOp::prepend_classes(self.item_kind().as_str())); self.alter_prop(PropsOp::prepend_classes(self.item_kind().as_str()));
} }

View file

@ -1,3 +1,4 @@
use crate::core::AnyCast;
use crate::core::component::{Component, Context}; use crate::core::component::{Component, Context};
use crate::html::{Markup, html}; use crate::html::{Markup, html};
use crate::{AutoDefault, UniqueId, builder_impl}; use crate::{AutoDefault, UniqueId, builder_impl};
@ -71,6 +72,24 @@ impl Child {
} }
} }
/// Devuelve una referencia al componente si es del tipo `C`, o `None` si es de otro tipo o el
/// `Child` está vacío.
///
/// Permite consultar el estado de un componente concreto de una lista sin renderizarlo (p. ej.
/// el tipo de cada [`dropdown::Item`](crate::base::component::dropdown::Item)).
///
/// # Ejemplo
///
/// ```rust
/// # use pagetop::prelude::*;
/// let child = Child::with(Html::with(|_| html! { "Prueba" }));
/// assert!(child.downcast_ref::<Html>().is_some());
/// assert!(child.downcast_ref::<Button>().is_none());
/// ```
pub fn downcast_ref<C: Component>(&self) -> Option<&C> {
self.0.as_deref().and_then(|c| c.downcast_ref::<C>())
}
// **< Child HELPERS >************************************************************************** // **< Child HELPERS >**************************************************************************
// Devuelve el [`UniqueId`] del tipo del componente, si el Child no está vacío. // Devuelve el [`UniqueId`] del tipo del componente, si el Child no está vacío.
@ -440,6 +459,11 @@ impl Children {
self.0.iter().filter(move |c| c.type_id() == Some(type_id)) self.0.iter().filter(move |c| c.type_id() == Some(type_id))
} }
/// Devuelve un iterador sobre todos los componentes hijo, en orden.
pub fn iter(&self) -> impl Iterator<Item = &Child> {
self.0.iter()
}
// **< Children RENDER >************************************************************************ // **< Children RENDER >************************************************************************
/// Renderiza todos los componentes hijo, en orden. /// Renderiza todos los componentes hijo, en orden.

View file

@ -1,6 +1,9 @@
use crate::CowStr;
use crate::auth::Access;
use crate::core::component::{Context, Contextual}; use crate::core::component::{Context, Contextual};
use crate::html::RoutePath; use crate::html::RoutePath;
use crate::util; use crate::util;
use crate::web::Endpoint;
use std::fmt; use std::fmt;
use std::sync::Arc; use std::sync::Arc;
@ -64,6 +67,13 @@ use std::sync::Arc;
/// [`Route::external()`] explícitamente cuando quieras dejar clara la intención sin ambigüedad, o /// [`Route::external()`] explícitamente cuando quieras dejar clara la intención sin ambigüedad, o
/// para esquemas que la heurística aplicada no reconozca. /// para esquemas que la heurística aplicada no reconozca.
/// ///
/// # Rutas con acceso
///
/// Una `Route` creada a partir de un [`Endpoint`] lleva además el acceso de esa ruta, y
/// [`is_accessible()`](Self::is_accessible) dice si el usuario actual lo cumple. Los enlaces de los
/// menús y [`Button::anchor()`](crate::base::component::Button::anchor) lo usan para no mostrarse a
/// quien no podría entrar. Cualquier otra `Route` se considera pública.
///
/// # Ejemplos /// # Ejemplos
/// ///
/// El caso más común es una ruta relativa dependiente del contexto, normalmente usando /// El caso más común es una ruta relativa dependiente del contexto, normalmente usando
@ -118,7 +128,10 @@ use std::sync::Arc;
/// let route = Route::external("ftp://files.example.com"); /// let route = Route::external("ftp://files.example.com");
/// ``` /// ```
#[derive(Clone)] #[derive(Clone)]
pub struct Route(Arc<dyn Fn(&Context) -> RoutePath + Send + Sync>); pub struct Route {
resolver: Arc<dyn Fn(&Context) -> RoutePath + Send + Sync>,
access: Access,
}
impl Route { impl Route {
/// Crea una `Route` a partir de un closure que resuelve la ruta según el contexto. /// Crea una `Route` a partir de un closure que resuelve la ruta según el contexto.
@ -126,7 +139,10 @@ impl Route {
where where
F: Fn(&Context) -> RoutePath + Send + Sync + 'static, F: Fn(&Context) -> RoutePath + Send + Sync + 'static,
{ {
Route(Arc::new(f)) Route {
resolver: Arc::new(f),
access: Access::Public,
}
} }
/// Crea una `Route` para una URL externa fija. /// Crea una `Route` para una URL externa fija.
@ -142,7 +158,7 @@ impl Route {
/// Invoca el closure interno para obtener la [`RoutePath`] final. /// Invoca el closure interno para obtener la [`RoutePath`] final.
pub fn resolve(&self, cx: &Context) -> RoutePath { pub fn resolve(&self, cx: &Context) -> RoutePath {
(self.0)(cx) (self.resolver)(cx)
} }
/// Como [`resolve()`](Self::resolve), pero devuelve `None` cuando la ruta calculada está vacía. /// Como [`resolve()`](Self::resolve), pero devuelve `None` cuando la ruta calculada está vacía.
@ -153,6 +169,27 @@ impl Route {
let route = self.resolve(cx); let route = self.resolve(cx);
(!route.is_empty()).then_some(route) (!route.is_empty()).then_some(route)
} }
/// Devuelve `true` si el usuario actual puede acceder a esta ruta.
///
/// Sirve para decidir qué se muestra: la ruta ya se protege con su propio acceso. Sólo una ruta
/// creada a partir de un [`Endpoint`] lleva acceso; cualquier otra es pública.
pub fn is_accessible(&self, cx: &Context) -> bool {
match self.access {
Access::Public => true,
access => cx.request().is_some_and(|request| access.allows(request)),
}
}
// Enlace a una ruta de un `Endpoint`, con su acceso: lo crean la conversión desde un `Endpoint`
// y `Endpoint::to()`.
pub(crate) fn endpoint(path: impl Into<CowStr>, access: Access) -> Self {
let path = path.into();
Route {
resolver: Arc::new(move |cx| cx.route(RoutePath::new(path.clone()))),
access,
}
}
} }
impl fmt::Debug for Route { impl fmt::Debug for Route {
@ -186,6 +223,21 @@ impl From<RoutePath> for Route {
} }
} }
/// Enlaza con una ruta declarada con [`Endpoint`], conservando su acceso.
///
/// Una ruta con parámetro se enlaza con [`Endpoint::to()`]; en desarrollo y en las pruebas, esta
/// conversión falla si se olvida.
impl<E: Endpoint> From<E> for Route {
fn from(endpoint: E) -> Self {
let path = endpoint.path();
debug_assert!(
!path.contains('{'),
"route `{path}` needs its parameter, link to it with `to()`"
);
Route::endpoint(path, endpoint.access())
}
}
impl From<&'static str> for Route { impl From<&'static str> for Route {
fn from(path: &'static str) -> Self { fn from(path: &'static str) -> Self {
if util::url_looks_external(path) { if util::url_looks_external(path) {

View file

@ -287,6 +287,9 @@ pub trait Extension: AnyInfo + Send + Sync {
/// } /// }
/// ``` /// ```
/// ///
/// Las rutas que se enlazan desde otros sitios se declaran mejor con [`Endpoint`] y se montan
/// con [`Routes::endpoint()`]: sus enlaces se ocultan solos a quien no tiene acceso.
///
/// ## Rutas agrupadas con su propio middleware /// ## Rutas agrupadas con su propio middleware
/// ///
/// Un `Router::new()` aparte, con sus capas, se añade bajo un prefijo con /// Un `Router::new()` aparte, con sus capas, se añade bajo un prefijo con
@ -314,7 +317,9 @@ pub trait Extension: AnyInfo + Send + Sync {
/// [`Access::Public`]: crate::auth::Access::Public /// [`Access::Public`]: crate::auth::Access::Public
/// [`Routes`]: crate::web::Routes /// [`Routes`]: crate::web::Routes
/// [`Routes::public_route()`]: crate::web::Routes::public_route /// [`Routes::public_route()`]: crate::web::Routes::public_route
/// [`Routes::endpoint()`]: crate::web::Routes::endpoint
/// [`Routes::nest()`]: crate::web::Routes::nest /// [`Routes::nest()`]: crate::web::Routes::nest
/// [`Endpoint`]: crate::web::Endpoint
/// [`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, routes: Routes) -> Routes {

View file

@ -36,8 +36,9 @@ pub use crate::locale::*;
pub use crate::datetime::*; pub use crate::datetime::*;
pub use crate::web; pub use crate::web::{
pub use crate::web::{HttpRequest, IntoResponse, Layers, Response, Router, Routes, StaticFiles}; self, Endpoint, HttpRequest, IntoResponse, Layers, Response, Router, Routes, StaticFiles,
};
pub use crate::core::{AnyCast, AnyInfo, TypeInfo}; pub use crate::core::{AnyCast, AnyInfo, TypeInfo};

View file

@ -73,6 +73,10 @@ pub(crate) use csrf::reject_cross_origin;
mod routes; mod routes;
pub use routes::{Layers, Routes, StaticFiles}; pub use routes::{Layers, Routes, StaticFiles};
// Rutas declaradas junto con su acceso, para montarlas y enlazarlas sin repetirlo.
mod endpoint;
pub use endpoint::Endpoint;
use axum::body::Body; use axum::body::Body;
use axum::extract::FromRequestParts; use axum::extract::FromRequestParts;

127
src/web/endpoint.rs Normal file
View file

@ -0,0 +1,127 @@
use crate::CowStr;
use crate::auth::Access;
use crate::core::component::Route;
use crate::web::push_percent_encoded;
use std::fmt;
/// Ruta de la aplicación con el acceso que la habilita, para montarla y enlazarla sin repetirlo.
///
/// Se implementa con un `enum` por extensión, igual que [`Permission`]: cada variante es una ruta
/// y, si `access()` es un `match` sin comodín (`_`), añadir una sin decir quién puede acceder a
/// ella no compila. La ruta se monta con [`Routes::endpoint()`] y se convierte en una [`Route`]
/// para usarla como destino de un enlace.
///
/// [`nav::Item`], [`dropdown::Item`] y [`Button::anchor()`] no se renderizan si el usuario actual
/// no tiene acceso a su ruta (y un [`Nav`] o un [`Dropdown`] sin elementos que mostrar, tampoco),
/// así que un enlace nunca nombra el permiso y no puede desalinearse de la ruta. El resto de
/// componentes usan la ruta sin ocultar nada. Sólo es una ayuda para la interfaz: quien escriba la
/// URL recibe la respuesta del acceso de la ruta.
///
/// # Ejemplo
///
/// ```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 notices() -> &'static str { "" }
/// # async fn new_notice() -> &'static str { "" }
/// # async fn edit_notice() -> &'static str { "" }
/// #[derive(Clone, Copy, Debug)]
/// enum BoardRoute {
/// Notices,
/// NewNotice,
/// EditNotice,
/// }
///
/// impl Endpoint for BoardRoute {
/// fn path(&self) -> CowStr {
/// match self {
/// Self::Notices => "/notices".into(),
/// Self::NewNotice => "/notices/new".into(),
/// Self::EditNotice => "/notices/{id}/edit".into(),
/// }
/// }
///
/// fn access(&self) -> Access {
/// match self {
/// Self::Notices => Access::Public,
/// Self::NewNotice | Self::EditNotice => {
/// Access::Permission(&BoardPermission::PostNotices)
/// }
/// }
/// }
/// }
///
/// fn configure_router(routes: Routes) -> Routes {
/// routes
/// .endpoint(BoardRoute::Notices, web::get(notices))
/// .endpoint(BoardRoute::NewNotice, web::get(new_notice))
/// .endpoint(BoardRoute::EditNotice, web::get(edit_notice))
/// }
///
/// // Quien no pueda publicar no verá ni el segundo enlace ni el botón.
/// fn menu(id: i32) -> (Nav, Button) {
/// let nav = Nav::new()
/// .with_item(nav::Item::link(Lc::n("Notices"), BoardRoute::Notices))
/// .with_item(nav::Item::link(Lc::n("New notice"), BoardRoute::NewNotice));
/// (nav, Button::anchor(Lc::n("Edit"), BoardRoute::EditNotice.to(id)))
/// }
/// ```
///
/// El acceso sólo responde por la ruta, no por lo que compruebe además su *handler*. Si varios
/// métodos de una misma ruta exigen un acceso distinto, cada uno es una variante con la misma ruta,
/// y el enlace usa la del método `GET`.
///
/// [`Permission`]: crate::auth::Permission
/// [`Routes::endpoint()`]: crate::web::Routes::endpoint
/// [`nav::Item`]: crate::base::component::nav::Item
/// [`dropdown::Item`]: crate::base::component::dropdown::Item
/// [`Button::anchor()`]: crate::base::component::Button::anchor
/// [`Nav`]: crate::base::component::Nav
/// [`Dropdown`]: crate::base::component::Dropdown
pub trait Endpoint {
/// Devuelve la ruta tal como se monta, con la sintaxis de parámetros de Axum si lo tiene
/// (`"/notices/{id}/edit"`).
fn path(&self) -> CowStr;
/// Devuelve quién puede acceder a la ruta.
fn access(&self) -> Access;
/// Crea el enlace a una ruta con parámetro, conservando su acceso.
///
/// Sustituye el parámetro `{...}` por el valor indicado: `BoardRoute::EditNotice.to(7)` enlaza
/// con `/notices/7/edit`. El valor se codifica (`%XX`) salvo letras, dígitos, `-`, `_`, `.` y
/// `~`, así que no puede añadir tramos, parámetros de consulta ni otro dominio a la URL. Aun
/// así, un valor vacío deja un tramo vacío, que no coincide con la ruta, y el navegador
/// resuelve `.` y `..` como otra ruta: los identificadores numéricos o validados no tienen ese
/// problema.
///
/// En desarrollo y en las pruebas falla si la ruta no tiene exactamente un parámetro.
fn to(&self, param: impl fmt::Display) -> Route {
let pattern = self.path();
let parts = pattern
.split_once('{')
.and_then(|(prefix, rest)| Some((prefix, rest.split_once('}')?.1)));
debug_assert!(
parts.is_some(),
"route `{pattern}` has no parameter to fill"
);
let Some((prefix, suffix)) = parts else {
return Route::endpoint(pattern, self.access());
};
debug_assert!(
!suffix.contains('{'),
"route `{pattern}` has more than one parameter"
);
let param = param.to_string();
let mut path = String::with_capacity(prefix.len() + param.len() + suffix.len());
path.push_str(prefix);
push_percent_encoded(&mut path, param);
path.push_str(suffix);
Route::endpoint(path, self.access())
}
}

View file

@ -1,6 +1,6 @@
use crate::admin::{AdminRegistry, admin_path, strip_admin_path, undeclared_permission}; use crate::admin::{AdminRegistry, admin_path, strip_admin_path, undeclared_permission};
use crate::auth::{Access, PermissionRegistry, deny_access}; use crate::auth::{Access, PermissionRegistry, deny_access};
use crate::web::{HttpRequest, IntoResponse, Request, Response, Router, middleware}; use crate::web::{Endpoint, HttpRequest, IntoResponse, Request, Response, Router, middleware};
use crate::{global, trace}; use crate::{global, trace};
use axum::extract::State; use axum::extract::State;
@ -19,6 +19,9 @@ use std::convert::Infallible;
/// comprueba antes de llegar al *handler* y responde con [`deny_access()`] a quien no lo cumple. /// comprueba antes de llegar al *handler* y responde con [`deny_access()`] a quien no lo cumple.
/// Una ruta [`Access::Public`] no añade ninguna comprobación. /// Una ruta [`Access::Public`] no añade ninguna comprobación.
/// ///
/// Las rutas que se enlazan desde otros sitios se declaran mejor con [`Endpoint`] y se montan con
/// [`endpoint()`](Self::endpoint): así, sus enlaces conocen el acceso sin repetirlo.
///
/// Las rutas del panel de administración (bajo [`admin_path`]) se montan con [`admin_route()`], que /// Las rutas del panel de administración (bajo [`admin_path`]) se montan con [`admin_route()`], que
/// exige el permiso de la página declarada ([`AdminPage`]) de la que cuelgan: el permiso se declara /// exige el permiso de la página declarada ([`AdminPage`]) de la que cuelgan: el permiso se declara
/// sólo en la página. Montar una con cualquier otro método, o una que no cuelgue de ninguna página, /// sólo en la página. Montar una con cualquier otro método, o una que no cuelgue de ninguna página,
@ -111,6 +114,13 @@ impl Routes {
self.route(path, Access::Public, method_router) self.route(path, Access::Public, method_router)
} }
/// Añade una ruta declarada con [`Endpoint`], con sus *handlers* por método.
///
/// Equivale a [`route()`](Self::route) con la ruta y el acceso que declara.
pub fn endpoint(self, endpoint: impl Endpoint, method_router: MethodRouter) -> Self {
self.route(&endpoint.path(), endpoint.access(), method_router)
}
/// Añade una ruta del panel de administración, relativa a su raíz, con sus *handlers* por /// Añade una ruta del panel de administración, relativa a su raíz, con sus *handlers* por
/// método. /// método.
/// ///

View file

@ -68,6 +68,15 @@ async fn child_id_returns_component_id() {
assert_eq!(child.id(), Some("my-id".to_string())); assert_eq!(child.id(), Some("my-id".to_string()));
} }
#[pagetop::test]
async fn child_downcast_ref_returns_the_component_only_with_its_type() {
let child = Child::with(TestComp::text("hello"));
let component = child.downcast_ref::<TestComp>().expect("a TestComp");
assert_eq!(component.text, "hello");
assert!(child.downcast_ref::<Html>().is_none());
assert!(Child::default().downcast_ref::<TestComp>().is_none());
}
#[pagetop::test] #[pagetop::test]
async fn child_from_component_is_equivalent_to_with() { async fn child_from_component_is_equivalent_to_with() {
let child: Child = TestComp::text("from-trait").into(); let child: Child = TestComp::text("from-trait").into();
@ -257,6 +266,19 @@ async fn children_iter_by_id_yields_all_matching_children() {
assert_eq!(c.iter_by_id("none").count(), 0); assert_eq!(c.iter_by_id("none").count(), 0);
} }
#[pagetop::test]
async fn children_iter_yields_all_children_in_order() {
let c = Children::new()
.with_child(TestComp::text("a"))
.with_child(TestComp::text("b"));
let texts: Vec<&str> = c
.iter()
.filter_map(|child| child.downcast_ref::<TestComp>())
.map(|component| component.text.as_str())
.collect();
assert_eq!(texts, ["a", "b"]);
}
#[pagetop::test] #[pagetop::test]
async fn children_render_concatenates_all_outputs_in_order() { async fn children_render_concatenates_all_outputs_in_order() {
let c = Children::new() let c = Children::new()

View file

@ -48,3 +48,148 @@ async fn menu_end_is_ignored_without_title() {
assert!(html.contains(r#"<ul class="dropdown-menu">"#)); assert!(html.contains(r#"<ul class="dropdown-menu">"#));
assert!(!html.contains("dropdown-menu-end")); assert!(!html.contains("dropdown-menu-end"));
} }
// **< Separators >*********************************************************************************
// A route that nobody can see without a request: its links are always hidden in these tests.
#[derive(Clone, Copy)]
struct Hidden;
impl Endpoint for Hidden {
fn path(&self) -> CowStr {
"/hidden".into()
}
fn access(&self) -> Access {
Access::Authenticated
}
}
fn shown(label: &'static str) -> dropdown::Item {
dropdown::Item::link(Lc::n(label), "/shown")
}
fn hidden(label: &'static str) -> dropdown::Item {
dropdown::Item::link(Lc::n(label), Hidden)
}
fn header(label: &'static str) -> dropdown::Item {
dropdown::Item::header(Lc::n(label))
}
// Position of `text` in `html`, which must contain it.
fn at(html: &str, text: &str) -> usize {
html.find(text)
.unwrap_or_else(|| panic!("`{text}` is missing in {html}"))
}
async fn render_menu(items: Vec<dropdown::Item>) -> String {
Dropdown::new()
.with_title(Lc::n("Menu"))
.with_item(TypedOp::AddMany(items))
.render(&mut Context::default())
.await
.into_string()
}
#[pagetop::test]
async fn a_header_without_visible_items_is_not_shown() {
let html = render_menu(vec![
header("group-empty"),
hidden("item-hidden"),
header("group-full"),
shown("item-shown"),
])
.await;
assert!(!html.contains("group-empty"), "{html}");
assert!(!html.contains("item-hidden"), "{html}");
assert!(html.contains("group-full"), "{html}");
assert!(at(&html, "group-full") < at(&html, "item-shown"), "{html}");
}
#[pagetop::test]
async fn dividers_only_separate_visible_items() {
let html = render_menu(vec![
dropdown::Item::divider(),
shown("first"),
dropdown::Item::divider(),
hidden("item-hidden"),
dropdown::Item::divider(),
shown("second"),
dropdown::Item::divider(),
])
.await;
assert_eq!(html.matches("dropdown-divider").count(), 1, "{html}");
let divider = at(&html, "dropdown-divider");
assert!(
at(&html, "first") < divider && divider < at(&html, "second"),
"{html}"
);
}
#[pagetop::test]
async fn a_divider_and_a_header_are_shown_before_the_next_visible_group() {
let html = render_menu(vec![
shown("first"),
dropdown::Item::divider(),
header("group"),
shown("second"),
])
.await;
let (divider, group) = (at(&html, "dropdown-divider"), at(&html, "group"));
assert!(at(&html, "first") < divider && divider < group, "{html}");
assert!(group < at(&html, "second"), "{html}");
}
#[pagetop::test]
async fn labels_and_buttons_count_as_visible_items() {
let html = render_menu(vec![
header("group-label"),
dropdown::Item::label(Lc::n("text")),
header("group-button"),
dropdown::Item::button(Lc::n("action")),
])
.await;
assert!(html.contains("group-label"), "{html}");
assert!(html.contains("group-button"), "{html}");
}
#[pagetop::test]
async fn a_dropdown_with_only_separators_left_is_not_rendered() {
let html = render_menu(vec![
header("group"),
hidden("item-hidden"),
dropdown::Item::divider(),
])
.await;
assert!(html.is_empty(), "{html}");
}
#[pagetop::test]
async fn separators_are_also_cleaned_in_a_dropdown_inside_a_nav() {
let menu = Dropdown::new()
.with_title(Lc::n("menu-empty"))
.with_item(header("group-empty"))
.with_item(hidden("item-hidden"));
let partial = Dropdown::new()
.with_title(Lc::n("menu-partial"))
.with_item(header("group-empty"))
.with_item(hidden("item-hidden"))
.with_item(dropdown::Item::divider())
.with_item(shown("item-shown"));
let mut nav = Nav::new()
.with_item(nav::Item::dropdown(menu))
.with_item(nav::Item::dropdown(partial));
let html = nav.render(&mut Context::default()).await.into_string();
assert!(!html.contains("menu-empty"), "{html}");
assert!(html.contains("menu-partial"), "{html}");
assert!(!html.contains("group-empty"), "{html}");
assert!(!html.contains("dropdown-divider"), "{html}");
assert!(html.contains("item-shown"), "{html}");
}

301
tests/web_endpoint.rs Normal file
View file

@ -0,0 +1,301 @@
// Verifies that a route declared with `Endpoint` is protected by its access when it is requested
// and that the links to it are only shown to whoever has that access.
use pagetop::prelude::*;
struct Granted;
impl Permission for Granted {
fn key(&self) -> CowStr {
"test:granted".into()
}
}
struct Denied;
impl Permission for Denied {
fn key(&self) -> CowStr {
"test:denied".into()
}
}
// Grants `test:granted` to everybody, as an authentication extension would.
fn grant(_: &HttpRequest, perm: PermissionRef, granted: &mut bool) {
if perm.key() == "test:granted" {
*granted = true;
}
}
#[derive(Clone, Copy)]
enum TestRoute {
Open,
Signed,
Allowed,
Forbidden,
Report(&'static str),
NoteView,
NoteSave,
AllowedItem,
ForbiddenItem,
}
impl Endpoint for TestRoute {
fn path(&self) -> CowStr {
match self {
Self::Open => "/open".into(),
Self::Signed => "/signed".into(),
Self::Allowed => "/allowed".into(),
Self::Forbidden => "/forbidden".into(),
Self::Report(slug) => format!("/reports/{slug}").into(),
Self::NoteView | Self::NoteSave => "/notes".into(),
Self::AllowedItem => "/items/{id}/edit".into(),
Self::ForbiddenItem => "/secrets/{id}/edit".into(),
}
}
fn access(&self) -> Access {
match self {
Self::Open => Access::Public,
Self::Signed => Access::Authenticated,
Self::Allowed | Self::Report(_) | Self::NoteView | Self::AllowedItem => {
Access::Permission(&Granted)
}
Self::Forbidden | Self::NoteSave | Self::ForbiddenItem => Access::Permission(&Denied),
}
}
}
// Signs in the requests that carry an `x-user` header.
async fn sign_in(mut request: web::Request, next: web::middleware::Next) -> Response {
if request.headers().contains_key("x-user") {
request
.extensions_mut()
.insert(CurrentUser::authenticated(1, "Test user"));
}
next.run(request).await
}
async fn ok() -> &'static str {
"ok"
}
async fn home(request: HttpRequest) -> Result<Markup, ErrorPage> {
Page::new(request)
.with_child(
Nav::new()
.with_item(nav::Item::link(Lc::n("nav-open"), TestRoute::Open))
.with_item(nav::Item::link(Lc::n("nav-signed"), TestRoute::Signed))
.with_item(nav::Item::link(Lc::n("nav-allowed"), TestRoute::Allowed))
.with_item(nav::Item::link(
Lc::n("nav-forbidden"),
TestRoute::Forbidden,
))
.with_item(nav::Item::link(
Lc::n("nav-report"),
TestRoute::Report("sales"),
))
.with_item(nav::Item::link(Lc::n("nav-literal"), "/literal"))
.with_item(nav::Item::label(Lc::n("nav-label")))
.with_item(nav::Item::dropdown(
Dropdown::new()
.with_title(Lc::n("dropdown-empty"))
.with_item(dropdown::Item::link(Lc::n("x"), TestRoute::Forbidden)),
))
.with_item(nav::Item::dropdown(
Dropdown::new()
.with_title(Lc::n("dropdown-partial"))
.with_item(dropdown::Item::link(
Lc::n("in-allowed"),
TestRoute::Allowed,
))
.with_item(dropdown::Item::link(
Lc::n("in-forbidden"),
TestRoute::Forbidden,
))
.with_item(dropdown::Item::button(Lc::n("in-button"))),
)),
)
.with_child(
Nav::new()
.with_id("nav-all-hidden")
.with_item(nav::Item::link(Lc::n("x"), TestRoute::Forbidden)),
)
.with_child(
Dropdown::new()
.with_title(Lc::n("standalone-empty"))
.with_item(dropdown::Item::link(Lc::n("x"), TestRoute::Forbidden)),
)
.with_child(Button::anchor(Lc::n("button-allowed"), TestRoute::Allowed))
.with_child(Button::anchor(
Lc::n("button-forbidden"),
TestRoute::Forbidden,
))
.with_child(Button::anchor(
Lc::n("item-allowed"),
TestRoute::AllowedItem.to(7),
))
.with_child(Button::anchor(
Lc::n("item-forbidden"),
TestRoute::ForbiddenItem.to(7),
))
.with_child(Button::anchor(
Lc::n("item-encoded"),
TestRoute::AllowedItem.to("a b/c?d#e"),
))
.with_child(Button::submit(Lc::n("button-submit")))
.render()
.await
}
struct Ext;
#[async_trait]
impl Extension for Ext {
fn actions(&self) -> Vec<ActionBox> {
actions![action::auth::CheckPermission::new(grant)]
}
fn configure_router(&self, routes: Routes) -> Routes {
routes
.public_route("/", web::get(home))
.endpoint(TestRoute::Open, web::get(ok))
.endpoint(TestRoute::Signed, web::get(ok))
.endpoint(TestRoute::Allowed, web::get(ok))
.endpoint(TestRoute::Forbidden, web::get(ok))
.endpoint(TestRoute::Report("sales"), web::get(ok))
// Reading is allowed, writing needs a permission that nobody has.
.endpoint(TestRoute::NoteView, web::get(ok))
.endpoint(TestRoute::NoteSave, web::post(ok))
.endpoint(TestRoute::AllowedItem, web::get(ok))
.endpoint(TestRoute::ForbiddenItem, web::get(ok))
}
fn configure_middleware(&self, layers: Layers) -> Layers {
layers.layer(web::middleware::from_fn(sign_in))
}
}
async fn send(request: web::test::TestRequest) -> Response {
let app = Application::prepare(&Ext).await.test();
web::test::send_request(&app, request.to_request()).await
}
async fn status_of(uri: &str) -> u16 {
let response = send(web::test::TestRequest::get().uri(uri)).await;
response.status().as_u16()
}
async fn home_page() -> String {
let response = send(web::test::TestRequest::get().uri("/")).await;
assert_eq!(response.status().as_u16(), 200);
web::test::read_body_text(response).await
}
#[pagetop::test]
async fn the_routes_require_the_access_they_declare() {
assert_eq!(status_of("/open").await, 200);
assert_eq!(status_of("/allowed").await, 200);
assert_eq!(status_of("/reports/sales").await, 200);
assert_eq!(status_of("/items/7/edit").await, 200);
assert_eq!(status_of("/signed").await, 403);
assert_eq!(status_of("/forbidden").await, 403);
assert_eq!(status_of("/secrets/7/edit").await, 403);
}
#[pagetop::test]
async fn each_method_of_a_route_can_require_its_own_access() {
assert_eq!(status_of("/notes").await, 200);
let save = send(web::test::TestRequest::post().uri("/notes")).await;
assert_eq!(save.status().as_u16(), 403);
}
#[pagetop::test]
async fn links_are_only_shown_with_access_to_their_route() {
let html = home_page().await;
for shown in [
"nav-open",
"nav-allowed",
"nav-report",
r#"href="/reports/sales""#,
"dropdown-partial",
"in-allowed",
"button-allowed",
] {
assert!(html.contains(shown), "`{shown}` is missing in {html}");
}
for hidden in [
"nav-signed",
"nav-forbidden",
"in-forbidden",
"button-forbidden",
"item-forbidden",
] {
assert!(!html.contains(hidden), "`{hidden}` is shown in {html}");
}
}
#[pagetop::test]
async fn links_for_signed_in_users_are_shown_after_signing_in() {
assert_eq!(status_of("/signed").await, 403);
let signed = send(
web::test::TestRequest::get()
.uri("/signed")
.header("x-user", "1"),
)
.await;
assert_eq!(signed.status().as_u16(), 200);
let home = send(web::test::TestRequest::get().uri("/").header("x-user", "1")).await;
let html = web::test::read_body_text(home).await;
assert!(
html.contains("nav-signed"),
"`nav-signed` is missing in {html}"
);
}
#[pagetop::test]
async fn elements_without_an_endpoint_are_not_affected() {
let html = home_page().await;
for shown in ["nav-literal", "nav-label", "in-button", "button-submit"] {
assert!(html.contains(shown), "`{shown}` is missing in {html}");
}
}
#[pagetop::test]
async fn menus_with_nothing_to_show_are_not_rendered() {
let html = home_page().await;
for hidden in ["dropdown-empty", "nav-all-hidden", "standalone-empty"] {
assert!(!html.contains(hidden), "`{hidden}` is shown in {html}");
}
}
#[pagetop::test]
async fn links_fill_the_parameter_of_their_route() {
let html = home_page().await;
assert!(html.contains(r#"href="/items/7/edit""#), "{html}");
assert!(
html.contains(r#"href="/items/a%20b%2Fc%3Fd%23e/edit""#),
"{html}"
);
}
#[pagetop::test]
async fn without_a_request_only_public_routes_are_accessible() {
let cx = Context::default();
assert!(Route::from(TestRoute::Open).is_accessible(&cx));
assert!(!Route::from(TestRoute::Signed).is_accessible(&cx));
assert!(!Route::from(TestRoute::Allowed).is_accessible(&cx));
assert!(Route::from("/literal").is_accessible(&cx));
}
#[pagetop::test]
#[should_panic(expected = "needs its parameter")]
async fn linking_to_a_route_with_a_parameter_needs_its_value() {
let _ = nav::Item::link(Lc::n("x"), TestRoute::AllowedItem);
}
#[pagetop::test]
#[should_panic(expected = "has no parameter")]
async fn filling_a_route_without_a_parameter_is_an_error() {
let _ = TestRoute::Allowed.to(7);
}