✨ (web): Exige el acceso de cada ruta al montarla
`configure_router()` recibe Routes, que no monta ninguna ruta sin su Access: `route()`, `public_route()` y `admin_route()`, que toma el permiso de la página del panel de la que cuelga. Una ruta del panel montada de otra forma impide arrancar. `configure_middleware()` recibe Layers y `configure_static_files()` recibe StaticFiles, siempre públicos.
This commit is contained in:
parent
71ea609088
commit
ab2677be44
28 changed files with 664 additions and 158 deletions
10
README.md
10
README.md
|
|
@ -53,8 +53,8 @@ struct HelloWorld;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for HelloWorld {
|
impl Extension for HelloWorld {
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/", web::get(hello_world))
|
routes.public_route("/", web::get(hello_world))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -102,8 +102,8 @@ El código se organiza en un *workspace* donde actualmente se incluyen los sigui
|
||||||
### Extensiones
|
### Extensiones
|
||||||
|
|
||||||
* **[pagetop-admin](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-admin)**,
|
* **[pagetop-admin](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-admin)**,
|
||||||
panel de administración extensible, al que cada extensión añade sus secciones, páginas y
|
páginas de ajustes del panel de administración que se guardan en la base de datos y se cambian
|
||||||
formularios de configuración.
|
desde el propio panel.
|
||||||
|
|
||||||
* **[pagetop-aliner](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-aliner)**,
|
* **[pagetop-aliner](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-aliner)**,
|
||||||
es un tema para demos y pruebas que muestra esquemáticamente la composición de las páginas HTML.
|
es un tema para demos y pruebas que muestra esquemáticamente la composición de las páginas HTML.
|
||||||
|
|
@ -128,7 +128,7 @@ El código se organiza en un *workspace* donde actualmente se incluyen los sigui
|
||||||
integra [SeaORM](https://www.sea-ql.org/SeaORM) para acceder a bases de datos relacionales.
|
integra [SeaORM](https://www.sea-ql.org/SeaORM) para acceder a bases de datos relacionales.
|
||||||
|
|
||||||
* **[pagetop-user](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-user)**,
|
* **[pagetop-user](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-user)**,
|
||||||
gestiona usuarios, autenticación, roles y permisos, con su administración en `pagetop-admin`.
|
gestiona usuarios, autenticación, roles y permisos, con su administración en el panel.
|
||||||
|
|
||||||
## Pruebas
|
## Pruebas
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,8 @@ impl Extension for FormControls {
|
||||||
vec![&pagetop_aliner::Aliner, &pagetop_bootsier::Bootsier]
|
vec![&pagetop_aliner::Aliner, &pagetop_bootsier::Bootsier]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/", web::get(form_controls).post(form_controls))
|
routes.public_route("/", web::get(form_controls).post(form_controls))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@ struct HelloName;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for HelloName {
|
impl Extension for HelloName {
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/hello/{name}", web::get(hello_name))
|
routes.public_route("/hello/{name}", web::get(hello_name))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@ struct HelloWorld;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for HelloWorld {
|
impl Extension for HelloWorld {
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/", web::get(hello_world))
|
routes.public_route("/", web::get(hello_world))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,8 @@ struct IntroColors;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for IntroColors {
|
impl Extension for IntroColors {
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/", web::get(intro_colors))
|
routes.public_route("/", web::get(intro_colors))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,8 @@ struct IntroDatetime;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for IntroDatetime {
|
impl Extension for IntroDatetime {
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/", web::get(intro_datetime))
|
routes.public_route("/", web::get(intro_datetime))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,8 @@ impl Extension for IntroFlex {
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
vec![&pagetop_bootsier::Bootsier]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/", web::get(intro_flex))
|
routes.public_route("/", web::get(intro_flex))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,8 @@ impl Extension for IntroGrid {
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
vec![&pagetop_bootsier::Bootsier]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/", web::get(intro_grid))
|
routes.public_route("/", web::get(intro_grid))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,8 @@ impl Extension for IntroResponsive {
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
vec![&pagetop_bootsier::Bootsier]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/", web::get(intro_responsive))
|
routes.public_route("/", web::get(intro_responsive))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -10,8 +10,8 @@ impl Extension for IntroSpacing {
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
vec![&pagetop_bootsier::Bootsier]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/", web::get(intro_spacing))
|
routes.public_route("/", web::get(intro_spacing))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,8 +11,8 @@ impl Extension for NavbarMenus {
|
||||||
vec![&pagetop_bootsier::Bootsier]
|
vec![&pagetop_bootsier::Bootsier]
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/", web::get(navbar_menus))
|
routes.public_route("/", web::get(navbar_menus))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -98,9 +98,9 @@ pub struct MyExtension;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for MyExtension {
|
impl Extension for MyExtension {
|
||||||
fn configure_static_files(&self, router: Router) -> Router {
|
fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
||||||
serve_static_files!(router, ["./static/css", app_css] => "/public/css");
|
serve_static_files!(files, ["./static/css", app_css] => "/public/css");
|
||||||
router
|
files
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
|
||||||
|
|
@ -99,9 +99,9 @@ pub struct MyExtension;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for MyExtension {
|
impl Extension for MyExtension {
|
||||||
fn configure_static_files(&self, router: Router) -> Router {
|
fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
||||||
serve_static_files!(router, ["./static/css", app_css] => "/public/css");
|
serve_static_files!(files, ["./static/css", app_css] => "/public/css");
|
||||||
router
|
files
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
|
||||||
26
src/app.rs
26
src/app.rs
|
|
@ -2,6 +2,7 @@
|
||||||
|
|
||||||
mod figfont;
|
mod figfont;
|
||||||
|
|
||||||
|
use crate::admin;
|
||||||
use crate::core::extension;
|
use crate::core::extension;
|
||||||
use crate::core::extension::ExtensionRef;
|
use crate::core::extension::ExtensionRef;
|
||||||
use crate::core::extension::all::StartupError;
|
use crate::core::extension::all::StartupError;
|
||||||
|
|
@ -221,7 +222,10 @@ impl Application {
|
||||||
let std_listener = std::net::TcpListener::bind(&addr)?;
|
let std_listener = std::net::TcpListener::bind(&addr)?;
|
||||||
std_listener.set_nonblocking(true)?;
|
std_listener.set_nonblocking(true)?;
|
||||||
|
|
||||||
let router = Self::build_router();
|
let router = match Self::build_router() {
|
||||||
|
Ok(router) => router,
|
||||||
|
Err(err) => Self::abort_startup(self.tracing.take(), err),
|
||||||
|
};
|
||||||
|
|
||||||
// Con el puerto ya enlazado, arranca los servicios en segundo plano de las extensiones.
|
// Con el puerto ya enlazado, arranca los servicios en segundo plano de las extensiones.
|
||||||
if let Err(err) = extension::all::start_extensions().await {
|
if let Err(err) = extension::all::start_extensions().await {
|
||||||
|
|
@ -242,8 +246,13 @@ impl Application {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Devuelve el servidor web configurado para usarlo en pruebas de integración.
|
/// Devuelve el servidor web configurado para usarlo en pruebas de integración.
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
///
|
||||||
|
/// Si alguna ruta del panel de administración está mal montada (ver
|
||||||
|
/// [`Routes`](crate::web::Routes)), que con [`run()`](Self::run) detendría el arranque.
|
||||||
pub fn test(self) -> Router {
|
pub fn test(self) -> Router {
|
||||||
Self::build_router()
|
Self::build_router().unwrap_or_else(|err| panic!("{err}"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Construye el router con las rutas, el middleware y los archivos estáticos de todas las
|
// Construye el router con las rutas, el middleware y los archivos estáticos de todas las
|
||||||
|
|
@ -256,6 +265,10 @@ impl Application {
|
||||||
// cambio, se registra antes: la página 404 debe ver lo que el middleware añade a la petición
|
// cambio, se registra antes: la página 404 debe ver lo que el middleware añade a la petición
|
||||||
// (p. ej. el usuario actual).
|
// (p. ej. el usuario actual).
|
||||||
//
|
//
|
||||||
|
// Cada ruta comprueba su acceso (`web::Routes`) después de pasar por el middleware de las
|
||||||
|
// extensiones, cuando éste ya ha resuelto el usuario actual. Si alguna ruta del panel de
|
||||||
|
// administración está mal montada, se devuelve un error y la aplicación no arranca.
|
||||||
|
//
|
||||||
// Los mensajes *flash* (`keep_flash_messages()`) se registran junto al middleware de las
|
// Los mensajes *flash* (`keep_flash_messages()`) se registran junto al middleware de las
|
||||||
// extensiones, también antes de los archivos estáticos, que no los muestran.
|
// extensiones, también antes de los archivos estáticos, que no los muestran.
|
||||||
//
|
//
|
||||||
|
|
@ -268,16 +281,17 @@ impl Application {
|
||||||
// Las capas de páginas de error y `CatchPanicLayer` cubren todo, porque se añaden al final. Con
|
// Las capas de páginas de error y `CatchPanicLayer` cubren todo, porque se añaden al final. Con
|
||||||
// `CatchPanicLayer` en la última capa se capturan incluso los `panic!` que se produzcan dentro
|
// `CatchPanicLayer` en la última capa se capturan incluso los `panic!` que se produzcan dentro
|
||||||
// del propio renderizado de una página de error.
|
// del propio renderizado de una página de error.
|
||||||
fn build_router() -> Router {
|
fn build_router() -> Result<Router, StartupError> {
|
||||||
let router = extension::all::configure_routes(Router::new()).fallback(route_not_found);
|
let router = extension::all::configure_routes(Router::new())?;
|
||||||
|
let router = admin::configure_routes(router).fallback(route_not_found);
|
||||||
let router = extension::all::configure_middleware(router)
|
let router = extension::all::configure_middleware(router)
|
||||||
.layer(axum::middleware::from_fn(keep_flash_messages));
|
.layer(axum::middleware::from_fn(keep_flash_messages));
|
||||||
let router = extension::all::configure_static_files(router);
|
let router = extension::all::configure_static_files(router);
|
||||||
router
|
Ok(router
|
||||||
.layer(axum::middleware::from_fn(reject_cross_origin))
|
.layer(axum::middleware::from_fn(reject_cross_origin))
|
||||||
.layer(axum::middleware::from_fn(limit_body))
|
.layer(axum::middleware::from_fn(limit_body))
|
||||||
.layer(axum::middleware::from_fn(render_error_pages))
|
.layer(axum::middleware::from_fn(render_error_pages))
|
||||||
.layer(CatchPanicLayer::custom(response_for_panic))
|
.layer(CatchPanicLayer::custom(response_for_panic)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -21,8 +21,8 @@ impl Extension for Welcome {
|
||||||
Lc::l("welcome_extension_description")
|
Lc::l("welcome_extension_description")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/", web::get(home))
|
routes.public_route("/", web::get(home))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,10 @@
|
||||||
|
use crate::admin::build_admin_registry;
|
||||||
|
use crate::auth::build_permission_registry;
|
||||||
use crate::core::action::publish_actions;
|
use crate::core::action::publish_actions;
|
||||||
use crate::core::extension::ExtensionRef;
|
use crate::core::extension::ExtensionRef;
|
||||||
use crate::core::theme::ThemeRef;
|
use crate::core::theme::ThemeRef;
|
||||||
use crate::core::theme::all::register_theme;
|
use crate::core::theme::all::register_theme;
|
||||||
use crate::web::Router;
|
use crate::web::{Layers, Router, Routes, StaticFiles};
|
||||||
use crate::{BoxError, config, global, serve_static_files, trace, web};
|
use crate::{BoxError, config, global, serve_static_files, trace, web};
|
||||||
|
|
||||||
use std::sync::OnceLock;
|
use std::sync::OnceLock;
|
||||||
|
|
@ -42,6 +44,14 @@ pub enum StartupError {
|
||||||
#[source]
|
#[source]
|
||||||
source: BoxError,
|
source: BoxError,
|
||||||
},
|
},
|
||||||
|
/// Rutas del panel de administración montadas sin
|
||||||
|
/// [`Routes::admin_route()`](crate::web::Routes::admin_route), o que no cuelgan de una página
|
||||||
|
/// declarada.
|
||||||
|
#[error(
|
||||||
|
"Administration routes must use admin_route() and hang from a declared page: {}",
|
||||||
|
.0.join(", ")
|
||||||
|
)]
|
||||||
|
InvalidAdminRoutes(Vec<String>),
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< REGISTRO DE LAS EXTENSIONES >****************************************************************
|
// **< REGISTRO DE LAS EXTENSIONES >****************************************************************
|
||||||
|
|
@ -127,6 +137,12 @@ pub fn register_actions() {
|
||||||
.flat_map(|extension| extension.actions())
|
.flat_map(|extension| extension.actions())
|
||||||
.collect()
|
.collect()
|
||||||
});
|
});
|
||||||
|
// El catálogo de permisos se construye con las acciones ya publicadas y antes de inicializar
|
||||||
|
// las extensiones, que pueden consultarlo en `initialize()`.
|
||||||
|
build_permission_registry();
|
||||||
|
// Luego el registro del panel, cuyas acciones de declaración pueden consultar ya el catálogo
|
||||||
|
// de permisos.
|
||||||
|
build_admin_registry();
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< CARGA LOS AJUSTES >**************************************************************************
|
// **< CARGA LOS AJUSTES >**************************************************************************
|
||||||
|
|
@ -224,7 +240,11 @@ pub async fn shutdown_extensions() {
|
||||||
|
|
||||||
// **< CONFIGURA LAS RUTAS >************************************************************************
|
// **< CONFIGURA LAS RUTAS >************************************************************************
|
||||||
|
|
||||||
pub fn configure_routes(router: Router) -> Router {
|
/// Añade las rutas de todas las extensiones, cada una con su acceso.
|
||||||
|
///
|
||||||
|
/// Devuelve un error si alguna ruta del panel de administración no se monta con
|
||||||
|
/// [`Routes::admin_route()`](crate::web::Routes::admin_route) o no cuelga de una página declarada.
|
||||||
|
pub fn configure_routes(router: Router) -> Result<Router, StartupError> {
|
||||||
// Sólo compila durante el desarrollo, para evitar errores 400 en la traza de eventos.
|
// Sólo compila durante el desarrollo, para evitar errores 400 en la traza de eventos.
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
let router = router.route(
|
let router = router.route(
|
||||||
|
|
@ -236,7 +256,9 @@ pub fn configure_routes(router: Router) -> Router {
|
||||||
.get()
|
.get()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
.fold(router, |r, e| e.configure_router(r))
|
.fold(Routes::new(router), |r, e| e.configure_router(r))
|
||||||
|
.into_router()
|
||||||
|
.map_err(StartupError::InvalidAdminRoutes)
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< CONFIGURA EL MIDDLEWARE GLOBAL >*************************************************************
|
// **< CONFIGURA EL MIDDLEWARE GLOBAL >*************************************************************
|
||||||
|
|
@ -251,7 +273,8 @@ pub fn configure_middleware(router: Router) -> Router {
|
||||||
.get()
|
.get()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
.fold(router, |r, e| e.configure_middleware(r))
|
.fold(Layers::new(router), |l, e| e.configure_middleware(l))
|
||||||
|
.into_router()
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< CONFIGURA LOS ARCHIVOS ESTÁTICOS >***********************************************************
|
// **< CONFIGURA LOS ARCHIVOS ESTÁTICOS >***********************************************************
|
||||||
|
|
@ -261,15 +284,15 @@ pub fn configure_middleware(router: Router) -> Router {
|
||||||
/// Se llama después de [`configure_middleware`], para que estas rutas no pasen por las capas de
|
/// Se llama después de [`configure_middleware`], para que estas rutas no pasen por las capas de
|
||||||
/// middleware de las extensiones.
|
/// middleware de las extensiones.
|
||||||
pub fn configure_static_files(router: Router) -> Router {
|
pub fn configure_static_files(router: Router) -> Router {
|
||||||
let router = EXTENSIONS
|
let files = EXTENSIONS
|
||||||
.get()
|
.get()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
.fold(router, |r, e| e.configure_static_files(r));
|
.fold(StaticFiles::new(router), |f, e| e.configure_static_files(f));
|
||||||
|
|
||||||
serve_static_files!(router, [&global::SETTINGS.dev.pagetop_static_dir, assets] => "/pagetop");
|
serve_static_files!(files, [&global::SETTINGS.dev.pagetop_static_dir, assets] => "/pagetop");
|
||||||
|
|
||||||
router
|
files.into_router()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ use crate::core::AnyInfo;
|
||||||
use crate::core::action::ActionBox;
|
use crate::core::action::ActionBox;
|
||||||
use crate::core::theme::ThemeRef;
|
use crate::core::theme::ThemeRef;
|
||||||
use crate::locale::Lc;
|
use crate::locale::Lc;
|
||||||
use crate::web::Router;
|
use crate::web::{Layers, Routes, StaticFiles};
|
||||||
|
|
||||||
/// Interfaz común que debe implementar cualquier extensión de PageTop.
|
/// Interfaz común que debe implementar cualquier extensión de PageTop.
|
||||||
///
|
///
|
||||||
|
|
@ -246,29 +246,30 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Registra rutas, servicios y capas de la extensión en el servidor web de la aplicación.
|
/// Registra las rutas de la extensión en el servidor web de la aplicación.
|
||||||
///
|
///
|
||||||
/// Recibe las rutas acumuladas hasta ese momento, añade lo que la extensión necesite y retorna
|
/// Recibe las rutas acumuladas hasta ese momento, añade las de la extensión y las devuelve. La
|
||||||
/// las rutas con las nuevas modificaciones. La implementación por defecto devuelve las rutas
|
/// implementación por defecto las devuelve sin cambios.
|
||||||
/// sin cambios.
|
|
||||||
///
|
///
|
||||||
/// # Operaciones disponibles
|
/// Cada ruta se monta con su acceso ([`Access`]): quién puede llegar a su *handler*, que
|
||||||
|
/// PageTop comprueba antes. No hay forma de montar una sin indicarlo; una ruta pública se
|
||||||
|
/// monta con [`Routes::public_route()`], que equivale a [`Access::Public`]. Ver [`Routes`] para
|
||||||
|
/// las operaciones disponibles.
|
||||||
///
|
///
|
||||||
/// | Operación | Llamada sobre `router` |
|
/// Los archivos estáticos se registran en [`configure_static_files`], donde no pasan por el
|
||||||
/// |----------------------------------|----------------------------------------------------|
|
/// middleware de las extensiones.
|
||||||
/// | Ruta HTTP | `.route("/path", web::get(handler))` |
|
|
||||||
/// | Rutas bajo prefijo común | `.nest("/prefix", sub_router)` |
|
|
||||||
/// | Estado compartido entre handlers | `.with_state(my_state)` |
|
|
||||||
///
|
|
||||||
/// Los archivos estáticos se registran normalmente en [`configure_static_files`], donde no
|
|
||||||
/// pasan por el middleware de las extensiones.
|
|
||||||
///
|
///
|
||||||
/// # Ejemplos
|
/// # Ejemplos
|
||||||
///
|
///
|
||||||
/// ## Rutas HTTP básicas
|
/// ## Rutas con su acceso
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
/// # use pagetop::prelude::*;
|
/// # use pagetop::prelude::*;
|
||||||
|
/// # #[derive(Clone, Copy, Debug)]
|
||||||
|
/// # enum BlogPermission { Publish }
|
||||||
|
/// # impl Permission for BlogPermission {
|
||||||
|
/// # fn key(&self) -> CowStr { "blog:publish".into() }
|
||||||
|
/// # }
|
||||||
/// # async fn list_posts() -> &'static str { "" }
|
/// # async fn list_posts() -> &'static str { "" }
|
||||||
/// # async fn view_post() -> &'static str { "" }
|
/// # async fn view_post() -> &'static str { "" }
|
||||||
/// # async fn create_post() -> &'static str { "" }
|
/// # async fn create_post() -> &'static str { "" }
|
||||||
|
|
@ -276,45 +277,20 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
///
|
///
|
||||||
/// #[async_trait]
|
/// #[async_trait]
|
||||||
/// impl Extension for Blog {
|
/// impl Extension for Blog {
|
||||||
/// fn configure_router(&self, router: Router) -> Router {
|
/// fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
/// router
|
/// let publish = Access::Permission(&BlogPermission::Publish);
|
||||||
/// .route("/posts", web::get(list_posts))
|
/// routes
|
||||||
/// .route("/posts/{id}", web::get(view_post))
|
/// .public_route("/posts", web::get(list_posts))
|
||||||
/// .route("/posts/new", web::post(create_post))
|
/// .public_route("/posts/{id}", web::get(view_post))
|
||||||
|
/// .route("/posts/new", publish, web::post(create_post))
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// ## Rutas agrupadas bajo un prefijo
|
/// ## Rutas agrupadas con su propio middleware
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// Un `Router::new()` aparte, con sus capas, se añade bajo un prefijo con
|
||||||
/// # use pagetop::prelude::*;
|
/// [`Routes::nest()`]: sus capas sólo envuelven sus rutas, y todas comparten el mismo acceso.
|
||||||
/// # async fn dashboard() -> &'static str { "" }
|
|
||||||
/// # async fn list_users() -> &'static str { "" }
|
|
||||||
/// pub struct Admin;
|
|
||||||
///
|
|
||||||
/// #[async_trait]
|
|
||||||
/// impl Extension for Admin {
|
|
||||||
/// fn configure_router(&self, router: Router) -> Router {
|
|
||||||
/// let admin = Router::new()
|
|
||||||
/// .route("/dashboard", web::get(dashboard))
|
|
||||||
/// .route("/users", web::get(list_users));
|
|
||||||
///
|
|
||||||
/// router.nest("/admin", admin)
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ## Rutas con middleware acotado a esta extensión
|
|
||||||
///
|
|
||||||
/// Cada `Router` mantiene su propia pila de middleware independiente. Cuando se crea un
|
|
||||||
/// `Router::new()` separado y se llama a `.layer()` sobre él, esa capa sólo se aplica a las
|
|
||||||
/// rutas de ese router concreto. Al fusionarlo con `.merge()` en el `router` principal, cada
|
|
||||||
/// ruta se añade con su middleware asociado, sin tocar las demás.
|
|
||||||
///
|
|
||||||
/// Otra cosa es llamar a `.layer()` directamente sobre el `router` principal que se recibe como
|
|
||||||
/// parámetro, porque ese objeto ya contiene todas las rutas acumuladas por extensiones
|
|
||||||
/// anteriores, y la capa se aplica a todas las rutas, no sólo a las propias.
|
|
||||||
///
|
///
|
||||||
/// ```rust,ignore
|
/// ```rust,ignore
|
||||||
/// # use pagetop::prelude::*;
|
/// # use pagetop::prelude::*;
|
||||||
|
|
@ -322,11 +298,11 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
///
|
///
|
||||||
/// #[async_trait]
|
/// #[async_trait]
|
||||||
/// impl Extension for Api {
|
/// impl Extension for Api {
|
||||||
/// fn configure_router(&self, router: Router) -> Router {
|
/// fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
/// let api = Router::new()
|
/// let api = Router::new()
|
||||||
/// .route("/api/data", web::get(get_data))
|
/// .route("/data", web::get(get_data))
|
||||||
/// .layer(auth_layer());
|
/// .layer(api_key_layer());
|
||||||
/// router.merge(api)
|
/// routes.nest("/api", Access::Public, api)
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
|
|
@ -334,10 +310,15 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
/// Para el middleware que deba cubrir las rutas de **todas** las extensiones, usar
|
/// Para el middleware que deba cubrir las rutas de **todas** las extensiones, usar
|
||||||
/// [`configure_middleware`].
|
/// [`configure_middleware`].
|
||||||
///
|
///
|
||||||
|
/// [`Access`]: crate::auth::Access
|
||||||
|
/// [`Access::Public`]: crate::auth::Access::Public
|
||||||
|
/// [`Routes`]: crate::web::Routes
|
||||||
|
/// [`Routes::public_route()`]: crate::web::Routes::public_route
|
||||||
|
/// [`Routes::nest()`]: crate::web::Routes::nest
|
||||||
/// [`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, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router
|
routes
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Añade capas de middleware globales a las rutas de la aplicación.
|
/// Añade capas de middleware globales a las rutas de la aplicación.
|
||||||
|
|
@ -364,13 +345,16 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
///
|
///
|
||||||
/// #[async_trait]
|
/// #[async_trait]
|
||||||
/// impl Extension for MyAuth {
|
/// impl Extension for MyAuth {
|
||||||
/// fn configure_middleware(&self, router: Router) -> Router {
|
/// fn configure_middleware(&self, layers: Layers) -> Layers {
|
||||||
/// router.layer(web::middleware::from_fn(session_middleware))
|
/// layers.layer(web::middleware::from_fn(session_middleware))
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
fn configure_middleware(&self, router: Router) -> Router {
|
///
|
||||||
router
|
/// Sólo admite capas ([`Layers`](crate::web::Layers)): las rutas se registran en
|
||||||
|
/// [`configure_router`](Self::configure_router), con su acceso.
|
||||||
|
fn configure_middleware(&self, layers: Layers) -> Layers {
|
||||||
|
layers
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Registra los archivos estáticos de la extensión (hojas de estilo, *scripts*, fuentes,
|
/// Registra los archivos estáticos de la extensión (hojas de estilo, *scripts*, fuentes,
|
||||||
|
|
@ -381,12 +365,13 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
/// **después** de [`configure_middleware`](Self::configure_middleware), así que estas rutas
|
/// **después** de [`configure_middleware`](Self::configure_middleware), así que estas rutas
|
||||||
/// **no** pasan por las capas de middleware de las extensiones (p. ej. la resolución de
|
/// **no** pasan por las capas de middleware de las extensiones (p. ej. la resolución de
|
||||||
/// sesión). Una página carga muchos recursos; sin esta separación, cada uno repetiría ese
|
/// sesión). Una página carga muchos recursos; sin esta separación, cada uno repetiría ese
|
||||||
/// trabajo, que no necesita. La implementación por defecto devuelve las rutas sin cambios.
|
/// trabajo, que no necesita. Por eso son siempre públicos. La implementación por defecto los
|
||||||
|
/// devuelve sin cambios.
|
||||||
///
|
///
|
||||||
/// Si algún archivo sí debe pasar por el middleware (p. ej. descargas que requieran una sesión
|
/// Si algún archivo debe pasar por el middleware o exigir un acceso (p. ej. descargas que
|
||||||
/// iniciada), se registra en [`configure_router`](Self::configure_router).
|
/// requieran una sesión iniciada), se registra en [`configure_router`](Self::configure_router).
|
||||||
///
|
///
|
||||||
/// La macro [`serve_static_files!`](crate::serve_static_files) sombrea `router` internamente,
|
/// La macro [`serve_static_files!`](crate::serve_static_files) sombrea `files` internamente,
|
||||||
/// por lo que el parámetro no necesita `mut`. Sí es necesario devolverlo al final.
|
/// por lo que el parámetro no necesita `mut`. Sí es necesario devolverlo al final.
|
||||||
///
|
///
|
||||||
/// # Ejemplo
|
/// # Ejemplo
|
||||||
|
|
@ -397,14 +382,14 @@ pub trait Extension: AnyInfo + Send + Sync {
|
||||||
///
|
///
|
||||||
/// #[async_trait]
|
/// #[async_trait]
|
||||||
/// impl Extension for MyExtension {
|
/// impl Extension for MyExtension {
|
||||||
/// fn configure_static_files(&self, router: Router) -> Router {
|
/// fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
||||||
/// serve_static_files!(router, [assets] => "/static");
|
/// serve_static_files!(files, [assets] => "/static");
|
||||||
/// router
|
/// files
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
fn configure_static_files(&self, router: Router) -> Router {
|
fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
||||||
router
|
files
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -54,8 +54,8 @@ struct HelloWorld;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for HelloWorld {
|
impl Extension for HelloWorld {
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/", web::get(hello_world))
|
routes.public_route("/", web::get(hello_world))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,7 @@ 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, Response, Router};
|
pub use crate::web::{HttpRequest, IntoResponse, Layers, Response, Router, Routes, StaticFiles};
|
||||||
|
|
||||||
pub use crate::core::{AnyCast, AnyInfo, TypeInfo};
|
pub use crate::core::{AnyCast, AnyInfo, TypeInfo};
|
||||||
|
|
||||||
|
|
|
||||||
35
src/web.rs
35
src/web.rs
|
|
@ -51,7 +51,7 @@ pub use axum::extract::multipart;
|
||||||
pub use axum::response::{IntoResponse, Response};
|
pub use axum::response::{IntoResponse, Response};
|
||||||
|
|
||||||
// Operaciones HTTP para registrar rutas.
|
// Operaciones HTTP para registrar rutas.
|
||||||
pub use axum::routing::{delete, get, patch, post, put};
|
pub use axum::routing::{MethodRouter, delete, get, patch, post, put};
|
||||||
|
|
||||||
// Middlewares de función (`from_fn`) y tipos asociados (`Next`).
|
// Middlewares de función (`from_fn`) y tipos asociados (`Next`).
|
||||||
pub use axum::middleware;
|
pub use axum::middleware;
|
||||||
|
|
@ -69,6 +69,10 @@ pub use download::Download;
|
||||||
mod csrf;
|
mod csrf;
|
||||||
pub(crate) use csrf::reject_cross_origin;
|
pub(crate) use csrf::reject_cross_origin;
|
||||||
|
|
||||||
|
// Rutas de las extensiones con su acceso, capas globales y archivos estáticos.
|
||||||
|
mod routes;
|
||||||
|
pub use routes::{Layers, Routes, StaticFiles};
|
||||||
|
|
||||||
use axum::body::Body;
|
use axum::body::Body;
|
||||||
use axum::extract::FromRequestParts;
|
use axum::extract::FromRequestParts;
|
||||||
|
|
||||||
|
|
@ -212,11 +216,18 @@ impl<S: Send + Sync> FromRequestParts<S> for HttpRequest {
|
||||||
parts: &mut http::request::Parts,
|
parts: &mut http::request::Parts,
|
||||||
_state: &S,
|
_state: &S,
|
||||||
) -> Result<Self, Self::Rejection> {
|
) -> Result<Self, Self::Rejection> {
|
||||||
Ok(HttpRequest(Arc::new(RequestParts {
|
Ok(HttpRequest::from_parts(parts))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HttpRequest {
|
||||||
|
// También la usa el *middleware* que comprueba el acceso de las rutas, antes del *handler*.
|
||||||
|
pub(crate) fn from_parts(parts: &http::request::Parts) -> Self {
|
||||||
|
HttpRequest(Arc::new(RequestParts {
|
||||||
uri: parts.uri.clone(),
|
uri: parts.uri.clone(),
|
||||||
headers: parts.headers.clone(),
|
headers: parts.headers.clone(),
|
||||||
extensions: parts.extensions.clone(),
|
extensions: parts.extensions.clone(),
|
||||||
})))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -373,7 +384,8 @@ impl tower::Service<http::Request<Body>> for ServeEmbedded {
|
||||||
/// Se usa normalmente en el método [`configure_static_files()`] de las extensiones, para que estas
|
/// Se usa normalmente en el método [`configure_static_files()`] de las extensiones, para que estas
|
||||||
/// rutas no pasen por su middleware.
|
/// rutas no pasen por su middleware.
|
||||||
///
|
///
|
||||||
/// La macro añade rutas al [`Router`] del primer argumento usando uno de los tres modos posibles:
|
/// La macro añade los archivos a los [`StaticFiles`] del primer argumento, siempre públicos, usando
|
||||||
|
/// uno de los tres modos posibles:
|
||||||
///
|
///
|
||||||
/// - **Sistema de ficheros o embebido** (`[$dir, $bundle]`): intenta servir los archivos desde el
|
/// - **Sistema de ficheros o embebido** (`[$dir, $bundle]`): intenta servir los archivos desde el
|
||||||
/// directorio `$dir`; si está vacío, no existe o no es un directorio, usa el conjunto de recursos
|
/// directorio `$dir`; si está vacío, no existe o no es un directorio, usa el conjunto de recursos
|
||||||
|
|
@ -385,7 +397,7 @@ impl tower::Service<http::Request<Body>> for ServeEmbedded {
|
||||||
///
|
///
|
||||||
/// # Argumentos
|
/// # Argumentos
|
||||||
///
|
///
|
||||||
/// * `$router` - Variable de tipo [`Router`] donde registrar las rutas.
|
/// * `$router` - Variable de tipo [`StaticFiles`] donde registrar los archivos.
|
||||||
/// * `$dir` - Ruta al directorio local con los archivos estáticos.
|
/// * `$dir` - Ruta al directorio local con los archivos estáticos.
|
||||||
/// * `$bundle` - Nombre del conjunto de recursos embebidos generado por `build.rs`.
|
/// * `$bundle` - Nombre del conjunto de recursos embebidos generado por `build.rs`.
|
||||||
/// * `$path` - Prefijo URL bajo el que se publicarán los archivos.
|
/// * `$path` - Prefijo URL bajo el que se publicarán los archivos.
|
||||||
|
|
@ -398,17 +410,17 @@ impl tower::Service<http::Request<Body>> for ServeEmbedded {
|
||||||
///
|
///
|
||||||
/// #[async_trait]
|
/// #[async_trait]
|
||||||
/// impl Extension for MyExtension {
|
/// impl Extension for MyExtension {
|
||||||
/// fn configure_static_files(&self, router: Router) -> Router {
|
/// fn configure_static_files(&self, files: StaticFiles) -> StaticFiles {
|
||||||
/// // Forma 1) Sistema de ficheros o embebido.
|
/// // Forma 1) Sistema de ficheros o embebido.
|
||||||
/// serve_static_files!(router, ["/var/www/static", assets] => "/public");
|
/// serve_static_files!(files, ["/var/www/static", assets] => "/public");
|
||||||
///
|
///
|
||||||
/// // Forma 2) Siempre embebido.
|
/// // Forma 2) Siempre embebido.
|
||||||
/// serve_static_files!(router, [assets] => "/public");
|
/// serve_static_files!(files, [assets] => "/public");
|
||||||
///
|
///
|
||||||
/// // Forma 3) Sólo sistema de ficheros (no requiere `assets`).
|
/// // Forma 3) Sólo sistema de ficheros (no requiere `assets`).
|
||||||
/// serve_static_files!(router, "/var/www/static" => "/public");
|
/// serve_static_files!(files, "/var/www/static" => "/public");
|
||||||
///
|
///
|
||||||
/// router
|
/// files
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
|
|
@ -614,7 +626,8 @@ pub mod test {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Construye un [`HttpRequest`](super::HttpRequest) listo para pasarlo a
|
/// Construye un [`HttpRequest`](super::HttpRequest) listo para pasarlo a
|
||||||
/// [`Context::new`](crate::core::component::Context::new) en tests unitarios de componentes.
|
/// [`Context::new`](crate::core::component::Context::new) en tests unitarios de
|
||||||
|
/// componentes.
|
||||||
pub fn to_http_request(self) -> super::HttpRequest {
|
pub fn to_http_request(self) -> super::HttpRequest {
|
||||||
let uri = self.uri.parse().unwrap();
|
let uri = self.uri.parse().unwrap();
|
||||||
super::HttpRequest(std::sync::Arc::new(super::RequestParts {
|
super::HttpRequest(std::sync::Arc::new(super::RequestParts {
|
||||||
|
|
|
||||||
320
src/web/routes.rs
Normal file
320
src/web/routes.rs
Normal file
|
|
@ -0,0 +1,320 @@
|
||||||
|
use crate::admin::{AdminRegistry, admin_path, strip_admin_path, undeclared_permission};
|
||||||
|
use crate::auth::{Access, PermissionRegistry, deny_access};
|
||||||
|
use crate::web::{HttpRequest, IntoResponse, Request, Response, Router, middleware};
|
||||||
|
use crate::{global, trace};
|
||||||
|
|
||||||
|
use axum::extract::State;
|
||||||
|
use axum::routing::{MethodRouter, Route};
|
||||||
|
use tower::{Layer, Service};
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::convert::Infallible;
|
||||||
|
|
||||||
|
// **< Routes >*************************************************************************************
|
||||||
|
|
||||||
|
/// Rutas de una extensión, cada una con el acceso que la habilita.
|
||||||
|
///
|
||||||
|
/// Es lo que recibe [`Extension::configure_router()`]. A diferencia del [`Router`] de Axum, no hay
|
||||||
|
/// forma de montar una ruta sin indicar quién puede acceder a ella ([`Access`]): PageTop lo
|
||||||
|
/// 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.
|
||||||
|
///
|
||||||
|
/// 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
|
||||||
|
/// sólo en la página. Montar una con cualquier otro método, o una que no cuelgue de ninguna página,
|
||||||
|
/// impide arrancar la aplicación.
|
||||||
|
///
|
||||||
|
/// # Ejemplo
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// # use pagetop::prelude::*;
|
||||||
|
/// # #[derive(Clone, Copy, Debug)]
|
||||||
|
/// # enum BlogPermission { Publish }
|
||||||
|
/// # impl Permission for BlogPermission {
|
||||||
|
/// # fn key(&self) -> CowStr { "blog:publish".into() }
|
||||||
|
/// # }
|
||||||
|
/// # async fn list_posts() -> &'static str { "" }
|
||||||
|
/// # async fn new_post_form() -> &'static str { "" }
|
||||||
|
/// # async fn new_post() -> &'static str { "" }
|
||||||
|
/// pub struct Blog;
|
||||||
|
///
|
||||||
|
/// #[async_trait]
|
||||||
|
/// impl Extension for Blog {
|
||||||
|
/// fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
|
/// routes
|
||||||
|
/// .public_route("/posts", web::get(list_posts))
|
||||||
|
/// .route(
|
||||||
|
/// "/posts/new",
|
||||||
|
/// Access::Permission(&BlogPermission::Publish),
|
||||||
|
/// web::get(new_post_form).post(new_post),
|
||||||
|
/// )
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// [`Extension::configure_router()`]: crate::core::extension::Extension::configure_router
|
||||||
|
/// [`admin_path`]: crate::global::AppSettings::admin_path
|
||||||
|
/// [`admin_route()`]: Self::admin_route
|
||||||
|
/// [`AdminPage`]: crate::admin::AdminPage
|
||||||
|
pub struct Routes {
|
||||||
|
router: Router,
|
||||||
|
// Rutas del panel de administración mal montadas, para detener el arranque.
|
||||||
|
invalid_admin: Vec<String>,
|
||||||
|
// Rutas que exigen un permiso que no está en el catálogo, por permiso, para avisar.
|
||||||
|
undeclared: BTreeMap<String, Vec<String>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Routes {
|
||||||
|
pub(crate) fn new(router: Router) -> Self {
|
||||||
|
Routes {
|
||||||
|
router,
|
||||||
|
invalid_admin: Vec::new(),
|
||||||
|
undeclared: BTreeMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Devuelve el router, o las rutas del panel de administración mal montadas. Antes avisa de los
|
||||||
|
// permisos que exigen las rutas sin estar en el catálogo: ninguna extensión de autenticación
|
||||||
|
// podría ofrecerlos para concederlos. Los de las rutas del panel los avisa su registro.
|
||||||
|
pub(crate) fn into_router(self) -> Result<Router, Vec<String>> {
|
||||||
|
for (key, paths) in &self.undeclared {
|
||||||
|
trace::warn!("{}", undeclared_permission(key, paths));
|
||||||
|
}
|
||||||
|
if self.invalid_admin.is_empty() {
|
||||||
|
Ok(self.router)
|
||||||
|
} else {
|
||||||
|
Err(self.invalid_admin)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Añade una ruta con su acceso y sus *handlers* por método (`web::get(...)`,
|
||||||
|
/// `web::get(...).post(...)`...).
|
||||||
|
///
|
||||||
|
/// Se puede llamar varias veces con la misma ruta y otros métodos, cada vez con su acceso: p.
|
||||||
|
/// ej. ver con un permiso y guardar con otro. Las rutas del panel de administración se montan
|
||||||
|
/// con [`admin_route()`](Self::admin_route).
|
||||||
|
pub fn route(mut self, path: &str, access: Access, method_router: MethodRouter) -> Self {
|
||||||
|
self.reject_admin(path, false);
|
||||||
|
self.check_declared(path, access);
|
||||||
|
self.router = self
|
||||||
|
.router
|
||||||
|
.route(path, protect_method(method_router, access));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Añade una ruta pública ([`Access::Public`]), a la que puede acceder cualquiera, también un
|
||||||
|
/// usuario anónimo.
|
||||||
|
///
|
||||||
|
/// Equivale a [`route()`](Self::route) con [`Access::Public`], que sigue sirviendo cuando el
|
||||||
|
/// acceso llega en una variable.
|
||||||
|
pub fn public_route(self, path: &str, method_router: MethodRouter) -> Self {
|
||||||
|
self.route(path, Access::Public, method_router)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Añade una ruta del panel de administración, relativa a su raíz, con sus *handlers* por
|
||||||
|
/// método.
|
||||||
|
///
|
||||||
|
/// Exige el permiso de la página declarada ([`AdminPage`]) de la que cuelga: la más cercana que
|
||||||
|
/// se encuentra al quitarle tramos por el final, tal como se monta, con sus parámetros
|
||||||
|
/// (`"user/users/{id}/edit"` cuelga de `"user/users"`). Si no cuelga de ninguna, la aplicación
|
||||||
|
/// no arranca; como las páginas se declaran con rutas fijas, tampoco cuelga una ruta con un
|
||||||
|
/// parámetro antes de cualquier página (`"{section}/list"`). Un permiso más concreto lo
|
||||||
|
/// comprueba el *handler* (ver [`require_permission()`](crate::auth::require_permission)).
|
||||||
|
///
|
||||||
|
/// [`AdminPage`]: crate::admin::AdminPage
|
||||||
|
pub fn admin_route(mut self, path: &str, method_router: MethodRouter) -> Self {
|
||||||
|
let full_path = admin_path(path);
|
||||||
|
let relative = strip_admin_path(&full_path).unwrap_or_default();
|
||||||
|
match AdminRegistry::global().nearest_page(relative) {
|
||||||
|
Some(page) => {
|
||||||
|
let access = Access::Permission(page.permission());
|
||||||
|
self.router = self
|
||||||
|
.router
|
||||||
|
.route(&full_path, protect_method(method_router, access));
|
||||||
|
}
|
||||||
|
None => self.invalid_admin.push(full_path),
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Añade un [`Router`] de Axum bajo un prefijo, con el mismo acceso para todas sus rutas.
|
||||||
|
///
|
||||||
|
/// Sirve para agrupar rutas con sus propias capas de *middleware* (p. ej. una API con su
|
||||||
|
/// autenticación). El prefijo no puede estar dentro del panel de administración ni contener su
|
||||||
|
/// raíz.
|
||||||
|
pub fn nest(mut self, path: &str, access: Access, router: Router) -> Self {
|
||||||
|
self.reject_admin(path, true);
|
||||||
|
self.check_declared(path, access);
|
||||||
|
self.router = self.router.nest(path, protect(router, access));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Añade un servicio de Tower bajo un prefijo, con el mismo acceso para todo lo que sirva (p.
|
||||||
|
/// ej. los recursos de un libro, o una interfaz web de otro *crate*).
|
||||||
|
///
|
||||||
|
/// El prefijo no puede estar dentro del panel de administración ni contener su raíz.
|
||||||
|
pub fn nest_service<S>(mut self, path: &str, access: Access, service: S) -> Self
|
||||||
|
where
|
||||||
|
S: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static,
|
||||||
|
S::Response: IntoResponse,
|
||||||
|
S::Future: Send + 'static,
|
||||||
|
{
|
||||||
|
self.reject_admin(path, true);
|
||||||
|
self.check_declared(path, access);
|
||||||
|
let nested = Router::new().nest_service(path, service);
|
||||||
|
self.router = self.router.merge(protect(nested, access));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_declared(&mut self, path: &str, access: Access) {
|
||||||
|
if let Access::Permission(perm) = access
|
||||||
|
&& !PermissionRegistry::global().has(perm)
|
||||||
|
{
|
||||||
|
self.undeclared
|
||||||
|
.entry(perm.key().into_owned())
|
||||||
|
.or_default()
|
||||||
|
.push(path.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Las rutas del panel sólo se montan con `admin_route()`. Un prefijo (`nested`) tampoco puede
|
||||||
|
// contener la raíz del panel, porque agruparía rutas del panel con otras.
|
||||||
|
fn reject_admin(&mut self, path: &str, nested: bool) {
|
||||||
|
let inside = strip_admin_path(path).is_some();
|
||||||
|
let contains_root = nested
|
||||||
|
&& global::SETTINGS
|
||||||
|
.app
|
||||||
|
.admin_path
|
||||||
|
.strip_prefix(path.trim_end_matches('/'))
|
||||||
|
.is_some_and(|rest| rest.starts_with('/'));
|
||||||
|
if inside || contains_root {
|
||||||
|
self.invalid_admin.push(path.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Con `layer()` y no `route_layer()`, que dejaría sin comprobar el *fallback* propio de las rutas
|
||||||
|
// (`web::get(...).fallback(...)`) o de un `Router` anidado. Un método no admitido también pasa
|
||||||
|
// antes por el acceso: quien no lo cumple no llega a saber qué métodos tiene la ruta.
|
||||||
|
fn protect_method(method_router: MethodRouter, access: Access) -> MethodRouter {
|
||||||
|
match access {
|
||||||
|
Access::Public => method_router,
|
||||||
|
_ => method_router.layer(middleware::from_fn_with_state(access, check_access)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn protect(router: Router, access: Access) -> Router {
|
||||||
|
match access {
|
||||||
|
Access::Public => router,
|
||||||
|
_ => router.layer(middleware::from_fn_with_state(access, check_access)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Comprueba el acceso de la ruta antes de llegar a su *handler*.
|
||||||
|
async fn check_access(
|
||||||
|
State(access): State<Access>,
|
||||||
|
request: Request,
|
||||||
|
next: middleware::Next,
|
||||||
|
) -> Response {
|
||||||
|
let (parts, body) = request.into_parts();
|
||||||
|
let http_request = HttpRequest::from_parts(&parts);
|
||||||
|
if access.allows(&http_request) {
|
||||||
|
next.run(Request::from_parts(parts, body)).await
|
||||||
|
} else {
|
||||||
|
deny_access(http_request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< Layers >*************************************************************************************
|
||||||
|
|
||||||
|
/// Capas de *middleware* globales, que envuelven todas las rutas de la aplicación.
|
||||||
|
///
|
||||||
|
/// Es lo que recibe [`Extension::configure_middleware()`]. Sólo admite capas: las rutas se montan
|
||||||
|
/// en [`Extension::configure_router()`], con su acceso ([`Routes`]).
|
||||||
|
///
|
||||||
|
/// [`Extension::configure_middleware()`]: crate::core::extension::Extension::configure_middleware
|
||||||
|
/// [`Extension::configure_router()`]: crate::core::extension::Extension::configure_router
|
||||||
|
pub struct Layers(Router);
|
||||||
|
|
||||||
|
impl Layers {
|
||||||
|
pub(crate) fn new(router: Router) -> Self {
|
||||||
|
Layers(router)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn into_router(self) -> Router {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Añade una capa de *middleware* (p. ej. `web::middleware::from_fn(...)`), igual que
|
||||||
|
/// [`Router::layer()`].
|
||||||
|
pub fn layer<L>(self, layer: L) -> Self
|
||||||
|
where
|
||||||
|
L: Layer<Route> + Clone + Send + Sync + 'static,
|
||||||
|
L::Service: Service<Request> + Clone + Send + Sync + 'static,
|
||||||
|
<L::Service as Service<Request>>::Response: IntoResponse + 'static,
|
||||||
|
<L::Service as Service<Request>>::Error: Into<Infallible> + 'static,
|
||||||
|
<L::Service as Service<Request>>::Future: Send + 'static,
|
||||||
|
{
|
||||||
|
Layers(self.0.layer(layer))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< StaticFiles >********************************************************************************
|
||||||
|
|
||||||
|
/// Archivos estáticos de una extensión, siempre públicos.
|
||||||
|
///
|
||||||
|
/// Es lo que recibe [`Extension::configure_static_files()`], y sólo se usa con la macro
|
||||||
|
/// [`serve_static_files!`](crate::serve_static_files): las demás rutas se montan en
|
||||||
|
/// [`Extension::configure_router()`], con su acceso ([`Routes`]).
|
||||||
|
///
|
||||||
|
/// [`Extension::configure_static_files()`]: crate::core::extension::Extension::configure_static_files
|
||||||
|
/// [`Extension::configure_router()`]: crate::core::extension::Extension::configure_router
|
||||||
|
pub struct StaticFiles(Router);
|
||||||
|
|
||||||
|
impl StaticFiles {
|
||||||
|
pub(crate) fn new(router: Router) -> Self {
|
||||||
|
StaticFiles(router)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn into_router(self) -> Router {
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
|
||||||
|
// La usa `serve_static_files!` con los servicios de archivos de PageTop.
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn nest_service<S>(self, path: &str, service: S) -> Self
|
||||||
|
where
|
||||||
|
S: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static,
|
||||||
|
S::Response: IntoResponse,
|
||||||
|
S::Future: Send + 'static,
|
||||||
|
{
|
||||||
|
StaticFiles(self.0.nest_service(path, service))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::CowStr;
|
||||||
|
use crate::auth::Permission;
|
||||||
|
use crate::web::get;
|
||||||
|
|
||||||
|
struct UndeclaredPermission;
|
||||||
|
|
||||||
|
impl Permission for UndeclaredPermission {
|
||||||
|
fn key(&self) -> CowStr {
|
||||||
|
"test:undeclared".into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn routes_with_permissions_missing_from_the_catalog_are_grouped_by_permission() {
|
||||||
|
let undeclared = Access::Permission(&UndeclaredPermission);
|
||||||
|
let routes = Routes::new(Router::new())
|
||||||
|
.route("/a", undeclared, get(|| async { "" }))
|
||||||
|
.route("/b", Access::Public, get(|| async { "" }))
|
||||||
|
.route("/c", undeclared, get(|| async { "" }));
|
||||||
|
assert_eq!(routes.undeclared.len(), 1);
|
||||||
|
assert_eq!(routes.undeclared["test:undeclared"], ["/a", "/c"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -6,8 +6,8 @@ struct PanicExtension;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for PanicExtension {
|
impl Extension for PanicExtension {
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/boom", web::get(boom))
|
routes.public_route("/boom", web::get(boom))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,15 +6,15 @@ struct FlashExtension;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for FlashExtension {
|
impl Extension for FlashExtension {
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router
|
routes
|
||||||
.route("/save", web::post(save))
|
.public_route("/save", web::post(save))
|
||||||
.route(
|
.public_route(
|
||||||
"/again",
|
"/again",
|
||||||
web::get(|| async { Redirect::see_other("/done") }),
|
web::get(|| async { Redirect::see_other("/done") }),
|
||||||
)
|
)
|
||||||
.route("/done", web::get(done))
|
.public_route("/done", web::get(done))
|
||||||
.route("/file", web::get(|| async { "plain text" }))
|
.public_route("/file", web::get(|| async { "plain text" }))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -25,12 +25,12 @@ struct MarkingExtension;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for MarkingExtension {
|
impl Extension for MarkingExtension {
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route("/page", web::get(|| async { "page" }))
|
routes.public_route("/page", web::get(|| async { "page" }))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_middleware(&self, router: Router) -> Router {
|
fn configure_middleware(&self, layers: Layers) -> Layers {
|
||||||
router.layer(web::middleware::from_fn(mark_response))
|
layers.layer(web::middleware::from_fn(mark_response))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -18,15 +18,15 @@ struct ActionExtension;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for ActionExtension {
|
impl Extension for ActionExtension {
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route(
|
routes.public_route(
|
||||||
"/action/{name}",
|
"/action/{name}",
|
||||||
web::get(|| async { "read" }).post(|| async { "done" }),
|
web::get(|| async { "read" }).post(|| async { "done" }),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn configure_middleware(&self, router: Router) -> Router {
|
fn configure_middleware(&self, layers: Layers) -> Layers {
|
||||||
router.layer(web::middleware::from_fn(record_path))
|
layers.layer(web::middleware::from_fn(record_path))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
151
tests/web_routes_access.rs
Normal file
151
tests/web_routes_access.rs
Normal file
|
|
@ -0,0 +1,151 @@
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Offers the login form to an anonymous user without access, as an authentication extension would.
|
||||||
|
fn offer_login(_: &HttpRequest) -> Option<Response> {
|
||||||
|
Some(Redirect::see_other("/login"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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"
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Ext;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for Ext {
|
||||||
|
fn actions(&self) -> Vec<ActionBox> {
|
||||||
|
actions![
|
||||||
|
action::auth::CheckPermission::new(grant),
|
||||||
|
action::auth::AnonymousDenied::new(offer_login),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
|
routes
|
||||||
|
.public_route("/public", web::get(ok))
|
||||||
|
.route("/account", Access::Authenticated, web::get(ok))
|
||||||
|
.route("/granted", Access::Permission(&Granted), web::get(ok))
|
||||||
|
.route("/denied", Access::Permission(&Denied), web::get(ok))
|
||||||
|
// Reading is public, writing needs a permission that nobody has.
|
||||||
|
.public_route("/notes", web::get(ok))
|
||||||
|
.route("/notes", Access::Permission(&Denied), web::post(ok))
|
||||||
|
// Their own fallbacks require the access too.
|
||||||
|
.route(
|
||||||
|
"/hooks",
|
||||||
|
Access::Permission(&Denied),
|
||||||
|
web::get(ok).fallback(ok),
|
||||||
|
)
|
||||||
|
.nest(
|
||||||
|
"/api",
|
||||||
|
Access::Permission(&Denied),
|
||||||
|
Router::new().route("/data", web::get(ok)).fallback(ok),
|
||||||
|
)
|
||||||
|
.nest_service("/files", Access::Authenticated, web::ServeDir::new("tests"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configure_middleware(&self, layers: Layers) -> Layers {
|
||||||
|
layers.layer(web::middleware::from_fn(sign_in))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send(method: &str, uri: &str, user: bool) -> (u16, Option<String>) {
|
||||||
|
let app = Application::prepare(&Ext).await.test();
|
||||||
|
let request = if method == "POST" {
|
||||||
|
web::test::TestRequest::post()
|
||||||
|
} else {
|
||||||
|
web::test::TestRequest::get()
|
||||||
|
};
|
||||||
|
let request = if user {
|
||||||
|
request.header("x-user", "1")
|
||||||
|
} else {
|
||||||
|
request
|
||||||
|
};
|
||||||
|
let response = web::test::send_request(&app, request.uri(uri).to_request()).await;
|
||||||
|
let location = response
|
||||||
|
.headers()
|
||||||
|
.get("location")
|
||||||
|
.map(|value| value.to_str().unwrap().to_owned());
|
||||||
|
(response.status().as_u16(), location)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn a_public_route_is_open_to_everybody() {
|
||||||
|
assert_eq!(send("GET", "/public", false).await.0, 200);
|
||||||
|
assert_eq!(send("GET", "/public", true).await.0, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn an_anonymous_user_without_access_gets_the_response_of_the_action() {
|
||||||
|
let login = (303, Some("/login".to_owned()));
|
||||||
|
assert_eq!(send("GET", "/account", false).await, login);
|
||||||
|
assert_eq!(send("GET", "/denied", false).await, login);
|
||||||
|
// A granted permission does not need a session.
|
||||||
|
assert_eq!(send("GET", "/granted", false).await.0, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn an_authenticated_user_without_access_gets_access_denied() {
|
||||||
|
assert_eq!(send("GET", "/account", true).await.0, 200);
|
||||||
|
assert_eq!(send("GET", "/granted", true).await.0, 200);
|
||||||
|
assert_eq!(send("GET", "/denied", true).await.0, 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn each_method_of_a_route_has_its_own_access() {
|
||||||
|
assert_eq!(send("GET", "/notes", true).await.0, 200);
|
||||||
|
assert_eq!(send("POST", "/notes", true).await.0, 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn the_fallback_of_a_route_requires_its_access() {
|
||||||
|
assert_eq!(send("POST", "/hooks", true).await.0, 403);
|
||||||
|
assert_eq!(send("GET", "/api/other", true).await.0, 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn nested_routers_and_services_share_the_access_of_the_prefix() {
|
||||||
|
assert_eq!(send("GET", "/api/data", true).await.0, 403);
|
||||||
|
assert_eq!(
|
||||||
|
send("GET", "/files/web_routes_access.rs", true).await.0,
|
||||||
|
200
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
send("GET", "/files/web_routes_access.rs", false).await.0,
|
||||||
|
303
|
||||||
|
);
|
||||||
|
// Routes that are not mounted are not affected.
|
||||||
|
assert_eq!(send("GET", "/missing", true).await.0, 404);
|
||||||
|
}
|
||||||
|
|
@ -18,8 +18,8 @@ struct Echo;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for Echo {
|
impl Extension for Echo {
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router.route(
|
routes.public_route(
|
||||||
"/item",
|
"/item",
|
||||||
web::get(|| async { "get" })
|
web::get(|| async { "get" })
|
||||||
.post(echo)
|
.post(echo)
|
||||||
|
|
|
||||||
|
|
@ -78,15 +78,15 @@ struct Uploads;
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Extension for Uploads {
|
impl Extension for Uploads {
|
||||||
fn configure_router(&self, router: Router) -> Router {
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
router
|
routes
|
||||||
.route(
|
.public_route(
|
||||||
"/plain",
|
"/plain",
|
||||||
web::post(|multipart: web::Multipart| {
|
web::post(|multipart: web::Multipart| {
|
||||||
save_all(web::Upload::new().with_subdir("plain"), multipart)
|
save_all(web::Upload::new().with_subdir("plain"), multipart)
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.route(
|
.public_route(
|
||||||
"/images",
|
"/images",
|
||||||
web::post(|multipart: web::Multipart| {
|
web::post(|multipart: web::Multipart| {
|
||||||
let upload = web::Upload::new()
|
let upload = web::Upload::new()
|
||||||
|
|
@ -95,20 +95,20 @@ impl Extension for Uploads {
|
||||||
save_all(upload, multipart)
|
save_all(upload, multipart)
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.route(
|
.public_route(
|
||||||
"/small",
|
"/small",
|
||||||
web::post(|multipart: web::Multipart| {
|
web::post(|multipart: web::Multipart| {
|
||||||
let upload = web::Upload::new().with_subdir("small").with_max_size(4);
|
let upload = web::Upload::new().with_subdir("small").with_max_size(4);
|
||||||
save_all(upload, multipart)
|
save_all(upload, multipart)
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.route(
|
.public_route(
|
||||||
"/escape",
|
"/escape",
|
||||||
web::post(|multipart: web::Multipart| {
|
web::post(|multipart: web::Multipart| {
|
||||||
save_all(web::Upload::new().with_subdir("../escape"), multipart)
|
save_all(web::Upload::new().with_subdir("../escape"), multipart)
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.route(
|
.public_route(
|
||||||
"/receive/{subdir}",
|
"/receive/{subdir}",
|
||||||
web::post(
|
web::post(
|
||||||
|web::Path(subdir): web::Path<String>, multipart: web::Multipart| {
|
|web::Path(subdir): web::Path<String>, multipart: web::Multipart| {
|
||||||
|
|
@ -116,7 +116,7 @@ impl Extension for Uploads {
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.route(
|
.public_route(
|
||||||
"/form",
|
"/form",
|
||||||
web::post(
|
web::post(
|
||||||
|web::Form(form): web::Form<Vec<(String, String)>>| async move {
|
|web::Form(form): web::Form<Vec<(String, String)>>| async move {
|
||||||
|
|
@ -124,13 +124,13 @@ impl Extension for Uploads {
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.route(
|
.public_route(
|
||||||
"/files/{*path}",
|
"/files/{*path}",
|
||||||
web::get(|request: HttpRequest, web::Path(path): web::Path<String>| {
|
web::get(|request: HttpRequest, web::Path(path): web::Path<String>| {
|
||||||
serve(request, web::Download::new(path))
|
serve(request, web::Download::new(path))
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.route(
|
.public_route(
|
||||||
"/named/{*path}",
|
"/named/{*path}",
|
||||||
web::get(|request: HttpRequest, web::Path(path): web::Path<String>| {
|
web::get(|request: HttpRequest, web::Path(path): web::Path<String>| {
|
||||||
serve(
|
serve(
|
||||||
|
|
@ -139,7 +139,7 @@ impl Extension for Uploads {
|
||||||
)
|
)
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.route(
|
.public_route(
|
||||||
"/attach/{*path}",
|
"/attach/{*path}",
|
||||||
web::get(|request: HttpRequest, web::Path(path): web::Path<String>| {
|
web::get(|request: HttpRequest, web::Path(path): web::Path<String>| {
|
||||||
serve(request, web::Download::new(path).with_attachment(true))
|
serve(request, web::Download::new(path).with_attachment(true))
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue