diff --git a/extensions/pagetop-bootsier/tests/hidden_links.rs b/extensions/pagetop-bootsier/tests/hidden_links.rs new file mode 100644 index 00000000..f39be679 --- /dev/null +++ b/extensions/pagetop-bootsier/tests/hidden_links.rs @@ -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 { + 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}"); +} diff --git a/src/auth.rs b/src/auth.rs index 43e49cd2..9ccdbe09 100644 --- a/src/auth.rs +++ b/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 /// 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 /// /// ```rust,no_run @@ -260,10 +265,12 @@ pub type PermissionRef = &'static dyn Permission; /// # fn key(&self) -> CowStr { "myapp:edit".into() } /// # } /// async fn my_handler(request: HttpRequest) -> Result { -/// if !has_permission(&request, &MyPermission::Edit) { -/// return Err(ErrorPage::NotFound(Some(request))); +/// let can_edit = has_permission(&request, &MyPermission::Edit); +/// 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 { @@ -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 /// (p. ej. que el usuario sea el autor de lo que edita). A quien no tiene acceso se le responde /// 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)] pub enum Access { /// Cualquiera, también un usuario anónimo. diff --git a/src/base/component/button/component.rs b/src/base/component/button/component.rs index 038e9fef..b9d8a50b 100644 --- a/src/base/component/button/component.rs +++ b/src/base/component/button/component.rs @@ -78,6 +78,10 @@ impl Component for Button { self.props.get_id() } + fn is_renderable(&self, cx: &Context) -> bool { + self.href().is_accessible(cx) + } + fn setup(&mut self, cx: &mut Context) { 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 /// cualquier otra variante de `Button`. No confundir con [`button::Style::Link`], que es sólo /// un estilo visual sobre un `