✨ (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.
This commit is contained in:
parent
87711e4a37
commit
e2e2ccb31e
13 changed files with 677 additions and 10 deletions
131
extensions/pagetop-bootsier/tests/hidden_links.rs
Normal file
131
extensions/pagetop-bootsier/tests/hidden_links.rs
Normal file
|
|
@ -0,0 +1,131 @@
|
||||||
|
// 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::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"] {
|
||||||
|
assert!(!html.contains(hidden), "`{hidden}` 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}");
|
||||||
|
}
|
||||||
16
src/auth.rs
16
src/auth.rs
|
|
@ -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.
|
||||||
|
|
|
||||||
|
|
@ -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,
|
||||||
|
|
|
||||||
|
|
@ -40,6 +40,9 @@ 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`]).
|
||||||
|
/// Los encabezados y separadores no dependen de ningún enlace y se muestran aunque queden solos.
|
||||||
#[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 +61,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! {},
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
///
|
///
|
||||||
|
|
|
||||||
|
|
@ -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()));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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) {
|
||||||
|
|
|
||||||
|
|
@ -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 {
|
||||||
|
|
|
||||||
|
|
@ -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};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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
127
src/web/endpoint.rs
Normal 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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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.
|
||||||
///
|
///
|
||||||
|
|
|
||||||
301
tests/web_endpoint.rs
Normal file
301
tests/web_endpoint.rs
Normal 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);
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue