Compare commits
6 commits
9c77a664f8
...
d83f8b0f7f
| Author | SHA1 | Date | |
|---|---|---|---|
| d83f8b0f7f | |||
| 8761c50fbb | |||
| 105d5a81af | |||
| a29f0f2b75 | |||
| 0472e698ae | |||
| 4603152075 |
58 changed files with 1776 additions and 411 deletions
|
|
@ -17,6 +17,7 @@
|
||||||
// Components, in alphabetical order. `buttons` must go before `dropdown` and `nav`, see the notes
|
// Components, in alphabetical order. `buttons` must go before `dropdown` and `nav`, see the notes
|
||||||
// in `basic/_buttons.scss`.
|
// in `basic/_buttons.scss`.
|
||||||
@use "basic/badge";
|
@use "basic/badge";
|
||||||
|
@use "basic/block";
|
||||||
@use "basic/brand";
|
@use "basic/brand";
|
||||||
@use "basic/breadcrumb";
|
@use "basic/breadcrumb";
|
||||||
@use "basic/buttons";
|
@use "basic/buttons";
|
||||||
|
|
|
||||||
|
|
@ -16,8 +16,10 @@ body {
|
||||||
-webkit-tap-highlight-color: transparent;
|
-webkit-tap-highlight-color: transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Header, Aside, Content and Footer are stacked in that order, using the full available width.
|
// Header, Aside, Content and Footer are stacked in that order, using the full available width, with
|
||||||
|
// side padding (the same as containers) so the content never touches the edges of the screen.
|
||||||
.wrapper {
|
.wrapper {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
padding-inline: 1rem;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
4
assets/scss/basic/_block.scss
Normal file
4
assets/scss/basic/_block.scss
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
// Space below each block, so consecutive blocks (and what follows them) do not sit right together.
|
||||||
|
.block {
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
@ -3,9 +3,17 @@
|
||||||
margin-left: 0.25rem;
|
margin-left: 0.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Fields are spaced below, as in Bootsier, so the first one of a form or a fieldset starts right
|
||||||
|
// at its top; the last one leaves no gap.
|
||||||
|
.form-field {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
.form-field:last-child {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
.form-label {
|
.form-label {
|
||||||
display: block;
|
display: block;
|
||||||
margin-top: 1em;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.form-text {
|
.form-text {
|
||||||
|
|
@ -25,7 +33,7 @@
|
||||||
}
|
}
|
||||||
|
|
||||||
fieldset {
|
fieldset {
|
||||||
margin: 2rem 0 1rem;
|
margin: 0 0 1rem;
|
||||||
background: var(--val-color--bg);
|
background: var(--val-color--bg);
|
||||||
}
|
}
|
||||||
fieldset > legend {
|
fieldset > legend {
|
||||||
|
|
@ -42,10 +50,6 @@ fieldset > legend {
|
||||||
min-height: 1.5rem;
|
min-height: 1.5rem;
|
||||||
margin-bottom: 0.25rem;
|
margin-bottom: 0.25rem;
|
||||||
}
|
}
|
||||||
// A single checkbox has no label above it to give it room, as the other fields do.
|
|
||||||
.form-field.form-check:not(.form-check-inline) {
|
|
||||||
margin-top: 1em;
|
|
||||||
}
|
|
||||||
.form-check-inline {
|
.form-check-inline {
|
||||||
display: inline-grid;
|
display: inline-grid;
|
||||||
margin-right: 1rem;
|
margin-right: 1rem;
|
||||||
|
|
|
||||||
|
|
@ -1,10 +1,11 @@
|
||||||
@use "breakpoints" as bp;
|
@use "breakpoints" as bp;
|
||||||
|
|
||||||
|
// No side padding, so the bar lines up with the rest of the page (fixed bars below get it back).
|
||||||
.navbar {
|
.navbar {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 1rem;
|
gap: 1rem;
|
||||||
padding: 0.5rem 1rem;
|
padding-block: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.navbar-toggle {
|
.navbar-toggle {
|
||||||
|
|
@ -53,12 +54,14 @@
|
||||||
.navbar.sticky-bottom {
|
.navbar.sticky-bottom {
|
||||||
background-color: var(--val-color--bg);
|
background-color: var(--val-color--bg);
|
||||||
}
|
}
|
||||||
|
// Fixed bars span the whole viewport, so they keep some side padding off its edges.
|
||||||
.navbar.fixed-top,
|
.navbar.fixed-top,
|
||||||
.navbar.fixed-bottom {
|
.navbar.fixed-bottom {
|
||||||
position: fixed;
|
position: fixed;
|
||||||
right: 0;
|
right: 0;
|
||||||
left: 0;
|
left: 0;
|
||||||
z-index: 1030;
|
z-index: 1030;
|
||||||
|
padding-inline: 1rem;
|
||||||
}
|
}
|
||||||
.navbar.fixed-top {
|
.navbar.fixed-top {
|
||||||
top: 0;
|
top: 0;
|
||||||
|
|
|
||||||
|
|
@ -33,8 +33,10 @@
|
||||||
margin-inline-end: 0;
|
margin-inline-end: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Cells wrap onto more lines when they don't fit, so a long pager never gets wider than the screen.
|
||||||
.pagination {
|
.pagination {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 0.25rem;
|
gap: 0.25rem;
|
||||||
list-style: none;
|
list-style: none;
|
||||||
|
|
@ -94,6 +96,11 @@
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
}
|
}
|
||||||
|
// The page number is a form field: without the bottom margin fields take elsewhere, so it lines up
|
||||||
|
// with the button.
|
||||||
|
.pager-jump-input {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
.pager-jump:focus-within {
|
.pager-jump:focus-within {
|
||||||
border-radius: 0.375rem;
|
border-radius: 0.375rem;
|
||||||
box-shadow: 0 0 0 0.2rem color-mix(in srgb, var(--val-color--primary) 25%, transparent);
|
box-shadow: 0 0 0 0.2rem color-mix(in srgb, var(--val-color--primary) 25%, transparent);
|
||||||
|
|
|
||||||
|
|
@ -35,9 +35,6 @@
|
||||||
|
|
||||||
[app]
|
[app]
|
||||||
name = "PageTop App" # Nombre de la aplicación.
|
name = "PageTop App" # Nombre de la aplicación.
|
||||||
theme = "Basic" # Tema predeterminado: "Basic" o el de una extensión enlazada
|
|
||||||
# por la aplicación ("Aliner", "Bootsier"...). Si no está
|
|
||||||
# habilitado se usa "Basic", con un aviso al arrancar.
|
|
||||||
#language = "es-ES" # Idioma predeterminado (BCP 47: "es-ES", "en-US"...). Sin
|
#language = "es-ES" # Idioma predeterminado (BCP 47: "es-ES", "en-US"...). Sin
|
||||||
# valor, o si no es válido, el idioma se negocia con otras
|
# valor, o si no es válido, el idioma se negocia con otras
|
||||||
# fuentes (cabecera Accept-Language, idioma de respaldo).
|
# fuentes (cabecera Accept-Language, idioma de respaldo).
|
||||||
|
|
@ -76,6 +73,14 @@ timezone_order = "Nearest" # Orden de esas regiones al elegir zona h
|
||||||
timezone_per_user = true # Si cada usuario puede tener su propia zona horaria (true) o
|
timezone_per_user = true # Si cada usuario puede tener su propia zona horaria (true) o
|
||||||
# se usa siempre 'timezone' (false). Con false no se ofrece
|
# se usa siempre 'timezone' (false). Con false no se ofrece
|
||||||
# elegirla y la guardada se conserva por si se reactiva.
|
# elegirla y la guardada se conserva por si se reactiva.
|
||||||
|
theme = "Basic" # Tema predeterminado: "Basic" o el de una extensión enlazada
|
||||||
|
# por la aplicación ("Aliner", "Bootsier"...). Si no está
|
||||||
|
# habilitado se usa "Basic", con un aviso al arrancar.
|
||||||
|
# Se aplica a anónimos y a usuarios sin tema propio, y a
|
||||||
|
# todos si 'theme_per_user' es false.
|
||||||
|
theme_per_user = false # Si cada usuario puede tener su propio tema (true) o se usa
|
||||||
|
# siempre 'theme' (false). Con false no se ofrece elegirlo y
|
||||||
|
# el guardado se conserva por si se activa.
|
||||||
admin_path = "/admin" # Ruta raíz del panel de administración. Debe empezar por
|
admin_path = "/admin" # Ruta raíz del panel de administración. Debe empezar por
|
||||||
# "/", sin "/" final; cada tramo sólo admite letras y dígitos
|
# "/", sin "/" final; cada tramo sólo admite letras y dígitos
|
||||||
# ASCII, "-", "_", "." y "~" (sin ser "." ni ".."). Una no
|
# ASCII, "-", "_", "." y "~" (sin ser "." ni ".."). Una no
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,7 @@
|
||||||
[app]
|
[app]
|
||||||
name = "Testing"
|
name = "Testing"
|
||||||
|
# Lets the tests check that a user's own theme is applied (it is off by default).
|
||||||
|
theme_per_user = true
|
||||||
|
|
||||||
[server]
|
[server]
|
||||||
bind_port = 9000
|
bind_port = 9000
|
||||||
|
|
|
||||||
72
examples/locale/en-US/theme-showcase.ftl
Normal file
72
examples/locale/en-US/theme-showcase.ftl
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
showcase_title = Theme showcase
|
||||||
|
|
||||||
|
showcase_menu_home = Home
|
||||||
|
showcase_menu_components = Components
|
||||||
|
showcase_menu_forms = Forms
|
||||||
|
showcase_menu_fields = Fields
|
||||||
|
showcase_menu_buttons = Buttons
|
||||||
|
showcase_menu_others = Others
|
||||||
|
showcase_menu_messages = Messages
|
||||||
|
showcase_menu_disabled = Disabled
|
||||||
|
showcase_menu_docs = Documentation
|
||||||
|
showcase_menu_sign_up = Sign up
|
||||||
|
showcase_menu_login = Log in
|
||||||
|
|
||||||
|
showcase_block_fields = Text fields and dropdowns
|
||||||
|
showcase_name = Name
|
||||||
|
showcase_name_help = Help text, smaller and lighter than the label.
|
||||||
|
showcase_email = Email
|
||||||
|
showcase_email_placeholder = name@example.com
|
||||||
|
showcase_focus = With focus
|
||||||
|
showcase_font = Font
|
||||||
|
showcase_disabled = Disabled
|
||||||
|
showcase_readonly = Read-only
|
||||||
|
showcase_disabled_select = Disabled dropdown
|
||||||
|
showcase_comment = Comment
|
||||||
|
showcase_comment_placeholder = Write here...
|
||||||
|
showcase_floating = Floating label
|
||||||
|
|
||||||
|
showcase_block_checks = Checks, switches and options
|
||||||
|
showcase_checks = Checks
|
||||||
|
showcase_check_off = Unchecked
|
||||||
|
showcase_check_on = Checked
|
||||||
|
showcase_check_disabled = Disabled
|
||||||
|
showcase_switches = Switches
|
||||||
|
showcase_switch_off = Off
|
||||||
|
showcase_switch_on = On
|
||||||
|
showcase_switch_disabled = Disabled
|
||||||
|
showcase_options = Options
|
||||||
|
showcase_option_small = Small
|
||||||
|
showcase_option_medium = Medium
|
||||||
|
showcase_option_large = Large
|
||||||
|
showcase_options_help = The disabled option cannot be chosen.
|
||||||
|
|
||||||
|
showcase_filter_hint =
|
||||||
|
Change a value without pressing "Filter": the filter marks the changed fields and highlights
|
||||||
|
its button until it is applied.
|
||||||
|
showcase_search = Search
|
||||||
|
showcase_search_placeholder = Name or email...
|
||||||
|
showcase_status = Status
|
||||||
|
showcase_status_any = Any
|
||||||
|
showcase_status_active = Active
|
||||||
|
showcase_status_blocked = Blocked
|
||||||
|
showcase_only_admins = Administrators only
|
||||||
|
|
||||||
|
showcase_block_tables = List filters and tables
|
||||||
|
showcase_new_user = New user
|
||||||
|
showcase_col_user = User
|
||||||
|
showcase_col_email = Email
|
||||||
|
showcase_col_status = Status
|
||||||
|
showcase_col_last_access = Last access
|
||||||
|
showcase_col_actions = Actions
|
||||||
|
showcase_status_pending = Pending
|
||||||
|
showcase_edit = Edit
|
||||||
|
showcase_empty_table = A table without rows shows its message:
|
||||||
|
|
||||||
|
showcase_block_buttons = Buttons
|
||||||
|
|
||||||
|
showcase_block_misc = Links, badges and pagination
|
||||||
|
showcase_link_text = A paragraph with <a href="#">a link</a> in the middle of the text.
|
||||||
|
showcase_msg_info = An informative message.
|
||||||
|
showcase_msg_warning = A warning message.
|
||||||
|
showcase_msg_error = An error message.
|
||||||
72
examples/locale/es-ES/theme-showcase.ftl
Normal file
72
examples/locale/es-ES/theme-showcase.ftl
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
showcase_title = Muestrario del tema
|
||||||
|
|
||||||
|
showcase_menu_home = Inicio
|
||||||
|
showcase_menu_components = Componentes
|
||||||
|
showcase_menu_forms = Formularios
|
||||||
|
showcase_menu_fields = Campos
|
||||||
|
showcase_menu_buttons = Botones
|
||||||
|
showcase_menu_others = Otros
|
||||||
|
showcase_menu_messages = Mensajes
|
||||||
|
showcase_menu_disabled = Deshabilitado
|
||||||
|
showcase_menu_docs = Documentación
|
||||||
|
showcase_menu_sign_up = Registrarse
|
||||||
|
showcase_menu_login = Iniciar sesión
|
||||||
|
|
||||||
|
showcase_block_fields = Campos de texto y listas
|
||||||
|
showcase_name = Nombre
|
||||||
|
showcase_name_help = Texto de ayuda, más pequeño y claro que la etiqueta.
|
||||||
|
showcase_email = Correo electrónico
|
||||||
|
showcase_email_placeholder = nombre@ejemplo.com
|
||||||
|
showcase_focus = Con el foco
|
||||||
|
showcase_font = Fuente
|
||||||
|
showcase_disabled = Deshabilitado
|
||||||
|
showcase_readonly = Sólo lectura
|
||||||
|
showcase_disabled_select = Lista deshabilitada
|
||||||
|
showcase_comment = Comentario
|
||||||
|
showcase_comment_placeholder = Escribe aquí...
|
||||||
|
showcase_floating = Etiqueta flotante
|
||||||
|
|
||||||
|
showcase_block_checks = Casillas, interruptores y opciones
|
||||||
|
showcase_checks = Casillas
|
||||||
|
showcase_check_off = Sin marcar
|
||||||
|
showcase_check_on = Marcada
|
||||||
|
showcase_check_disabled = Deshabilitada
|
||||||
|
showcase_switches = Interruptores
|
||||||
|
showcase_switch_off = Apagado
|
||||||
|
showcase_switch_on = Encendido
|
||||||
|
showcase_switch_disabled = Deshabilitado
|
||||||
|
showcase_options = Opciones
|
||||||
|
showcase_option_small = Pequeño
|
||||||
|
showcase_option_medium = Mediano
|
||||||
|
showcase_option_large = Grande
|
||||||
|
showcase_options_help = La opción deshabilitada no se puede elegir.
|
||||||
|
|
||||||
|
showcase_filter_hint =
|
||||||
|
Cambia algún valor sin pulsar «Filtrar»: el filtro marca los campos cambiados y destaca su
|
||||||
|
botón hasta que se aplica.
|
||||||
|
showcase_search = Buscar
|
||||||
|
showcase_search_placeholder = Nombre o correo...
|
||||||
|
showcase_status = Estado
|
||||||
|
showcase_status_any = Cualquiera
|
||||||
|
showcase_status_active = Activo
|
||||||
|
showcase_status_blocked = Bloqueado
|
||||||
|
showcase_only_admins = Sólo administradores
|
||||||
|
|
||||||
|
showcase_block_tables = Filtros de listados y tablas
|
||||||
|
showcase_new_user = Nuevo usuario
|
||||||
|
showcase_col_user = Usuario
|
||||||
|
showcase_col_email = Correo electrónico
|
||||||
|
showcase_col_status = Estado
|
||||||
|
showcase_col_last_access = Último acceso
|
||||||
|
showcase_col_actions = Acciones
|
||||||
|
showcase_status_pending = Pendiente
|
||||||
|
showcase_edit = Editar
|
||||||
|
showcase_empty_table = Una tabla sin filas muestra su mensaje:
|
||||||
|
|
||||||
|
showcase_block_buttons = Botones
|
||||||
|
|
||||||
|
showcase_block_misc = Enlaces, insignias y paginación
|
||||||
|
showcase_link_text = Un párrafo con <a href="#">un enlace</a> en medio del texto.
|
||||||
|
showcase_msg_info = Un mensaje informativo.
|
||||||
|
showcase_msg_warning = Un mensaje de aviso.
|
||||||
|
showcase_msg_error = Un mensaje de error.
|
||||||
488
examples/theme-showcase.rs
Normal file
488
examples/theme-showcase.rs
Normal file
|
|
@ -0,0 +1,488 @@
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_bootsier::theme::*;
|
||||||
|
|
||||||
|
include_locales!(LOC from "examples/locale");
|
||||||
|
|
||||||
|
struct ThemeShowcase;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for ThemeShowcase {
|
||||||
|
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
vec![&pagetop_bootsier::Bootsier]
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn initialize(&self) -> Result<(), BoxError> {
|
||||||
|
let brand = Brand::new()
|
||||||
|
.with_image(
|
||||||
|
// Recuadro en el color primario de Bootsier (petróleo, `#0e6973`), con la línea
|
||||||
|
// clara que elige el logotipo por contraste. Se ve igual en los dos modos de color.
|
||||||
|
Image::with(image::Source::logo(PageTopSvg::TileRGB(14, 105, 115)))
|
||||||
|
.with_size(image::Size::Both(UnitValue::Px(36))),
|
||||||
|
)
|
||||||
|
.with_title(Lc::n("PageTop"))
|
||||||
|
.with_route(Route::from("/"));
|
||||||
|
|
||||||
|
// Menú completo: enlace activo, desplegable con secciones, enlace externo y deshabilitado.
|
||||||
|
// Ocupa el espacio libre entre la marca y el menú de la cuenta, con sus opciones centradas.
|
||||||
|
let main_menu = Nav::new()
|
||||||
|
.with_layout(nav::Layout::Center)
|
||||||
|
.with_prop(FlexItem::new().with_grow(flex::ItemGrow::Is1))
|
||||||
|
.with_item(nav::Item::link(Lc::t("showcase_menu_home", &LOC), "/").with_active(true))
|
||||||
|
.with_item(nav::Item::dropdown(
|
||||||
|
Dropdown::new()
|
||||||
|
.with_title(Lc::t("showcase_menu_components", &LOC))
|
||||||
|
.with_item(dropdown::Item::header(Lc::t("showcase_menu_forms", &LOC)))
|
||||||
|
.with_item(dropdown::Item::link(
|
||||||
|
Lc::t("showcase_menu_fields", &LOC),
|
||||||
|
"#",
|
||||||
|
))
|
||||||
|
.with_item(dropdown::Item::link(
|
||||||
|
Lc::t("showcase_menu_buttons", &LOC),
|
||||||
|
"#",
|
||||||
|
))
|
||||||
|
.with_item(dropdown::Item::divider())
|
||||||
|
.with_item(dropdown::Item::header(Lc::t("showcase_menu_others", &LOC)))
|
||||||
|
.with_item(dropdown::Item::link(
|
||||||
|
Lc::t("showcase_menu_messages", &LOC),
|
||||||
|
"#",
|
||||||
|
))
|
||||||
|
.with_item(dropdown::Item::link_disabled(
|
||||||
|
Lc::t("showcase_menu_disabled", &LOC),
|
||||||
|
"#",
|
||||||
|
)),
|
||||||
|
))
|
||||||
|
.with_item(nav::Item::link_blank(
|
||||||
|
Lc::t("showcase_menu_docs", &LOC),
|
||||||
|
"https://docs.rs/pagetop",
|
||||||
|
))
|
||||||
|
.with_item(nav::Item::link_disabled(
|
||||||
|
Lc::t("showcase_menu_disabled", &LOC),
|
||||||
|
"#",
|
||||||
|
));
|
||||||
|
|
||||||
|
// Menú de la cuenta al final de la barra y, con Bootsier, el selector de modo de color
|
||||||
|
// (claro, oscuro o automático).
|
||||||
|
let mut user_menu = Nav::new()
|
||||||
|
.with_prop(FlexItem::push_end())
|
||||||
|
.with_item(nav::Item::link(Lc::t("showcase_menu_sign_up", &LOC), "#"))
|
||||||
|
.with_item(nav::Item::link(Lc::t("showcase_menu_login", &LOC), "#"));
|
||||||
|
if is_bootsier() {
|
||||||
|
user_menu = user_menu.with_item(bs::theme_toggle());
|
||||||
|
}
|
||||||
|
|
||||||
|
let header = Navbar::brand_left(brand)
|
||||||
|
.with_expand(Breakpoint::Lg)
|
||||||
|
.with_item(navbar::Item::nav(main_menu))
|
||||||
|
.with_item(navbar::Item::nav(user_menu));
|
||||||
|
|
||||||
|
InRegion::Global(&CoreRegions::Header).add(header);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configure_router(&self, routes: Routes) -> Routes {
|
||||||
|
routes.public_route("/", web::get(theme_showcase))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn theme_showcase(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
|
let mut page = Page::new(request)
|
||||||
|
.with_title(Lc::t("showcase_title", &LOC))
|
||||||
|
.with_child(fields_block())
|
||||||
|
.with_child(checks_block())
|
||||||
|
.with_child(tables_block())
|
||||||
|
.with_child(buttons_block())
|
||||||
|
.with_child(misc_block());
|
||||||
|
|
||||||
|
// Un mensaje de cada nivel, que muestra el listado del bloque de tablas entre su botón y la
|
||||||
|
// tabla, como haría con el aviso de un borrado.
|
||||||
|
page.push_message(MessageLevel::Info, Lc::t("showcase_msg_info", &LOC));
|
||||||
|
page.push_message(MessageLevel::Warning, Lc::t("showcase_msg_warning", &LOC));
|
||||||
|
page.push_message(MessageLevel::Error, Lc::t("showcase_msg_error", &LOC));
|
||||||
|
|
||||||
|
page.render().await
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bootsier aporta piezas propias que otros temas no tienen: el selector de modo de color, las
|
||||||
|
// etiquetas flotantes y los botones de los colores claro y oscuro de su paleta.
|
||||||
|
fn is_bootsier() -> bool {
|
||||||
|
global::SETTINGS.app.theme.eq_ignore_ascii_case("bootsier")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rejilla de una columna en pantallas pequeñas, dos a partir de `Md` y tres a partir de `Lg`. Sin
|
||||||
|
// hueco entre filas: ya separa los campos su propio margen.
|
||||||
|
fn columns() -> Grid {
|
||||||
|
let tracks = |n| grid::Tracks::repeat(n, grid::AxisTrack::Fraction(1.0));
|
||||||
|
Grid::new()
|
||||||
|
.with_columns(tracks(1))
|
||||||
|
.with_columns_at(Breakpoint::Md, tracks(2))
|
||||||
|
.with_columns_at(Breakpoint::Lg, tracks(3))
|
||||||
|
.with_gap(align::Gap::Distinct {
|
||||||
|
row: UnitValue::None,
|
||||||
|
column: UnitValue::RelRem(1.5),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Campos de texto y listas en sus distintos estados.
|
||||||
|
fn fields_block() -> Block {
|
||||||
|
let mut grid = columns()
|
||||||
|
.with_child(
|
||||||
|
form::input::Field::text()
|
||||||
|
.with_name("name")
|
||||||
|
.with_label(Lc::t("showcase_name", &LOC))
|
||||||
|
.with_value("Ana García")
|
||||||
|
.with_help_text(Lc::t("showcase_name_help", &LOC))
|
||||||
|
.with_required(true),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::input::Field::email()
|
||||||
|
.with_name("email")
|
||||||
|
.with_label(Lc::t("showcase_email", &LOC))
|
||||||
|
.with_placeholder(Lc::t("showcase_email_placeholder", &LOC)),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::input::Field::text()
|
||||||
|
.with_name("focus")
|
||||||
|
.with_label(Lc::t("showcase_focus", &LOC))
|
||||||
|
.with_value("1200")
|
||||||
|
.with_autofocus(true),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::select::Field::new()
|
||||||
|
.with_name("font")
|
||||||
|
.with_label(Lc::t("showcase_font", &LOC))
|
||||||
|
.with_item(form::select::Item::new(
|
||||||
|
"playfair",
|
||||||
|
Lc::n("Playfair Display"),
|
||||||
|
))
|
||||||
|
.with_item(form::select::Item::new("source", Lc::n("Source Sans 3")))
|
||||||
|
.with_item(form::select::Item::new("roboto", Lc::n("Roboto"))),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::input::Field::text()
|
||||||
|
.with_name("disabled")
|
||||||
|
.with_label(Lc::t("showcase_disabled", &LOC))
|
||||||
|
.with_value("Ana García")
|
||||||
|
.with_disabled(true),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::input::Field::email()
|
||||||
|
.with_name("readonly")
|
||||||
|
.with_label(Lc::t("showcase_readonly", &LOC))
|
||||||
|
.with_value("ana@example.com")
|
||||||
|
.with_readonly(true),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::select::Field::new()
|
||||||
|
.with_name("disabled_font")
|
||||||
|
.with_label(Lc::t("showcase_disabled_select", &LOC))
|
||||||
|
.with_item(form::select::Item::new(
|
||||||
|
"playfair",
|
||||||
|
Lc::n("Playfair Display"),
|
||||||
|
))
|
||||||
|
.with_disabled(true),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::Textarea::new()
|
||||||
|
.with_name("comment")
|
||||||
|
.with_label(Lc::t("showcase_comment", &LOC))
|
||||||
|
.with_placeholder(Lc::t("showcase_comment_placeholder", &LOC)),
|
||||||
|
);
|
||||||
|
if is_bootsier() {
|
||||||
|
grid = grid.with_child(
|
||||||
|
form::input::Field::text()
|
||||||
|
.with_name("floating")
|
||||||
|
.with_label(Lc::t("showcase_floating", &LOC))
|
||||||
|
.with_value("Ana García")
|
||||||
|
.with_floating_label(true),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// El último campo no tiene margen inferior y, si es el más alto de su fila, la rejilla acaba en
|
||||||
|
// su borde. El margen de la rejilla repone ese espacio, como el que dejan debajo los demás
|
||||||
|
// bloques.
|
||||||
|
Block::new()
|
||||||
|
.with_title(Lc::t("showcase_block_fields", &LOC))
|
||||||
|
.with_child(grid.with_prop(Margin::new().with_bottom(UnitValue::RelRem(1.0))))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Casillas, interruptores y botones de opción, marcados, sin marcar y deshabilitados.
|
||||||
|
fn checks_block() -> Block {
|
||||||
|
Block::new()
|
||||||
|
.with_title(Lc::t("showcase_block_checks", &LOC))
|
||||||
|
.with_child(
|
||||||
|
columns()
|
||||||
|
.with_child(
|
||||||
|
form::Fieldset::new()
|
||||||
|
.with_legend(Lc::t("showcase_checks", &LOC))
|
||||||
|
.with_child(
|
||||||
|
form::Checkbox::new()
|
||||||
|
.with_name("check_off")
|
||||||
|
.with_label(Lc::t("showcase_check_off", &LOC)),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::Checkbox::new()
|
||||||
|
.with_name("check_on")
|
||||||
|
.with_label(Lc::t("showcase_check_on", &LOC))
|
||||||
|
.with_checked(true),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::Checkbox::new()
|
||||||
|
.with_name("check_disabled")
|
||||||
|
.with_label(Lc::t("showcase_check_disabled", &LOC))
|
||||||
|
.with_disabled(true),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::Fieldset::new()
|
||||||
|
.with_legend(Lc::t("showcase_switches", &LOC))
|
||||||
|
.with_child(
|
||||||
|
form::Checkbox::switch()
|
||||||
|
.with_name("switch_off")
|
||||||
|
.with_label(Lc::t("showcase_switch_off", &LOC)),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::Checkbox::switch()
|
||||||
|
.with_name("switch_on")
|
||||||
|
.with_label(Lc::t("showcase_switch_on", &LOC))
|
||||||
|
.with_checked(true),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::Checkbox::switch()
|
||||||
|
.with_name("switch_disabled")
|
||||||
|
.with_label(Lc::t("showcase_switch_disabled", &LOC))
|
||||||
|
.with_disabled(true),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.with_child(
|
||||||
|
form::Fieldset::new()
|
||||||
|
.with_legend(Lc::t("showcase_options", &LOC))
|
||||||
|
.with_child(
|
||||||
|
form::radio::Field::new()
|
||||||
|
.with_name("size")
|
||||||
|
.with_item(form::radio::Item::new(
|
||||||
|
"small",
|
||||||
|
Lc::t("showcase_option_small", &LOC),
|
||||||
|
))
|
||||||
|
.with_item(
|
||||||
|
form::radio::Item::new(
|
||||||
|
"medium",
|
||||||
|
Lc::t("showcase_option_medium", &LOC),
|
||||||
|
)
|
||||||
|
.with_checked(true),
|
||||||
|
)
|
||||||
|
.with_item(
|
||||||
|
form::radio::Item::new(
|
||||||
|
"large",
|
||||||
|
Lc::t("showcase_option_large", &LOC),
|
||||||
|
)
|
||||||
|
.with_disabled(true),
|
||||||
|
)
|
||||||
|
.with_help_text(Lc::t("showcase_options_help", &LOC)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filtro de listado, listado completo (botón de acción, tabla con cabeceras ordenables y
|
||||||
|
// paginador) y tabla vacía.
|
||||||
|
fn tables_block() -> Block {
|
||||||
|
// Columna ordenable; `dir` marca la que determina el orden vigente.
|
||||||
|
let sortable = |key: &'static str, sort: &str, dir: Option<SortDir>| {
|
||||||
|
table::Column::new(Lc::t(key, &LOC))
|
||||||
|
.with_sort(table::SortLink::new(util::join!("/?sort=", sort)).with_dir(dir))
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut users = Table::new()
|
||||||
|
.with_column(sortable("showcase_col_user", "user", Some(SortDir::Asc)))
|
||||||
|
.with_column(sortable("showcase_col_email", "email", None))
|
||||||
|
.with_column(Lc::t("showcase_col_status", &LOC))
|
||||||
|
.with_column(sortable("showcase_col_last_access", "access", None))
|
||||||
|
.with_column(Lc::t("showcase_col_actions", &LOC));
|
||||||
|
for (user, email, status, access) in [
|
||||||
|
("ana", "ana@example.com", "active", "2026-11-14 09:12"),
|
||||||
|
("bruno", "bruno@example.com", "pending", "-"),
|
||||||
|
("carmen", "carmen@example.com", "active", "2026-11-13 18:40"),
|
||||||
|
("david", "david@example.com", "blocked", "2026-10-02 11:05"),
|
||||||
|
] {
|
||||||
|
let badge = match status {
|
||||||
|
"active" => Badge::success(Lc::t("showcase_status_active", &LOC)),
|
||||||
|
"pending" => Badge::warning(Lc::t("showcase_status_pending", &LOC)),
|
||||||
|
_ => Badge::severe(Lc::t("showcase_status_blocked", &LOC)),
|
||||||
|
};
|
||||||
|
users.alter_row(
|
||||||
|
table::Row::new()
|
||||||
|
.with_cell(user)
|
||||||
|
.with_cell(email)
|
||||||
|
.with_cell(table::Cell::new(badge))
|
||||||
|
.with_cell(access)
|
||||||
|
.with_cell(table::Cell::new(
|
||||||
|
Button::anchor(Lc::t("showcase_edit", &LOC), "#")
|
||||||
|
.with_style(button::Style::Link),
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let list = ListView::new()
|
||||||
|
.with_id("showcase-users")
|
||||||
|
.with_action(
|
||||||
|
Button::anchor(Lc::t("showcase_new_user", &LOC), "#")
|
||||||
|
.with_style(button::Style::Solid(Intent::Primary)),
|
||||||
|
)
|
||||||
|
.with_table(users)
|
||||||
|
.with_pager(
|
||||||
|
Pager::new()
|
||||||
|
.with_base_path("/")
|
||||||
|
.with_current_page(1)
|
||||||
|
.with_items_per_page(4)
|
||||||
|
.with_total_items(14),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Sin filas, la tabla muestra su mensaje predeterminado.
|
||||||
|
let empty = Table::new()
|
||||||
|
.with_column(Lc::t("showcase_col_user", &LOC))
|
||||||
|
.with_column(Lc::t("showcase_col_email", &LOC))
|
||||||
|
.with_column(Lc::t("showcase_col_status", &LOC));
|
||||||
|
|
||||||
|
Block::new()
|
||||||
|
.with_title(Lc::t("showcase_block_tables", &LOC))
|
||||||
|
.with_child(Html::with(|cx| {
|
||||||
|
html! {
|
||||||
|
p { (Lc::t("showcase_filter_hint", &LOC).using(cx)) }
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
// El filtro va fuera del listado: si se reemplazara con él, el campo de búsqueda perdería
|
||||||
|
// el foco al actualizar sólo el listado.
|
||||||
|
.with_child(
|
||||||
|
ListFilter::new()
|
||||||
|
.with_filter_action("/")
|
||||||
|
.with_field(
|
||||||
|
form::input::Field::search()
|
||||||
|
.with_name("q")
|
||||||
|
.with_label(Lc::t("showcase_search", &LOC))
|
||||||
|
.with_placeholder(Lc::t("showcase_search_placeholder", &LOC)),
|
||||||
|
)
|
||||||
|
.with_field(
|
||||||
|
form::select::Field::new()
|
||||||
|
.with_name("status")
|
||||||
|
.with_label(Lc::t("showcase_status", &LOC))
|
||||||
|
.with_item(form::select::Item::new(
|
||||||
|
"",
|
||||||
|
Lc::t("showcase_status_any", &LOC),
|
||||||
|
))
|
||||||
|
.with_item(form::select::Item::new(
|
||||||
|
"active",
|
||||||
|
Lc::t("showcase_status_active", &LOC),
|
||||||
|
))
|
||||||
|
.with_item(form::select::Item::new(
|
||||||
|
"blocked",
|
||||||
|
Lc::t("showcase_status_blocked", &LOC),
|
||||||
|
)),
|
||||||
|
)
|
||||||
|
.with_field(
|
||||||
|
form::Checkbox::new()
|
||||||
|
.with_name("admins")
|
||||||
|
.with_label(Lc::t("showcase_only_admins", &LOC)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.with_child(list)
|
||||||
|
.with_child(Html::with(|cx| {
|
||||||
|
html! {
|
||||||
|
p { (Lc::t("showcase_empty_table", &LOC).using(cx)) }
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.with_child(empty)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Botones macizos y de contorno de todas las intenciones.
|
||||||
|
fn buttons_block() -> Block {
|
||||||
|
Block::new()
|
||||||
|
.with_title(Lc::t("showcase_block_buttons", &LOC))
|
||||||
|
.with_child(
|
||||||
|
Flex::new()
|
||||||
|
.with_direction(flex::Direction::Column)
|
||||||
|
.with_gap(align::Gap::Both(UnitValue::RelRem(0.5)))
|
||||||
|
.with_prop(Margin::new().with_bottom(UnitValue::RelRem(1.5)))
|
||||||
|
.with_child(buttons(false))
|
||||||
|
.with_child(buttons(true)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Una fila con un botón por intención. Con Bootsier, también los colores claro y oscuro de su
|
||||||
|
// paleta, que no corresponden a ninguna intención. El estilo enlace sólo va en la fila maciza.
|
||||||
|
fn buttons(outline: bool) -> Flex {
|
||||||
|
let style = |intent| match outline {
|
||||||
|
false => button::Style::Solid(intent),
|
||||||
|
true => button::Style::Outline(intent),
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut row = Flex::new()
|
||||||
|
.with_wrap(flex::Behavior::Wrap)
|
||||||
|
.with_gap(align::Gap::Both(UnitValue::RelRem(0.5)));
|
||||||
|
for (label, intent) in [
|
||||||
|
("Primary", Intent::Primary),
|
||||||
|
("Neutral", Intent::Neutral),
|
||||||
|
("Info", Intent::Info),
|
||||||
|
("Success", Intent::Success),
|
||||||
|
("Warning", Intent::Warning),
|
||||||
|
("Severe", Intent::Severe),
|
||||||
|
] {
|
||||||
|
row = row.with_child(Button::plain(Lc::n(label)).with_style(style(intent)));
|
||||||
|
}
|
||||||
|
if is_bootsier() {
|
||||||
|
for (label, color) in [
|
||||||
|
("Light", BootsierColors::Light),
|
||||||
|
("Dark", BootsierColors::Dark),
|
||||||
|
] {
|
||||||
|
row = row.with_child(
|
||||||
|
Button::plain(Lc::n(label))
|
||||||
|
.with_style(style(Intent::Neutral))
|
||||||
|
.with_color(color),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !outline {
|
||||||
|
row = row.with_child(Button::plain(Lc::n("Link")).with_style(button::Style::Link));
|
||||||
|
}
|
||||||
|
row
|
||||||
|
}
|
||||||
|
|
||||||
|
// Enlaces, insignias, paginación y mensajes, que también toman los colores del tema.
|
||||||
|
fn misc_block() -> Block {
|
||||||
|
let mut badges = Flex::new()
|
||||||
|
.with_wrap(flex::Behavior::Wrap)
|
||||||
|
.with_gap(align::Gap::Both(UnitValue::RelRem(0.5)));
|
||||||
|
for badge in [
|
||||||
|
Badge::primary(Lc::n("Primary")),
|
||||||
|
Badge::neutral(Lc::n("Neutral")),
|
||||||
|
Badge::info(Lc::n("Info")),
|
||||||
|
Badge::success(Lc::n("Success")),
|
||||||
|
Badge::warning(Lc::n("Warning")),
|
||||||
|
Badge::severe(Lc::n("Severe")),
|
||||||
|
] {
|
||||||
|
badges = badges.with_child(badge);
|
||||||
|
}
|
||||||
|
|
||||||
|
Block::new()
|
||||||
|
.with_title(Lc::t("showcase_block_misc", &LOC))
|
||||||
|
.with_child(Html::with(|cx| {
|
||||||
|
html! {
|
||||||
|
p { (Lc::t("showcase_link_text", &LOC).using(cx)) }
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.with_child(badges)
|
||||||
|
// Con 50 páginas y la actual en medio aparecen todas sus piezas: anterior y siguiente, las
|
||||||
|
// elipsis de los tramos ocultos a cada lado, el resumen y el formulario para saltar a una
|
||||||
|
// página.
|
||||||
|
.with_child(
|
||||||
|
Pager::new()
|
||||||
|
.with_base_path("/")
|
||||||
|
.with_current_page(24)
|
||||||
|
.with_items_per_page(10)
|
||||||
|
.with_total_items(500),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::main]
|
||||||
|
async fn main() -> std::io::Result<()> {
|
||||||
|
Application::prepare(&ThemeShowcase).await.run().await
|
||||||
|
}
|
||||||
|
|
@ -95,9 +95,10 @@ async fn about(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
|
|
||||||
## Panel de administración
|
## Panel de administración
|
||||||
|
|
||||||
En la plantilla `Admin`, Bootsier sigue la composición del núcleo: tras la cabecera pinta la
|
En la plantilla `Admin`, Bootsier sigue la composición del núcleo: en lugar del contenido pinta el
|
||||||
navegación del panel (`AdminMenu`) y, en lugar del contenido, el marco de la página (`AdminFrame`:
|
marco de la página (`AdminFrame`: migas, título, botones y pestañas). La navegación del panel
|
||||||
migas, título, botones y pestañas). Los dos se construyen con componentes del núcleo
|
(`Nav::admin()`) la coloca la aplicación, en una barra aparte o en su barra principal, donde se
|
||||||
|
pliega con su botón en pantallas pequeñas. Todo se construye con componentes del núcleo
|
||||||
(`Navbar`/`Nav`/`Dropdown`, `Breadcrumb`), que Bootsier ya pinta con su aspecto.
|
(`Navbar`/`Nav`/`Dropdown`, `Breadcrumb`), que Bootsier ya pinta con su aspecto.
|
||||||
|
|
||||||
## Selector de modo de color
|
## Selector de modo de color
|
||||||
|
|
@ -117,6 +118,87 @@ let navbar = bs::Navbar::simple().with_item(bs::navbar::Item::nav(
|
||||||
));
|
));
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Temas hijo
|
||||||
|
|
||||||
|
Un tema hijo hereda todo de Bootsier (plantillas, componentes, estilos, *scripts* y fuentes) y
|
||||||
|
cambia su aspecto con una hoja de estilos propia que se carga detrás de la de Bootsier. Esa hoja
|
||||||
|
sólo contiene lo que cambia: Bootstrap define casi todo su aspecto con variables CSS (`--bs-*`), y
|
||||||
|
basta con redefinirlas:
|
||||||
|
|
||||||
|
```css
|
||||||
|
:root {
|
||||||
|
--bs-border-radius: .25rem;
|
||||||
|
--bs-link-color: #6f42c1;
|
||||||
|
--bs-link-color-rgb: 111, 66, 193;
|
||||||
|
--bs-link-hover-color: #59359a;
|
||||||
|
--bs-link-hover-color-rgb: 89, 53, 154;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Las variantes de color de los componentes (`.btn-primary`, `.alert-primary`...) llevan sus propios
|
||||||
|
valores, así que se cambian redefiniendo las variables de cada componente:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.btn-primary {
|
||||||
|
--bs-btn-bg: #6f42c1;
|
||||||
|
--bs-btn-border-color: #6f42c1;
|
||||||
|
--bs-btn-hover-bg: #59359a;
|
||||||
|
--bs-btn-hover-border-color: #59359a;
|
||||||
|
--bs-btn-active-bg: #4b2d83;
|
||||||
|
--bs-btn-active-border-color: #4b2d83;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Lo redefinido en `:root` vale también en el modo oscuro, porque gana a los valores oscuros de
|
||||||
|
Bootstrap; lo que deba ser distinto en él va dentro de `[data-bs-theme=dark] { ... }`.
|
||||||
|
|
||||||
|
El `build.rs` del tema hijo incluye la hoja en el binario con `pagetop-build`:
|
||||||
|
|
||||||
|
```rust,ignore
|
||||||
|
use pagetop_build::StaticFilesBundle;
|
||||||
|
|
||||||
|
fn main() -> std::io::Result<()> {
|
||||||
|
StaticFilesBundle::from_dir("./assets/css", None)
|
||||||
|
.with_name("my_theme_css")
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
El tema la sirve con `serve_static_files!(files, [my_theme_css] => "/my-theme/css")` en
|
||||||
|
`Extension::configure_static_files()`, declara a Bootsier como padre y añade su hoja tras la de
|
||||||
|
Bootsier:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_bootsier::Bootsier;
|
||||||
|
|
||||||
|
pub struct MyTheme;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for MyTheme {
|
||||||
|
fn theme(&self) -> Option<ThemeRef> {
|
||||||
|
Some(&Self)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
vec![&Bootsier]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Theme for MyTheme {
|
||||||
|
fn parent(&self) -> Option<ThemeRef> {
|
||||||
|
Some(&Bootsier)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn before_render_page_body(&self, page: &mut Page) {
|
||||||
|
Bootsier.before_render_page_body(page);
|
||||||
|
// Justo detrás de la hoja de Bootsier (peso -99).
|
||||||
|
page.alter_assets(StyleSheet::from("/my-theme/css/my-theme.css").with_weight(-98));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Créditos
|
## Créditos
|
||||||
|
|
||||||
Este *crate* integra la biblioteca de estilos [Bootstrap 5.3.8](https://getbootstrap.com/) para
|
Este *crate* integra la biblioteca de estilos [Bootstrap 5.3.8](https://getbootstrap.com/) para
|
||||||
|
|
|
||||||
|
|
@ -19,6 +19,46 @@
|
||||||
font-display: swap;
|
font-display: swap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Background of the form fields ($input-bg in _bootsier-variables.scss), of disabled fields
|
||||||
|
// ($input-disabled-bg), of unchecked checks ($form-check-input-bg), of fieldsets, of dropdown menus
|
||||||
|
// ($dropdown-bg) and of breadcrumbs ($breadcrumb-bg), color of the group titles of dropdown menus
|
||||||
|
// ($dropdown-header-color, a lighter gray than their items in light mode, nearly white in dark
|
||||||
|
// mode), color of the legends of fieldsets (darker than Bootstrap's secondary color in light mode,
|
||||||
|
// since their thin weight makes them lighter), and shadow of focused fields
|
||||||
|
// ($input-focus-box-shadow), for each color mode. On a dark background the primary color barely
|
||||||
|
// shows, so the dark mode uses a lighter tint of it with more opacity.
|
||||||
|
:root,
|
||||||
|
[data-bs-theme="light"] {
|
||||||
|
--bootsier-input-bg: #f1f3f4;
|
||||||
|
--bootsier-input-disabled-bg: #f7f8f9;
|
||||||
|
--bootsier-check-bg: #e2e5e8;
|
||||||
|
--bootsier-fieldset-bg: #fefefe;
|
||||||
|
--bootsier-dropdown-bg: #fdfdfd;
|
||||||
|
--bootsier-breadcrumb-bg: #f8f9fa;
|
||||||
|
--bootsier-dropdown-header-color: rgba(var(--bs-body-color-rgb), .65);
|
||||||
|
--bootsier-legend-color: rgba(var(--bs-body-color-rgb), .9);
|
||||||
|
--bootsier-focus-shadow: 0 0 2px #{rgba($primary, .15)}, 0 0 6px #{rgba($primary, .35)};
|
||||||
|
}
|
||||||
|
|
||||||
|
@include color-mode(dark, true) {
|
||||||
|
--bootsier-input-bg: #{$gray-800};
|
||||||
|
--bootsier-input-disabled-bg: #31363b;
|
||||||
|
--bootsier-check-bg: #{$gray-700};
|
||||||
|
--bootsier-fieldset-bg: #292e33;
|
||||||
|
--bootsier-dropdown-bg: #3e444a;
|
||||||
|
--bootsier-breadcrumb-bg: #292e33;
|
||||||
|
--bootsier-dropdown-header-color: rgba(var(--bs-emphasis-color-rgb), .85);
|
||||||
|
--bootsier-legend-color: var(--bs-secondary-color);
|
||||||
|
--bootsier-focus-shadow:
|
||||||
|
0 0 2px #{rgba(tint-color($primary, 60%), .4)}, 0 0 6px #{rgba(tint-color($primary, 60%), .7)};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disabled form fields also fade as disabled buttons do.
|
||||||
|
.form-control:disabled,
|
||||||
|
.form-select:disabled {
|
||||||
|
opacity: $btn-disabled-opacity;
|
||||||
|
}
|
||||||
|
|
||||||
// Font-relative top offset to keep the skip-link hidden at any font size.
|
// Font-relative top offset to keep the skip-link hidden at any font size.
|
||||||
.skip-link {
|
.skip-link {
|
||||||
top: -3em;
|
top: -3em;
|
||||||
|
|
@ -48,12 +88,20 @@
|
||||||
margin: 1rem 0;
|
margin: 1rem 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fieldset with border and floating legend.
|
// Space below each block (Block), from Bootstrap's spacing unit, so consecutive blocks (and what
|
||||||
|
// follows them) do not sit right together. Twice $spacer, as the 2rem of the Basic theme.
|
||||||
|
.block {
|
||||||
|
margin-bottom: $spacer * 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fieldset outlined only by a soft shadow (Bootstrap's reboot already removes the border), with a
|
||||||
|
// floating legend.
|
||||||
fieldset {
|
fieldset {
|
||||||
position: relative;
|
position: relative;
|
||||||
background-color: var(--bs-body-bg);
|
background-color: var(--bootsier-fieldset-bg);
|
||||||
border: var(--bs-border-width) solid var(--bs-border-color);
|
|
||||||
border-radius: var(--bs-border-radius);
|
border-radius: var(--bs-border-radius);
|
||||||
|
// Offset down with a negative spread: strongest below, softer at the sides, faintest on top.
|
||||||
|
box-shadow: 0 1px 3px rgba(0, 0, 0, .10), 0 4px 8px -2px rgba(0, 0, 0, .22);
|
||||||
padding: 2rem 1rem 1rem;
|
padding: 2rem 1rem 1rem;
|
||||||
margin: 2rem 0 1rem;
|
margin: 2rem 0 1rem;
|
||||||
}
|
}
|
||||||
|
|
@ -63,13 +111,14 @@ fieldset > legend {
|
||||||
top: 0;
|
top: 0;
|
||||||
left: 1rem;
|
left: 1rem;
|
||||||
transform: translateY(-50%);
|
transform: translateY(-50%);
|
||||||
color: var(--bs-secondary-color);
|
color: var(--bootsier-legend-color);
|
||||||
background-color: var(--bs-body-bg);
|
background-color: var(--bs-body-bg);
|
||||||
border: var(--bs-border-width) solid var(--bs-border-color);
|
// Soft outline with the gray of the form fields, in both color modes.
|
||||||
|
border: var(--bs-border-width) solid var(--bootsier-input-bg);
|
||||||
border-radius: var(--bs-border-radius);
|
border-radius: var(--bs-border-radius);
|
||||||
padding: 0.125rem 0.75rem;
|
padding: 0.125rem 0.75rem;
|
||||||
font-size: ($font-size-sm + $font-size-base) / 2;
|
font-size: ($font-size-sm + $font-size-base) / 2;
|
||||||
font-weight: var(--bs-font-weight-normal);
|
font-weight: $font-weight-light;
|
||||||
line-height: 1.25;
|
line-height: 1.25;
|
||||||
width: fit-content;
|
width: fit-content;
|
||||||
max-width: 75%;
|
max-width: 75%;
|
||||||
|
|
@ -82,6 +131,11 @@ fieldset > legend {
|
||||||
margin-bottom: 1rem;
|
margin-bottom: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Labels start a little inside, clear of the rounded corner of their field.
|
||||||
|
.form-label {
|
||||||
|
padding-left: .25rem;
|
||||||
|
}
|
||||||
|
|
||||||
// Gap between group label and first inline check.
|
// Gap between group label and first inline check.
|
||||||
.form-label + .form-check-inline {
|
.form-label + .form-check-inline {
|
||||||
margin-left: 1rem;
|
margin-left: 1rem;
|
||||||
|
|
@ -99,11 +153,68 @@ fieldset > legend {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Images with this class show their colors inverted in dark mode, such as a dark logo that would
|
||||||
|
// otherwise blend into the background. Only for images that keep their look when inverted: a full
|
||||||
|
// color one would change its hues.
|
||||||
|
[data-bs-theme="dark"] .image-invert-dark {
|
||||||
|
filter: invert(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dropdown menus have no border (_bootsier-variables.scss), so a soft shadow sets them apart from
|
||||||
|
// the content they cover, as fieldsets are outlined. Bootstrap only adds its own with
|
||||||
|
// $enable-shadows.
|
||||||
|
.dropdown-menu {
|
||||||
|
box-shadow: 0 1px 3px rgba(0, 0, 0, .10), 0 4px 8px -2px rgba(0, 0, 0, .22);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group titles of dropdown menus in a lighter weight than their items.
|
||||||
|
.dropdown-header {
|
||||||
|
font-weight: $font-weight-light;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Navbars have no inner container, so they line up with the rest of the page. Fixed bars span the
|
||||||
|
// whole viewport, so they take back the side padding of a container off its edges.
|
||||||
|
.navbar.fixed-top,
|
||||||
|
.navbar.fixed-bottom {
|
||||||
|
padding-right: $container-padding-x * .5;
|
||||||
|
padding-left: $container-padding-x * .5;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The first link of the first menu and the last link of the last menu drop their outer padding, so
|
||||||
|
// their text lines up with the rest of the page (next to the brand, its own margin keeps them
|
||||||
|
// apart). Collapsed bars stack their links with no side padding already.
|
||||||
|
.navbar-nav:first-child > .nav-item:first-child > .nav-link {
|
||||||
|
padding-left: 0;
|
||||||
|
}
|
||||||
|
.navbar-nav:last-child > .nav-item:last-child > .nav-link {
|
||||||
|
padding-right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Disabled links of navbars, lighter in dark mode: Bootstrap's 30% of the text color barely shows
|
||||||
|
// on the dark background (links take 65%).
|
||||||
|
[data-bs-theme="dark"] .navbar {
|
||||||
|
--bs-navbar-disabled-color: rgba(var(--bs-emphasis-color-rgb), .45);
|
||||||
|
}
|
||||||
|
|
||||||
// Messages component. Classes are fixed by pagetop core (`.message`, `.message-info`,
|
// Messages component. Classes are fixed by pagetop core (`.message`, `.message-info`,
|
||||||
// `.message-warning`, `.message-error`); reusing Bootstrap's own `.alert`/`.alert-*` styles keeps
|
// `.message-warning`, `.message-error`); reusing Bootstrap's own `.alert`/`.alert-*` styles keeps
|
||||||
// the palette in sync with the active Bootstrap theme instead of duplicating it here.
|
// the palette in sync with the active Bootstrap theme instead of duplicating it here.
|
||||||
.message {
|
.message {
|
||||||
@extend .alert;
|
@extend .alert;
|
||||||
|
// Outlined by a shadow tinted with the text color of each variant instead of a border. A single
|
||||||
|
// offset shadow is always stronger below than at the sides, so three are combined (left, right
|
||||||
|
// and below) to reach the same width on those three sides, leaving the top faint.
|
||||||
|
--bootsier-message-shadow: color-mix(in srgb, var(--bs-alert-color) 35%, transparent);
|
||||||
|
border: 0;
|
||||||
|
box-shadow:
|
||||||
|
0 1px 2px color-mix(in srgb, var(--bs-alert-color) 15%, transparent),
|
||||||
|
-4px 0 6px -4px var(--bootsier-message-shadow),
|
||||||
|
4px 0 6px -4px var(--bootsier-message-shadow),
|
||||||
|
0 3px 6px -3px var(--bootsier-message-shadow);
|
||||||
|
}
|
||||||
|
// No shadow in dark mode, where it barely shows: the background of each variant is enough.
|
||||||
|
[data-bs-theme="dark"] .message {
|
||||||
|
box-shadow: none;
|
||||||
}
|
}
|
||||||
.message-info {
|
.message-info {
|
||||||
@extend .alert-info;
|
@extend .alert-info;
|
||||||
|
|
@ -133,6 +244,14 @@ fieldset > legend {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Message of a table without rows, as in the Basic theme: centered, in italics and muted (inside
|
||||||
|
// .table, to win over the color Bootstrap gives to every cell).
|
||||||
|
.table .table-empty {
|
||||||
|
text-align: center;
|
||||||
|
font-style: italic;
|
||||||
|
color: var(--bs-secondary-color);
|
||||||
|
}
|
||||||
|
|
||||||
// List filters (ListFilter): fields and button on one row, wrapping when there is no room.
|
// List filters (ListFilter): fields and button on one row, wrapping when there is no room.
|
||||||
.list-filter {
|
.list-filter {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|
@ -150,8 +269,9 @@ fieldset > legend {
|
||||||
// colors and opacity change, never sizes: the dot always takes its room, hidden, so nothing moves
|
// colors and opacity change, never sizes: the dot always takes its room, hidden, so nothing moves
|
||||||
// when it shows up. A vivid orange, set apart from the primary color of the button, darkened just
|
// when it shows up. A vivid orange, set apart from the primary color of the button, darkened just
|
||||||
// enough to keep a 3:1 contrast against the background. Every changed field gets the dot by its
|
// enough to keep a 3:1 contrast against the background. Every changed field gets the dot by its
|
||||||
// label, once per field (on the title of a group); text fields and dropdowns also show a gray
|
// label, once per field (on the title of a group); text fields, dropdowns and checks also show
|
||||||
// background. Floating labels are left out: Bootstrap draws their background with `::after`.
|
// their border in that color. Floating labels are left out: Bootstrap draws their background with
|
||||||
|
// `::after`.
|
||||||
.list-filter {
|
.list-filter {
|
||||||
--list-filter-mark: #{mix(#000, $orange, 15%)};
|
--list-filter-mark: #{mix(#000, $orange, 15%)};
|
||||||
}
|
}
|
||||||
|
|
@ -173,12 +293,11 @@ fieldset > legend {
|
||||||
.form-control,
|
.form-control,
|
||||||
.form-select,
|
.form-select,
|
||||||
.form-check-input {
|
.form-check-input {
|
||||||
background-color: var(--bs-secondary-bg);
|
border-color: var(--list-filter-mark);
|
||||||
}
|
}
|
||||||
|
|
||||||
.form-check-input:checked {
|
.form-check-input:checked {
|
||||||
background-color: var(--list-filter-mark);
|
background-color: var(--list-filter-mark);
|
||||||
border-color: var(--list-filter-mark);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -244,6 +363,24 @@ fieldset > legend {
|
||||||
margin-inline-end: 0;
|
margin-inline-end: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Joined cells, as in Bootstrap, but wrapping onto more lines when they don't fit: a long pager
|
||||||
|
// never gets wider than the screen (mobile browsers would zoom out the whole page). Each line
|
||||||
|
// overlaps the border of the one above, as cells do side by side. On small screens they also get
|
||||||
|
// smaller, so that more of them fit on a line.
|
||||||
|
.pagination {
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.pagination .page-link {
|
||||||
|
margin-bottom: calc(var(--bs-pagination-border-width) * -1);
|
||||||
|
}
|
||||||
|
@include media-breakpoint-down(sm) {
|
||||||
|
.pagination {
|
||||||
|
--bs-pagination-padding-x: .5rem;
|
||||||
|
--bs-pagination-padding-y: .25rem;
|
||||||
|
--bs-pagination-font-size: #{$font-size-base * .875};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// By default, .page-link-icon shows the text of pager_previous_label/pager_next_label
|
// By default, .page-link-icon shows the text of pager_previous_label/pager_next_label
|
||||||
// ("Previous"/"Next"). The full accessible text lives separately, in the link's aria-label, so
|
// ("Previous"/"Next"). The full accessible text lives separately, in the link's aria-label, so
|
||||||
// replacing the visible text here with a symbol does not affect accessibility. To use "‹"/"›"
|
// replacing the visible text here with a symbol does not affect accessibility. To use "‹"/"›"
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,4 @@
|
||||||
// Bootstrap utility extensions. Imported just before utilities/api so variable changes take effect.
|
// Bootstrap utility extensions. Imported just before utilities/api so the changes take effect.
|
||||||
|
|
||||||
// CSS Grid (Bootstrap 5): disable legacy grid classes and enable native CSS Grid.
|
|
||||||
$enable-grid-classes: false;
|
|
||||||
$enable-cssgrid: true;
|
|
||||||
|
|
||||||
// Extend the $utilities map with additional classes.
|
// Extend the $utilities map with additional classes.
|
||||||
$utilities: map-merge(
|
$utilities: map-merge(
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,74 @@ $font-family-sans-serif: "Source Sans 3", system-ui, -apple-system, "Segoe UI",
|
||||||
"Helvetica Neue", "Noto Sans", "Liberation Sans", Arial, sans-serif, "Apple Color Emoji",
|
"Helvetica Neue", "Noto Sans", "Liberation Sans", Arial, sans-serif, "Apple Color Emoji",
|
||||||
"Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
"Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
||||||
|
|
||||||
|
// Theme colors from the PageTop logo and the Intro component: warm neutrals and state colors of the
|
||||||
|
// same palette, with a petrol blue as the primary color. The text Bootstrap picks for their
|
||||||
|
// buttons (white or black) keeps a contrast of at least 4.5:1 with all of them.
|
||||||
|
$primary: #0e6973; // Petrol blue, a cool counterpoint to the warm palette.
|
||||||
|
$secondary: #6e604a; // Warm gray of the logo, darkened.
|
||||||
|
$success: #4d7c0f; // Lime of the logo, as olive green.
|
||||||
|
$danger: #b91c1c; // Red of the Intro button.
|
||||||
|
$warning: #ffb84b; // Amber of the logo.
|
||||||
|
$info: #4cb5c4; // Teal of the screens in the Intro illustration.
|
||||||
|
$light: #fff1db; // Cream of the Intro blocks.
|
||||||
|
$dark: #1a202c; // Text color of Intro.
|
||||||
|
|
||||||
|
// Filled form fields: text fields, dropdowns and checks take a gray background, one for each color
|
||||||
|
// mode (--bootsier-input-bg, declared in _bootsier-custom.scss), and the same color as their
|
||||||
|
// border, which only shows when it changes color (validation). Checked checks already take the
|
||||||
|
// same color for both.
|
||||||
|
$input-bg: var(--bootsier-input-bg);
|
||||||
|
$input-border-color: $input-bg;
|
||||||
|
// Unchecked checks, radios and switches take a somewhat darker gray (--bootsier-check-bg), since
|
||||||
|
// they are small and would barely stand out with the background of text fields.
|
||||||
|
$form-check-input-bg: var(--bootsier-check-bg);
|
||||||
|
$form-check-input-border: var(--bs-border-width) solid $form-check-input-bg;
|
||||||
|
// Disabled fields take a lighter background (--bootsier-input-disabled-bg), with the border in the
|
||||||
|
// same color, and also fade (see _bootsier-custom.scss).
|
||||||
|
$input-disabled-bg: var(--bootsier-input-disabled-bg);
|
||||||
|
$input-disabled-border-color: $input-disabled-bg;
|
||||||
|
// Focused text fields and dropdowns keep their border hidden and stand out with a shadow in the
|
||||||
|
// primary color, equally wide on all four sides, one for each color mode (--bootsier-focus-shadow,
|
||||||
|
// declared in _bootsier-custom.scss). Checks keep Bootstrap's focus ring, with no border.
|
||||||
|
$input-focus-border-color: $input-bg;
|
||||||
|
$input-focus-box-shadow: var(--bootsier-focus-shadow);
|
||||||
|
$form-select-focus-box-shadow: $input-focus-box-shadow;
|
||||||
|
$form-check-input-focus-border: $form-check-input-bg;
|
||||||
|
// Bootstrap draws the knob of focused switches with $input-focus-border-color inside an SVG, where
|
||||||
|
// CSS variables do not work: keep its default color.
|
||||||
|
$form-switch-focus-color: tint-color($primary, 50%);
|
||||||
|
|
||||||
|
// Labels closer to their field (Bootstrap's default is .5rem), and two pixels smaller than the
|
||||||
|
// body text (16px with the 18px of $font-size-base; Bootstrap's default inherits it).
|
||||||
|
$form-label-margin-bottom: .125rem;
|
||||||
|
$form-label-font-size: $font-size-base - .125rem;
|
||||||
|
|
||||||
|
// Lighter help text than Bootstrap's (.75 opacity), still above a 4.5:1 contrast in both color
|
||||||
|
// modes (4.9:1 on white), and slightly smaller (Bootstrap's default is .875em).
|
||||||
|
$form-text-color: rgba(var(--bs-body-color-rgb), .65);
|
||||||
|
$form-text-font-size: .8125em;
|
||||||
|
|
||||||
// Table cells centered vertically, as in the Basic theme: with Bootstrap's default (top), a cell
|
// Table cells centered vertically, as in the Basic theme: with Bootstrap's default (top), a cell
|
||||||
// holding a button is taller and the text of the other cells sticks to the top of the row. Header
|
// holding a button is taller and the text of the other cells sticks to the top of the row. Header
|
||||||
// cells keep Bootstrap's bottom alignment.
|
// cells keep Bootstrap's bottom alignment.
|
||||||
$table-cell-vertical-align: middle;
|
$table-cell-vertical-align: middle;
|
||||||
|
|
||||||
|
// Dropdown menus: a gray background between those of fieldsets and text fields, one for each color
|
||||||
|
// mode (--bootsier-dropdown-bg, declared in _bootsier-custom.scss), with no outer border nor
|
||||||
|
// rounded corners; dividers keep the border color. The hovered item takes the gray of text fields,
|
||||||
|
// since Bootstrap's (--bs-tertiary-bg) would match the menu background.
|
||||||
|
$dropdown-bg: var(--bootsier-dropdown-bg);
|
||||||
|
$dropdown-border-width: 0;
|
||||||
|
$dropdown-border-radius: 0;
|
||||||
|
$dropdown-inner-border-radius: 0;
|
||||||
|
$dropdown-link-hover-bg: var(--bootsier-input-bg);
|
||||||
|
// Group titles of dropdown menus, lighter in light mode (--bootsier-dropdown-header-color).
|
||||||
|
$dropdown-header-color: var(--bootsier-dropdown-header-color);
|
||||||
|
|
||||||
|
// Breadcrumbs: a light gray background, one for each color mode (--bootsier-breadcrumb-bg, declared
|
||||||
|
// in _bootsier-custom.scss), padding that keeps the text off its edges, and 16px text (1rem),
|
||||||
|
// smaller than the 18px of $font-size-base.
|
||||||
|
$breadcrumb-bg: var(--bootsier-breadcrumb-bg);
|
||||||
|
$breadcrumb-padding-y: .5rem;
|
||||||
|
$breadcrumb-padding-x: .75rem;
|
||||||
|
$breadcrumb-font-size: 1rem;
|
||||||
|
|
|
||||||
|
|
@ -17,12 +17,12 @@
|
||||||
@import "bootstrap-5.3.8/scss/utilities";
|
@import "bootstrap-5.3.8/scss/utilities";
|
||||||
|
|
||||||
// Bootstrap Layout & components
|
// Bootstrap Layout & components
|
||||||
|
// No "grid": page layout comes from PageTop's own Flex and Grid components.
|
||||||
@import "bootstrap-5.3.8/scss/root";
|
@import "bootstrap-5.3.8/scss/root";
|
||||||
@import "bootstrap-5.3.8/scss/reboot";
|
@import "bootstrap-5.3.8/scss/reboot";
|
||||||
@import "bootstrap-5.3.8/scss/type";
|
@import "bootstrap-5.3.8/scss/type";
|
||||||
@import "bootstrap-5.3.8/scss/images";
|
@import "bootstrap-5.3.8/scss/images";
|
||||||
@import "bootstrap-5.3.8/scss/containers";
|
@import "bootstrap-5.3.8/scss/containers";
|
||||||
@import "bootstrap-5.3.8/scss/grid";
|
|
||||||
@import "bootstrap-5.3.8/scss/tables";
|
@import "bootstrap-5.3.8/scss/tables";
|
||||||
@import "bootstrap-5.3.8/scss/forms";
|
@import "bootstrap-5.3.8/scss/forms";
|
||||||
@import "bootstrap-5.3.8/scss/buttons";
|
@import "bootstrap-5.3.8/scss/buttons";
|
||||||
|
|
|
||||||
|
|
@ -96,9 +96,10 @@ async fn about(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
|
|
||||||
## Panel de administración
|
## Panel de administración
|
||||||
|
|
||||||
En la plantilla `Admin`, Bootsier sigue la composición del núcleo: tras la cabecera pinta la
|
En la plantilla `Admin`, Bootsier sigue la composición del núcleo: en lugar del contenido pinta el
|
||||||
navegación del panel (`AdminMenu`) y, en lugar del contenido, el marco de la página (`AdminFrame`:
|
marco de la página (`AdminFrame`: migas, título, botones y pestañas). La navegación del panel
|
||||||
migas, título, botones y pestañas). Los dos se construyen con componentes del núcleo
|
(`Nav::admin()`) la coloca la aplicación, en una barra aparte o en su barra principal, donde se
|
||||||
|
pliega con su botón en pantallas pequeñas. Todo se construye con componentes del núcleo
|
||||||
(`Navbar`/`Nav`/`Dropdown`, `Breadcrumb`), que Bootsier ya pinta con su aspecto.
|
(`Navbar`/`Nav`/`Dropdown`, `Breadcrumb`), que Bootsier ya pinta con su aspecto.
|
||||||
|
|
||||||
## Selector de modo de color
|
## Selector de modo de color
|
||||||
|
|
@ -117,6 +118,87 @@ let navbar = bs::Navbar::simple().with_item(bs::navbar::Item::nav(
|
||||||
.with_item(bs::theme_toggle()),
|
.with_item(bs::theme_toggle()),
|
||||||
));
|
));
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Temas hijo
|
||||||
|
|
||||||
|
Un tema hijo hereda todo de Bootsier (plantillas, componentes, estilos, *scripts* y fuentes) y
|
||||||
|
cambia su aspecto con una hoja de estilos propia que se carga detrás de la de Bootsier. Esa hoja
|
||||||
|
sólo contiene lo que cambia: Bootstrap define casi todo su aspecto con variables CSS (`--bs-*`), y
|
||||||
|
basta con redefinirlas:
|
||||||
|
|
||||||
|
```css
|
||||||
|
:root {
|
||||||
|
--bs-border-radius: .25rem;
|
||||||
|
--bs-link-color: #6f42c1;
|
||||||
|
--bs-link-color-rgb: 111, 66, 193;
|
||||||
|
--bs-link-hover-color: #59359a;
|
||||||
|
--bs-link-hover-color-rgb: 89, 53, 154;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Las variantes de color de los componentes (`.btn-primary`, `.alert-primary`...) llevan sus propios
|
||||||
|
valores, así que se cambian redefiniendo las variables de cada componente:
|
||||||
|
|
||||||
|
```css
|
||||||
|
.btn-primary {
|
||||||
|
--bs-btn-bg: #6f42c1;
|
||||||
|
--bs-btn-border-color: #6f42c1;
|
||||||
|
--bs-btn-hover-bg: #59359a;
|
||||||
|
--bs-btn-hover-border-color: #59359a;
|
||||||
|
--bs-btn-active-bg: #4b2d83;
|
||||||
|
--bs-btn-active-border-color: #4b2d83;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Lo redefinido en `:root` vale también en el modo oscuro, porque gana a los valores oscuros de
|
||||||
|
Bootstrap; lo que deba ser distinto en él va dentro de `[data-bs-theme=dark] { ... }`.
|
||||||
|
|
||||||
|
El `build.rs` del tema hijo incluye la hoja en el binario con `pagetop-build`:
|
||||||
|
|
||||||
|
```rust,ignore
|
||||||
|
use pagetop_build::StaticFilesBundle;
|
||||||
|
|
||||||
|
fn main() -> std::io::Result<()> {
|
||||||
|
StaticFilesBundle::from_dir("./assets/css", None)
|
||||||
|
.with_name("my_theme_css")
|
||||||
|
.build()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
El tema la sirve con `serve_static_files!(files, [my_theme_css] => "/my-theme/css")` en
|
||||||
|
`Extension::configure_static_files()`, declara a Bootsier como padre y añade su hoja tras la de
|
||||||
|
Bootsier:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_bootsier::Bootsier;
|
||||||
|
|
||||||
|
pub struct MyTheme;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for MyTheme {
|
||||||
|
fn theme(&self) -> Option<ThemeRef> {
|
||||||
|
Some(&Self)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
vec![&Bootsier]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Theme for MyTheme {
|
||||||
|
fn parent(&self) -> Option<ThemeRef> {
|
||||||
|
Some(&Bootsier)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn before_render_page_body(&self, page: &mut Page) {
|
||||||
|
Bootsier.before_render_page_body(page);
|
||||||
|
// Justo detrás de la hoja de Bootsier (peso -99).
|
||||||
|
page.alter_assets(StyleSheet::from("/my-theme/css/my-theme.css").with_weight(-98));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#![doc(
|
#![doc(
|
||||||
|
|
@ -176,7 +258,7 @@ impl Theme for Bootsier {
|
||||||
fn breakpoint_entry(&self, bp: Breakpoint) -> BreakpointEntry {
|
fn breakpoint_entry(&self, bp: Breakpoint) -> BreakpointEntry {
|
||||||
use Breakpoint::*;
|
use Breakpoint::*;
|
||||||
|
|
||||||
// Anchos mínimos de la rejilla de Bootstrap (`$grid-breakpoints`). Bootstrap no tiene un
|
// Anchos mínimos de los puntos de corte de Bootstrap (`$grid-breakpoints`). No tiene un
|
||||||
// punto de corte por encima de `xxl`, así que `Xxxl` se resuelve como `xxl`.
|
// punto de corte por encima de `xxl`, así que `Xxxl` se resuelve como `xxl`.
|
||||||
match bp {
|
match bp {
|
||||||
Xs => BreakpointEntry { breakpoint: Xs, name: "xs", min_width: "" },
|
Xs => BreakpointEntry { breakpoint: Xs, name: "xs", min_width: "" },
|
||||||
|
|
|
||||||
|
|
@ -35,10 +35,13 @@
|
||||||
//!
|
//!
|
||||||
//! # Panel de administración
|
//! # Panel de administración
|
||||||
//!
|
//!
|
||||||
//! En la plantilla `Admin`, Bootsier sigue la composición del núcleo: tras la cabecera pinta la
|
//! En la plantilla `Admin`, Bootsier sigue la composición del núcleo: en lugar del contenido pinta
|
||||||
//! navegación del panel ([`AdminMenu`]) y, en lugar del contenido, el marco de la página
|
//! el marco de la página ([`AdminFrame`]: migas, título, botones y pestañas). La navegación del
|
||||||
//! ([`AdminFrame`]: migas, título, botones y pestañas). Los dos se construyen con componentes del
|
//! panel ([`Nav::admin()`]) la coloca la aplicación, en una barra aparte o en su barra principal,
|
||||||
//! núcleo ([`Navbar`]/[`Nav`]/[`Dropdown`], [`Breadcrumb`]), que Bootsier ya pinta con su aspecto.
|
//! donde se pliega con su botón en pantallas pequeñas. Todo se construye con componentes del núcleo
|
||||||
|
//! ([`Navbar`]/[`Nav`]/[`Dropdown`], [`Breadcrumb`]), que Bootsier ya pinta con su aspecto.
|
||||||
|
//!
|
||||||
|
//! [`AdminFrame`]: pagetop::prelude::layout::AdminFrame
|
||||||
//!
|
//!
|
||||||
//! # Selector de modo de color
|
//! # Selector de modo de color
|
||||||
//!
|
//!
|
||||||
|
|
|
||||||
|
|
@ -8,9 +8,9 @@ use crate::theme::bs;
|
||||||
// `CoreTemplates`, dejando que el resto de la cadena de temas (o el propio componente) resuelva el
|
// `CoreTemplates`, dejando que el resto de la cadena de temas (o el propio componente) resuelva el
|
||||||
// renderizado por defecto.
|
// renderizado por defecto.
|
||||||
//
|
//
|
||||||
// `CoreTemplates::Admin` sigue la composición del núcleo: tras la cabecera, la navegación del
|
// `CoreTemplates::Admin` sigue la composición del núcleo: en lugar del contenido, el marco de la
|
||||||
// panel (`AdminMenu`) y, en lugar del contenido, el marco de la página (`AdminFrame`), que
|
// página (`AdminFrame`), que contiene la región `Content`. La navegación del panel la coloca la
|
||||||
// contiene la región `Content`.
|
// aplicación (`Nav::admin()`).
|
||||||
pub(crate) async fn render(
|
pub(crate) async fn render(
|
||||||
component: &layout::Template,
|
component: &layout::Template,
|
||||||
cx: &mut Context,
|
cx: &mut Context,
|
||||||
|
|
@ -33,15 +33,13 @@ async fn render_standard(cx: &mut Context) -> Markup {
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
// Como `render_standard()`, con la navegación del panel tras la cabecera y el marco de la página
|
// Como `render_standard()`, con el marco de la página en lugar de la región `Content`.
|
||||||
// en lugar de la región `Content`.
|
|
||||||
async fn render_admin(cx: &mut Context) -> Markup {
|
async fn render_admin(cx: &mut Context) -> Markup {
|
||||||
wrapper()
|
wrapper()
|
||||||
.with_prop(PropsOp::add_classes("container-wrapper-admin"))
|
.with_prop(PropsOp::add_classes("container-wrapper-admin"))
|
||||||
.with_child(layout::Region::header())
|
.with_child(layout::Region::header())
|
||||||
.with_child(AdminMenu::new())
|
|
||||||
.with_child(layout::Region::aside())
|
.with_child(layout::Region::aside())
|
||||||
.with_child(AdminFrame::new())
|
.with_child(layout::AdminFrame::new())
|
||||||
.with_child(layout::Region::footer())
|
.with_child(layout::Region::footer())
|
||||||
.render(cx)
|
.render(cx)
|
||||||
.await
|
.await
|
||||||
|
|
|
||||||
|
|
@ -261,68 +261,66 @@ pub(crate) async fn render(navbar: &Navbar, cx: &mut Context) -> Result<Markup,
|
||||||
|
|
||||||
Ok(html! {
|
Ok(html! {
|
||||||
nav (navbar.props().unpack(cx)) {
|
nav (navbar.props().unpack(cx)) {
|
||||||
div class="container-fluid" {
|
@match layout {
|
||||||
@match layout {
|
// Barra más sencilla: sólo contenido.
|
||||||
// Barra más sencilla: sólo contenido.
|
bs::navbar::Layout::Simple => {
|
||||||
bs::navbar::Layout::Simple => {
|
(items)
|
||||||
|
},
|
||||||
|
|
||||||
|
// Barra sencilla que se puede contraer/expandir.
|
||||||
|
bs::navbar::Layout::SimpleToggle => {
|
||||||
|
(button(cx, TOGGLE_COLLAPSE, &id_content))
|
||||||
|
div id=(&id_content) class="collapse navbar-collapse" {
|
||||||
(items)
|
(items)
|
||||||
},
|
}
|
||||||
|
},
|
||||||
|
|
||||||
// Barra sencilla que se puede contraer/expandir.
|
// Barra con marca a la izquierda, siempre visible. El contenedor ocupa el espacio
|
||||||
bs::navbar::Layout::SimpleToggle => {
|
// que deja la marca y coloca en él los contenidos, como en las barras que se
|
||||||
(button(cx, TOGGLE_COLLAPSE, &id_content))
|
// contraen. Sin `collapse`, `setup()` garantiza `navbar-expand` y Bootstrap lo
|
||||||
div id=(&id_content) class="collapse navbar-collapse" {
|
// muestra siempre.
|
||||||
(items)
|
bs::navbar::Layout::SimpleBrandLeft(brand) => {
|
||||||
}
|
(brand.render(cx).await)
|
||||||
},
|
div class="navbar-collapse" { (items) }
|
||||||
|
},
|
||||||
|
|
||||||
// Barra con marca a la izquierda, siempre visible. El contenedor deja los
|
// Barra con marca a la izquierda y botón a la derecha.
|
||||||
// contenidos junto a la marca: sin él, el `space-between` de `container-fluid`
|
bs::navbar::Layout::BrandLeft(brand) => {
|
||||||
// los llevaría al extremo opuesto. Sin `collapse`, `setup()` garantiza
|
(brand.render(cx).await)
|
||||||
// `navbar-expand` y Bootstrap lo muestra siempre.
|
(button(cx, TOGGLE_COLLAPSE, &id_content))
|
||||||
bs::navbar::Layout::SimpleBrandLeft(brand) => {
|
div id=(&id_content) class="collapse navbar-collapse" {
|
||||||
(brand.render(cx).await)
|
(items)
|
||||||
div class="navbar-collapse" { (items) }
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// Barra con marca a la izquierda y botón a la derecha.
|
// Barra con botón a la izquierda y marca a la derecha.
|
||||||
bs::navbar::Layout::BrandLeft(brand) => {
|
bs::navbar::Layout::BrandRight(brand) => {
|
||||||
(brand.render(cx).await)
|
(button(cx, TOGGLE_COLLAPSE, &id_content))
|
||||||
(button(cx, TOGGLE_COLLAPSE, &id_content))
|
(brand.render(cx).await)
|
||||||
div id=(&id_content) class="collapse navbar-collapse" {
|
div id=(&id_content) class="collapse navbar-collapse" {
|
||||||
(items)
|
(items)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
// Barra con botón a la izquierda y marca a la derecha.
|
// Barra cuyo contenido se muestra en un panel lateral, sin marca.
|
||||||
bs::navbar::Layout::BrandRight(brand) => {
|
bs::navbar::Layout::Offcanvas(panel) => {
|
||||||
(button(cx, TOGGLE_COLLAPSE, &id_content))
|
(button(cx, TOGGLE_OFFCANVAS, &id_content))
|
||||||
(brand.render(cx).await)
|
(panel.render_panel(cx, &id_content, &items))
|
||||||
div id=(&id_content) class="collapse navbar-collapse" {
|
},
|
||||||
(items)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
// Barra cuyo contenido se muestra en un panel lateral, sin marca.
|
// Barra con marca a la izquierda y contenido en un panel lateral.
|
||||||
bs::navbar::Layout::Offcanvas(panel) => {
|
bs::navbar::Layout::OffcanvasBrandLeft(brand, panel) => {
|
||||||
(button(cx, TOGGLE_OFFCANVAS, &id_content))
|
(brand.render(cx).await)
|
||||||
(panel.render_panel(cx, &id_content, &items))
|
(button(cx, TOGGLE_OFFCANVAS, &id_content))
|
||||||
},
|
(panel.render_panel(cx, &id_content, &items))
|
||||||
|
},
|
||||||
|
|
||||||
// Barra con marca a la izquierda y contenido en un panel lateral.
|
// Barra con contenido en un panel lateral y marca a la derecha.
|
||||||
bs::navbar::Layout::OffcanvasBrandLeft(brand, panel) => {
|
bs::navbar::Layout::OffcanvasBrandRight(brand, panel) => {
|
||||||
(brand.render(cx).await)
|
(button(cx, TOGGLE_OFFCANVAS, &id_content))
|
||||||
(button(cx, TOGGLE_OFFCANVAS, &id_content))
|
(brand.render(cx).await)
|
||||||
(panel.render_panel(cx, &id_content, &items))
|
(panel.render_panel(cx, &id_content, &items))
|
||||||
},
|
},
|
||||||
|
|
||||||
// Barra con contenido en un panel lateral y marca a la derecha.
|
|
||||||
bs::navbar::Layout::OffcanvasBrandRight(brand, panel) => {
|
|
||||||
(button(cx, TOGGLE_OFFCANVAS, &id_content))
|
|
||||||
(brand.render(cx).await)
|
|
||||||
(panel.render_panel(cx, &id_content, &items))
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ use pagetop::prelude::*;
|
||||||
|
|
||||||
use tokio::sync::{Notify, watch};
|
use tokio::sync::{Notify, watch};
|
||||||
|
|
||||||
use crate::config::{CronMode, JobSettings, SETTINGS};
|
use crate::config;
|
||||||
use crate::schedule::Trigger;
|
use crate::schedule::Trigger;
|
||||||
use crate::{AfterJobRun, CronError, CronJobs, Job, JobContext, JobOutcome, JobRun, JobStatus};
|
use crate::{AfterJobRun, CronError, CronJobs, Job, JobContext, JobOutcome, JobRun, JobStatus};
|
||||||
use crate::{Overlap, RunTrigger, Schedule};
|
use crate::{Overlap, RunTrigger, Schedule};
|
||||||
|
|
@ -102,18 +102,19 @@ fn build(jobs: Vec<Job>, now: DateTime<Utc>) -> Result<Registry, CronError> {
|
||||||
if !is_valid_key(&key) {
|
if !is_valid_key(&key) {
|
||||||
return Err(CronError::InvalidKey(key));
|
return Err(CronError::InvalidKey(key));
|
||||||
}
|
}
|
||||||
let entry = Entry::new(job, SETTINGS.jobs.get(&key), default_tz, now).map_err(|err| {
|
let entry =
|
||||||
CronError::InvalidJob {
|
Entry::new(job, config::SETTINGS.jobs.get(&key), default_tz, now).map_err(|err| {
|
||||||
key: key.clone(),
|
CronError::InvalidJob {
|
||||||
source: Box::new(err),
|
key: key.clone(),
|
||||||
}
|
source: Box::new(err),
|
||||||
})?;
|
}
|
||||||
|
})?;
|
||||||
if !keys.insert(key.clone()) {
|
if !keys.insert(key.clone()) {
|
||||||
return Err(CronError::DuplicateJob(key));
|
return Err(CronError::DuplicateJob(key));
|
||||||
}
|
}
|
||||||
entries.push(Arc::new(entry));
|
entries.push(Arc::new(entry));
|
||||||
}
|
}
|
||||||
for key in SETTINGS.jobs.keys() {
|
for key in config::SETTINGS.jobs.keys() {
|
||||||
if !keys.contains(key) {
|
if !keys.contains(key) {
|
||||||
trace::warn!("Unknown cron job \"{key}\" in [cron.jobs], ignored. Check settings");
|
trace::warn!("Unknown cron job \"{key}\" in [cron.jobs], ignored. Check settings");
|
||||||
}
|
}
|
||||||
|
|
@ -132,7 +133,7 @@ fn is_valid_key(key: &str) -> bool {
|
||||||
// El modo externo necesita una clave larga y que se pueda escribir tal cual en la cabecera, y un
|
// El modo externo necesita una clave larga y que se pueda escribir tal cual en la cabecera, y un
|
||||||
// intervalo entre llamadas válido.
|
// intervalo entre llamadas válido.
|
||||||
fn check_external_settings() -> Result<(), CronError> {
|
fn check_external_settings() -> Result<(), CronError> {
|
||||||
if SETTINGS.mode != CronMode::External {
|
if config::SETTINGS.mode != config::CronMode::External {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let valid = trigger_token().is_some_and(|token| {
|
let valid = trigger_token().is_some_and(|token| {
|
||||||
|
|
@ -160,11 +161,14 @@ fn check_external_settings() -> Result<(), CronError> {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn trigger_token() -> Option<&'static str> {
|
fn trigger_token() -> Option<&'static str> {
|
||||||
SETTINGS.trigger_token.as_deref().and_then(util::non_blank)
|
config::SETTINGS
|
||||||
|
.trigger_token
|
||||||
|
.as_deref()
|
||||||
|
.and_then(util::non_blank)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn trigger_interval() -> Option<Duration> {
|
fn trigger_interval() -> Option<Duration> {
|
||||||
let secs = i64::try_from(SETTINGS.trigger_interval_secs).ok()?;
|
let secs = i64::try_from(config::SETTINGS.trigger_interval_secs).ok()?;
|
||||||
Duration::try_seconds(secs)
|
Duration::try_seconds(secs)
|
||||||
.filter(|interval| *interval >= Duration::seconds(1) && *interval <= Duration::days(36_500))
|
.filter(|interval| *interval >= Duration::seconds(1) && *interval <= Duration::days(36_500))
|
||||||
}
|
}
|
||||||
|
|
@ -195,7 +199,7 @@ pub(crate) fn token_matches(given: &str) -> bool {
|
||||||
impl Entry {
|
impl Entry {
|
||||||
fn new(
|
fn new(
|
||||||
job: Job,
|
job: Job,
|
||||||
settings: Option<&JobSettings>,
|
settings: Option<&config::JobSettings>,
|
||||||
default_tz: Tz,
|
default_tz: Tz,
|
||||||
now: DateTime<Utc>,
|
now: DateTime<Utc>,
|
||||||
) -> Result<Self, CronError> {
|
) -> Result<Self, CronError> {
|
||||||
|
|
@ -231,7 +235,7 @@ impl Entry {
|
||||||
|
|
||||||
// Con el modo externo, la próxima ejecución se conoce desde el arranque; la del arranque,
|
// Con el modo externo, la próxima ejecución se conoce desde el arranque; la del arranque,
|
||||||
// si la hay, la hace la primera llamada.
|
// si la hay, la hace la primera llamada.
|
||||||
let external = enabled && SETTINGS.mode == CronMode::External;
|
let external = enabled && config::SETTINGS.mode == config::CronMode::External;
|
||||||
let pending_start = external && job.run_on_start();
|
let pending_start = external && job.run_on_start();
|
||||||
let next_run = match (external, pending_start) {
|
let next_run = match (external, pending_start) {
|
||||||
(true, true) => Some(now),
|
(true, true) => Some(now),
|
||||||
|
|
@ -440,7 +444,7 @@ pub async fn run_now(key: impl AsRef<str>) -> Result<JobRun, CronError> {
|
||||||
/// hasta el final. Si se abandona la espera (p. ej. el programa externo cierra la conexión), los
|
/// hasta el final. Si se abandona la espera (p. ej. el programa externo cierra la conexión), los
|
||||||
/// trabajos siguen igualmente hasta terminar o agotar su tiempo máximo.
|
/// trabajos siguen igualmente hasta terminar o agotar su tiempo máximo.
|
||||||
pub async fn run_due() -> Vec<JobRun> {
|
pub async fn run_due() -> Vec<JobRun> {
|
||||||
if SETTINGS.mode != CronMode::External {
|
if config::SETTINGS.mode != config::CronMode::External {
|
||||||
trace::warn!("Cron run_due() ignored: [cron].mode is not \"external\"");
|
trace::warn!("Cron run_due() ignored: [cron].mode is not \"external\"");
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
}
|
}
|
||||||
|
|
@ -493,17 +497,17 @@ pub(crate) fn start() {
|
||||||
}
|
}
|
||||||
let total = registry.entries.len();
|
let total = registry.entries.len();
|
||||||
let enabled = registry.entries.iter().filter(|e| e.enabled).count();
|
let enabled = registry.entries.iter().filter(|e| e.enabled).count();
|
||||||
match SETTINGS.mode {
|
match config::SETTINGS.mode {
|
||||||
CronMode::Internal => {
|
config::CronMode::Internal => {
|
||||||
for entry in registry.entries.iter().filter(|e| e.enabled) {
|
for entry in registry.entries.iter().filter(|e| e.enabled) {
|
||||||
tokio::spawn(job_loop(Arc::clone(entry)));
|
tokio::spawn(job_loop(Arc::clone(entry)));
|
||||||
}
|
}
|
||||||
trace::info!("Cron scheduler started with {enabled} of {total} jobs");
|
trace::info!("Cron scheduler started with {enabled} of {total} jobs");
|
||||||
}
|
}
|
||||||
CronMode::External => trace::info!(
|
config::CronMode::External => trace::info!(
|
||||||
"Cron jobs ({enabled} of {total}) run on authorized calls to POST {TRIGGER_PATH}"
|
"Cron jobs ({enabled} of {total}) run on authorized calls to POST {TRIGGER_PATH}"
|
||||||
),
|
),
|
||||||
CronMode::Off => {
|
config::CronMode::Off => {
|
||||||
trace::info!("Cron jobs ({total}) only run on demand: [cron].mode is \"off\"");
|
trace::info!("Cron jobs ({total}) only run on demand: [cron].mode is \"off\"");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -674,7 +678,7 @@ pub(crate) async fn shutdown() {
|
||||||
if active == 0 {
|
if active == 0 {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let limit = SETTINGS.shutdown_timeout_secs;
|
let limit = config::SETTINGS.shutdown_timeout_secs;
|
||||||
trace::info!("Waiting up to {limit} s for {active} running cron jobs to finish");
|
trace::info!("Waiting up to {limit} s for {active} running cron jobs to finish");
|
||||||
let idle = async {
|
let idle = async {
|
||||||
loop {
|
loop {
|
||||||
|
|
@ -707,7 +711,7 @@ mod tests {
|
||||||
|
|
||||||
// Settings come from this crate's `config/common.toml` (external mode, Madrid timezone).
|
// Settings come from this crate's `config/common.toml` (external mode, Madrid timezone).
|
||||||
fn load_settings() {
|
fn load_settings() {
|
||||||
SETTINGS.load().unwrap();
|
config::SETTINGS.load().unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn noop(_cx: JobContext) -> crate::JobResult {
|
async fn noop(_cx: JobContext) -> crate::JobResult {
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ use pagetop::prelude::*;
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use crate::config::{self, MailTransport, SmtpSecurity};
|
use crate::config;
|
||||||
use crate::{Email, LOCALES_MAIL, Mailbox};
|
use crate::{Email, LOCALES_MAIL, Mailbox};
|
||||||
|
|
||||||
// Ruta de la página, relativa a la raíz del panel.
|
// Ruta de la página, relativa a la raíz del panel.
|
||||||
|
|
@ -124,8 +124,8 @@ async fn test_mail_post(
|
||||||
// Aviso si el transporte configurado no entrega los correos.
|
// Aviso si el transporte configurado no entrega los correos.
|
||||||
fn not_delivered_warning() -> Option<Lc> {
|
fn not_delivered_warning() -> Option<Lc> {
|
||||||
let key = match config::SETTINGS.transport {
|
let key = match config::SETTINGS.transport {
|
||||||
MailTransport::Log => "test_log_warning",
|
config::MailTransport::Log => "test_log_warning",
|
||||||
MailTransport::Memory => "test_memory_warning",
|
config::MailTransport::Memory => "test_memory_warning",
|
||||||
_ => return None,
|
_ => return None,
|
||||||
};
|
};
|
||||||
Some(Lc::t(key, &LOCALES_MAIL))
|
Some(Lc::t(key, &LOCALES_MAIL))
|
||||||
|
|
@ -138,11 +138,11 @@ fn settings_summary() -> Block {
|
||||||
let text = |value: &Option<String>| value.clone().map_or_else(none, Lc::n);
|
let text = |value: &Option<String>| value.clone().map_or_else(none, Lc::n);
|
||||||
|
|
||||||
let transport = match settings.transport {
|
let transport = match settings.transport {
|
||||||
MailTransport::Smtp => "transport_smtp",
|
config::MailTransport::Smtp => "transport_smtp",
|
||||||
MailTransport::Sendmail => "transport_sendmail",
|
config::MailTransport::Sendmail => "transport_sendmail",
|
||||||
MailTransport::File => "transport_file",
|
config::MailTransport::File => "transport_file",
|
||||||
MailTransport::Log => "transport_log",
|
config::MailTransport::Log => "transport_log",
|
||||||
MailTransport::Memory => "transport_memory",
|
config::MailTransport::Memory => "transport_memory",
|
||||||
};
|
};
|
||||||
let mut rows = vec![
|
let mut rows = vec![
|
||||||
("test_transport", Lc::t(transport, &LOCALES_MAIL)),
|
("test_transport", Lc::t(transport, &LOCALES_MAIL)),
|
||||||
|
|
@ -153,25 +153,25 @@ fn settings_summary() -> Block {
|
||||||
rows.push(("test_redirect_to", text(&settings.redirect_to)));
|
rows.push(("test_redirect_to", text(&settings.redirect_to)));
|
||||||
}
|
}
|
||||||
match settings.transport {
|
match settings.transport {
|
||||||
MailTransport::Smtp => {
|
config::MailTransport::Smtp => {
|
||||||
let smtp = &settings.smtp;
|
let smtp = &settings.smtp;
|
||||||
let (security, default_port) = match smtp.security {
|
let (security, default_port) = match smtp.security {
|
||||||
SmtpSecurity::None => ("security_none", 25),
|
config::SmtpSecurity::None => ("security_none", 25),
|
||||||
SmtpSecurity::Opportunistic => ("security_opportunistic", 25),
|
config::SmtpSecurity::Opportunistic => ("security_opportunistic", 25),
|
||||||
SmtpSecurity::StartTls => ("security_starttls", 587),
|
config::SmtpSecurity::StartTls => ("security_starttls", 587),
|
||||||
SmtpSecurity::Tls => ("security_tls", 465),
|
config::SmtpSecurity::Tls => ("security_tls", 465),
|
||||||
};
|
};
|
||||||
let port = smtp.port.unwrap_or(default_port).to_string();
|
let port = smtp.port.unwrap_or(default_port).to_string();
|
||||||
rows.push(("test_smtp_server", Lc::n(util::join!(smtp.host, ":", port))));
|
rows.push(("test_smtp_server", Lc::n(util::join!(smtp.host, ":", port))));
|
||||||
rows.push(("test_smtp_security", Lc::t(security, &LOCALES_MAIL)));
|
rows.push(("test_smtp_security", Lc::t(security, &LOCALES_MAIL)));
|
||||||
}
|
}
|
||||||
MailTransport::Sendmail => {
|
config::MailTransport::Sendmail => {
|
||||||
rows.push(("test_sendmail_command", text(&settings.sendmail.command)));
|
rows.push(("test_sendmail_command", text(&settings.sendmail.command)));
|
||||||
}
|
}
|
||||||
MailTransport::File => {
|
config::MailTransport::File => {
|
||||||
rows.push(("test_file_dir", Lc::n(settings.file.dir.clone())));
|
rows.push(("test_file_dir", Lc::n(settings.file.dir.clone())));
|
||||||
}
|
}
|
||||||
MailTransport::Log | MailTransport::Memory => {}
|
config::MailTransport::Log | config::MailTransport::Memory => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut table = Table::new();
|
let mut table = Table::new();
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
use crate::config::{self, MailTransport, SmtpSecurity, SmtpSettings};
|
use crate::config;
|
||||||
use crate::{Email, MailError, Mailbox, outbox};
|
use crate::{Email, MailError, Mailbox, outbox};
|
||||||
|
|
||||||
use lettre::Transport as _;
|
use lettre::Transport as _;
|
||||||
|
|
@ -289,22 +289,28 @@ impl Mailer {
|
||||||
#[cfg(feature = "queue")]
|
#[cfg(feature = "queue")]
|
||||||
crate::queue::check_settings()?;
|
crate::queue::check_settings()?;
|
||||||
let slots = match settings.transport {
|
let slots = match settings.transport {
|
||||||
MailTransport::Smtp => slots("mail.smtp.pool_max_size", settings.smtp.pool_max_size)?,
|
config::MailTransport::Smtp => {
|
||||||
MailTransport::Sendmail => slots(
|
slots("mail.smtp.pool_max_size", settings.smtp.pool_max_size)?
|
||||||
|
}
|
||||||
|
config::MailTransport::Sendmail => slots(
|
||||||
"mail.sendmail.max_concurrent",
|
"mail.sendmail.max_concurrent",
|
||||||
settings.sendmail.max_concurrent,
|
settings.sendmail.max_concurrent,
|
||||||
)?,
|
)?,
|
||||||
MailTransport::File => slots("mail.file.max_concurrent", settings.file.max_concurrent)?,
|
config::MailTransport::File => {
|
||||||
|
slots("mail.file.max_concurrent", settings.file.max_concurrent)?
|
||||||
|
}
|
||||||
// Sin turnos: se entregan al momento.
|
// Sin turnos: se entregan al momento.
|
||||||
MailTransport::Log | MailTransport::Memory => 1,
|
config::MailTransport::Log | config::MailTransport::Memory => 1,
|
||||||
};
|
};
|
||||||
let transport = match settings.transport {
|
let transport = match settings.transport {
|
||||||
MailTransport::Smtp => Transport::Smtp(smtp_transport(&settings.smtp)?),
|
config::MailTransport::Smtp => Transport::Smtp(smtp_transport(&settings.smtp)?),
|
||||||
MailTransport::Sendmail => Transport::Sendmail(match &settings.sendmail.command {
|
config::MailTransport::Sendmail => {
|
||||||
Some(command) => AsyncSendmailTransport::new_with_command(command),
|
Transport::Sendmail(match &settings.sendmail.command {
|
||||||
None => AsyncSendmailTransport::new(),
|
Some(command) => AsyncSendmailTransport::new_with_command(command),
|
||||||
}),
|
None => AsyncSendmailTransport::new(),
|
||||||
MailTransport::File => {
|
})
|
||||||
|
}
|
||||||
|
config::MailTransport::File => {
|
||||||
let dir = PathBuf::from(&settings.file.dir);
|
let dir = PathBuf::from(&settings.file.dir);
|
||||||
std::fs::create_dir_all(&dir).map_err(|source| MailError::CreateDir {
|
std::fs::create_dir_all(&dir).map_err(|source| MailError::CreateDir {
|
||||||
path: dir.clone(),
|
path: dir.clone(),
|
||||||
|
|
@ -312,8 +318,8 @@ impl Mailer {
|
||||||
})?;
|
})?;
|
||||||
Transport::File(AsyncFileTransport::new(dir))
|
Transport::File(AsyncFileTransport::new(dir))
|
||||||
}
|
}
|
||||||
MailTransport::Log => Transport::Log,
|
config::MailTransport::Log => Transport::Log,
|
||||||
MailTransport::Memory => Transport::Memory,
|
config::MailTransport::Memory => Transport::Memory,
|
||||||
};
|
};
|
||||||
let redirect_to = match settings.redirect_to.as_deref().and_then(util::non_blank) {
|
let redirect_to = match settings.redirect_to.as_deref().and_then(util::non_blank) {
|
||||||
Some(address) => Some(address.parse::<Address>().map_err(|source| {
|
Some(address) => Some(address.parse::<Address>().map_err(|source| {
|
||||||
|
|
@ -410,7 +416,7 @@ fn tickets(slots: usize, max_waiting: u32) -> usize {
|
||||||
.min(Semaphore::MAX_PERMITS)
|
.min(Semaphore::MAX_PERMITS)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn smtp_transport(smtp: &SmtpSettings) -> Result<SmtpTransport, MailError> {
|
fn smtp_transport(smtp: &config::SmtpSettings) -> Result<SmtpTransport, MailError> {
|
||||||
let tls_parameters = || {
|
let tls_parameters = || {
|
||||||
TlsParameters::builder(smtp.host.clone())
|
TlsParameters::builder(smtp.host.clone())
|
||||||
.dangerous_accept_invalid_certs(smtp.accept_invalid_certs)
|
.dangerous_accept_invalid_certs(smtp.accept_invalid_certs)
|
||||||
|
|
@ -418,10 +424,10 @@ fn smtp_transport(smtp: &SmtpSettings) -> Result<SmtpTransport, MailError> {
|
||||||
.map_err(|err| invalid_setting("mail.smtp", MailError::Smtp(err)))
|
.map_err(|err| invalid_setting("mail.smtp", MailError::Smtp(err)))
|
||||||
};
|
};
|
||||||
let (tls, default_port) = match smtp.security {
|
let (tls, default_port) = match smtp.security {
|
||||||
SmtpSecurity::None => (Tls::None, 25),
|
config::SmtpSecurity::None => (Tls::None, 25),
|
||||||
SmtpSecurity::Opportunistic => (Tls::Opportunistic(tls_parameters()?), 25),
|
config::SmtpSecurity::Opportunistic => (Tls::Opportunistic(tls_parameters()?), 25),
|
||||||
SmtpSecurity::StartTls => (Tls::Required(tls_parameters()?), 587),
|
config::SmtpSecurity::StartTls => (Tls::Required(tls_parameters()?), 587),
|
||||||
SmtpSecurity::Tls => (Tls::Wrapper(tls_parameters()?), 465),
|
config::SmtpSecurity::Tls => (Tls::Wrapper(tls_parameters()?), 465),
|
||||||
};
|
};
|
||||||
let mut builder = SmtpTransport::builder_dangerous(&smtp.host)
|
let mut builder = SmtpTransport::builder_dangerous(&smtp.host)
|
||||||
.port(smtp.port.unwrap_or(default_port))
|
.port(smtp.port.unwrap_or(default_port))
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ use pagetop::prelude::*;
|
||||||
use pagetop_seaorm::db::*;
|
use pagetop_seaorm::db::*;
|
||||||
|
|
||||||
use crate::account::UserStatus;
|
use crate::account::UserStatus;
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::entity::{role_permission, user, user_identity};
|
use crate::entity::{role_permission, user, user_identity};
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
use crate::identity::{self, Email, Username};
|
use crate::identity::{self, Email, Username};
|
||||||
|
|
@ -101,7 +101,7 @@ pub(crate) async fn login(
|
||||||
_ => Vec::new(),
|
_ => Vec::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let fallback = SETTINGS.login.local_fallback;
|
let fallback = config::SETTINGS.login.local_fallback;
|
||||||
let mut released = false;
|
let mut released = false;
|
||||||
if let Some(user) = local
|
if let Some(user) = local
|
||||||
.as_ref()
|
.as_ref()
|
||||||
|
|
@ -288,7 +288,7 @@ pub async fn register(
|
||||||
plain_password: &str,
|
plain_password: &str,
|
||||||
confirm_password: &str,
|
confirm_password: &str,
|
||||||
) -> Result<i32, AuthError> {
|
) -> Result<i32, AuthError> {
|
||||||
let username = identity::username(username, SETTINGS.identity_policy, None)?;
|
let username = identity::username(username, config::SETTINGS.identity_policy, None)?;
|
||||||
let email = identity::email(email)?;
|
let email = identity::email(email)?;
|
||||||
password::validate_strength(plain_password)?;
|
password::validate_strength(plain_password)?;
|
||||||
password::passwords_match(plain_password, confirm_password)?;
|
password::passwords_match(plain_password, confirm_password)?;
|
||||||
|
|
@ -297,7 +297,7 @@ pub async fn register(
|
||||||
|
|
||||||
let hash = password::hash_password_async(plain_password).await?;
|
let hash = password::hash_password_async(plain_password).await?;
|
||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
let status = if SETTINGS.require_email_verification {
|
let status = if config::SETTINGS.require_email_verification {
|
||||||
UserStatus::Pending
|
UserStatus::Pending
|
||||||
} else {
|
} else {
|
||||||
UserStatus::Active
|
UserStatus::Active
|
||||||
|
|
@ -556,9 +556,9 @@ async fn register_failed_login(
|
||||||
user_model.failed_login_at,
|
user_model.failed_login_at,
|
||||||
now,
|
now,
|
||||||
FailedLoginPolicy {
|
FailedLoginPolicy {
|
||||||
max: SETTINGS.max_failed_logins,
|
max: config::SETTINGS.max_failed_logins,
|
||||||
window: Duration::seconds(SETTINGS.failed_login_window_secs),
|
window: Duration::seconds(config::SETTINGS.failed_login_window_secs),
|
||||||
locked_for: Duration::seconds(SETTINGS.locked_for_secs),
|
locked_for: Duration::seconds(config::SETTINGS.locked_for_secs),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
user::ActiveModel {
|
user::ActiveModel {
|
||||||
|
|
@ -617,8 +617,8 @@ fn failed_login_outcome(
|
||||||
/// Falla con [`AuthError::InvalidSetting`] si el nombre de usuario o el email configurados no son
|
/// Falla con [`AuthError::InvalidSetting`] si el nombre de usuario o el email configurados no son
|
||||||
/// válidos, aunque ya existan usuarios, como cualquier otro ajuste no válido.
|
/// válidos, aunque ya existan usuarios, como cualquier otro ajuste no válido.
|
||||||
pub(crate) async fn seed_initial_data() -> Result<(), AuthError> {
|
pub(crate) async fn seed_initial_data() -> Result<(), AuthError> {
|
||||||
let cfg = &SETTINGS.seed;
|
let cfg = &config::SETTINGS.seed;
|
||||||
let username = identity::username(&cfg.admin_username, SETTINGS.identity_policy, None)
|
let username = identity::username(&cfg.admin_username, config::SETTINGS.identity_policy, None)
|
||||||
.map_err(|err| invalid_setting("user.seed.admin_username", err))?;
|
.map_err(|err| invalid_setting("user.seed.admin_username", err))?;
|
||||||
let email = identity::email(&cfg.admin_email)
|
let email = identity::email(&cfg.admin_email)
|
||||||
.map_err(|err| invalid_setting("user.seed.admin_email", err))?;
|
.map_err(|err| invalid_setting("user.seed.admin_email", err))?;
|
||||||
|
|
@ -639,7 +639,7 @@ async fn do_seed(username: Username, email: Email) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let cfg = &SETTINGS.seed;
|
let cfg = &config::SETTINGS.seed;
|
||||||
let (admin_password, generated) = match &cfg.admin_password {
|
let (admin_password, generated) = match &cfg.admin_password {
|
||||||
Some(p) if !p.is_empty() => (p.clone(), false),
|
Some(p) if !p.is_empty() => (p.clone(), false),
|
||||||
_ => {
|
_ => {
|
||||||
|
|
|
||||||
|
|
@ -26,10 +26,9 @@ use pagetop::prelude::*;
|
||||||
|
|
||||||
use crate::account::UserStatus;
|
use crate::account::UserStatus;
|
||||||
use crate::component::admin::status_key;
|
use crate::component::admin::status_key;
|
||||||
use crate::config::{user_language_applies, user_timezone_applies};
|
|
||||||
use crate::entity::user;
|
use crate::entity::user;
|
||||||
use crate::provider;
|
|
||||||
use crate::{LOCALES_USER, PROFILE_PATH};
|
use crate::{LOCALES_USER, PROFILE_PATH};
|
||||||
|
use crate::{config, provider};
|
||||||
|
|
||||||
// Texto libre de varias líneas como contenido seguro: cada salto de línea se convierte en `<br>`,
|
// Texto libre de varias líneas como contenido seguro: cada salto de línea se convierte en `<br>`,
|
||||||
// sin depender del CSS del tema. Se usa para mostrar el "Sobre mí" del usuario.
|
// sin depender del CSS del tema. Se usa para mostrar el "Sobre mí" del usuario.
|
||||||
|
|
@ -138,26 +137,28 @@ pub(crate) async fn user_details(user: &user::Model, cx: &mut Context) -> Block
|
||||||
)),
|
)),
|
||||||
);
|
);
|
||||||
// Sólo se muestran si se aplican, igual que en el formulario de edición.
|
// Sólo se muestran si se aplican, igual que en el formulario de edición.
|
||||||
if user_language_applies() {
|
if config::user_language_applies() {
|
||||||
table = table.with_row(
|
table = table.with_row(
|
||||||
table::Row::new()
|
table::Row::new()
|
||||||
.with_cell(Lc::t("field-language", &LOCALES_USER))
|
.with_cell(Lc::t("field-language", &LOCALES_USER))
|
||||||
.with_cell(language_name(user.language.as_deref())),
|
.with_cell(language_name(user.language.as_deref())),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if user_timezone_applies() {
|
if config::user_timezone_applies() {
|
||||||
table = table.with_row(
|
table = table.with_row(
|
||||||
table::Row::new()
|
table::Row::new()
|
||||||
.with_cell(Lc::t("field-timezone", &LOCALES_USER))
|
.with_cell(Lc::t("field-timezone", &LOCALES_USER))
|
||||||
.with_cell(user.timezone.as_deref().unwrap_or("-")),
|
.with_cell(user.timezone.as_deref().unwrap_or("-")),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
table = table
|
if config::user_theme_applies() {
|
||||||
.with_row(
|
table = table.with_row(
|
||||||
table::Row::new()
|
table::Row::new()
|
||||||
.with_cell(Lc::t("field-theme", &LOCALES_USER))
|
.with_cell(Lc::t("field-theme", &LOCALES_USER))
|
||||||
.with_cell(theme_name(user.theme.as_deref())),
|
.with_cell(theme_name(user.theme.as_deref())),
|
||||||
)
|
);
|
||||||
|
}
|
||||||
|
table = table
|
||||||
.with_row(
|
.with_row(
|
||||||
table::Row::new()
|
table::Row::new()
|
||||||
.with_cell(Lc::t("col-status", &LOCALES_USER))
|
.with_cell(Lc::t("col-status", &LOCALES_USER))
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
use pagetop_htmx::prelude::*;
|
use pagetop_htmx::prelude::*;
|
||||||
|
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::{LOCALES_USER, LOGIN_PATH, LOGOUT_PATH, PROFILE_PATH, REGISTER_PATH};
|
use crate::{LOCALES_USER, LOGIN_PATH, LOGOUT_PATH, PROFILE_PATH, REGISTER_PATH};
|
||||||
|
|
||||||
/// Construye el menú de cuenta como un [`Nav`] justificado al final de su contenedor.
|
/// Construye el menú de cuenta como un [`Nav`] justificado al final de su contenedor.
|
||||||
|
|
@ -59,7 +59,7 @@ pub fn account_menu(cx: &Context) -> Nav {
|
||||||
Lc::t("menu-login", &LOCALES_USER),
|
Lc::t("menu-login", &LOCALES_USER),
|
||||||
cx.route(LOGIN_PATH),
|
cx.route(LOGIN_PATH),
|
||||||
));
|
));
|
||||||
if SETTINGS.allow_registration {
|
if config::SETTINGS.allow_registration {
|
||||||
nav.with_item(nav::Item::link(
|
nav.with_item(nav::Item::link(
|
||||||
Lc::t("link-register", &LOCALES_USER),
|
Lc::t("link-register", &LOCALES_USER),
|
||||||
cx.route(REGISTER_PATH),
|
cx.route(REGISTER_PATH),
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
use crate::LOCALES_USER;
|
use crate::LOCALES_USER;
|
||||||
use crate::config::{SETTINGS, user_language_applies, user_timezone_applies};
|
use crate::config;
|
||||||
use crate::user_path;
|
use crate::user_path;
|
||||||
use crate::{ADMIN_USERS_PATH, PROFILE_EDIT_PATH};
|
use crate::{ADMIN_USERS_PATH, PROFILE_EDIT_PATH};
|
||||||
|
|
||||||
|
|
@ -102,12 +102,12 @@ impl Component for UserForm {
|
||||||
} else if username_readonly {
|
} else if username_readonly {
|
||||||
Lc::none()
|
Lc::none()
|
||||||
} else {
|
} else {
|
||||||
username_help(SETTINGS.identity_policy)
|
username_help(config::SETTINGS.identity_policy)
|
||||||
})
|
})
|
||||||
.with_required(true)
|
.with_required(true)
|
||||||
.with_readonly(username_readonly)
|
.with_readonly(username_readonly)
|
||||||
.with_minlength(USERNAME_MIN_CHARS)
|
.with_minlength(USERNAME_MIN_CHARS)
|
||||||
.with_maxlength(username_max_chars(SETTINGS.identity_policy)),
|
.with_maxlength(username_max_chars(config::SETTINGS.identity_policy)),
|
||||||
)
|
)
|
||||||
.with_child(
|
.with_child(
|
||||||
form::input::Field::email()
|
form::input::Field::email()
|
||||||
|
|
@ -135,9 +135,9 @@ impl Component for UserForm {
|
||||||
.with_maxlength(DISPLAY_NAME_MAX_CHARS),
|
.with_maxlength(DISPLAY_NAME_MAX_CHARS),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Sólo se ofrecen si se aplican (ver `config::user_language_applies()` y
|
// Sólo se ofrecen si se aplican (ver `config::user_language_applies()`,
|
||||||
// `config::user_timezone_applies()`).
|
// `config::user_timezone_applies()` y `config::user_theme_applies()`).
|
||||||
if user_language_applies() {
|
if config::user_language_applies() {
|
||||||
form = form.with_child(
|
form = form.with_child(
|
||||||
form::SelectLanguage::new()
|
form::SelectLanguage::new()
|
||||||
.with_name("language")
|
.with_name("language")
|
||||||
|
|
@ -146,7 +146,7 @@ impl Component for UserForm {
|
||||||
.with_selected(self.language()),
|
.with_selected(self.language()),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if user_timezone_applies() {
|
if config::user_timezone_applies() {
|
||||||
form = form.with_child(
|
form = form.with_child(
|
||||||
form::SelectTimezone::new()
|
form::SelectTimezone::new()
|
||||||
.with_name("timezone")
|
.with_name("timezone")
|
||||||
|
|
@ -156,13 +156,15 @@ impl Component for UserForm {
|
||||||
.with_selected(self.timezone()),
|
.with_selected(self.timezone()),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
form = form.with_child(
|
if config::user_theme_applies() {
|
||||||
form::SelectTheme::new()
|
form = form.with_child(
|
||||||
.with_name("theme")
|
form::SelectTheme::new()
|
||||||
.with_label(Lc::t("field-theme", &LOCALES_USER))
|
.with_name("theme")
|
||||||
.with_disabled(managed(UserField::Theme))
|
.with_label(Lc::t("field-theme", &LOCALES_USER))
|
||||||
.with_selected(self.theme()),
|
.with_disabled(managed(UserField::Theme))
|
||||||
);
|
.with_selected(self.theme()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
match (self.mode(), self.provider()) {
|
match (self.mode(), self.provider()) {
|
||||||
// Una cuenta que entrará con un proveedor no tiene contraseña local.
|
// Una cuenta que entrará con un proveedor no tiene contraseña local.
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
use crate::component::error_banner;
|
use crate::component::error_banner;
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::provider::{self, HelpLink, ResetLink};
|
use crate::provider::{self, HelpLink, ResetLink};
|
||||||
use crate::{LOCALES_USER, LOGIN_PATH, PASSWORD_RESET_PATH, REGISTER_PATH};
|
use crate::{LOCALES_USER, LOGIN_PATH, PASSWORD_RESET_PATH, REGISTER_PATH};
|
||||||
|
|
||||||
|
|
@ -35,7 +35,7 @@ impl Component for LoginForm {
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
let action = self.waypoint().append_to(cx.route(LOGIN_PATH));
|
let action = self.waypoint().append_to(cx.route(LOGIN_PATH));
|
||||||
let strict = SETTINGS.login.strict;
|
let strict = config::SETTINGS.login.strict;
|
||||||
let (notes, reset) = provider::login_hints();
|
let (notes, reset) = provider::login_hints();
|
||||||
|
|
||||||
// En modo estricto se dificulta que el navegador recuerde o autorrellene las
|
// En modo estricto se dificulta que el navegador recuerde o autorrellene las
|
||||||
|
|
@ -83,7 +83,7 @@ impl Component for LoginForm {
|
||||||
Button::submit(Lc::t("btn-login", &LOCALES_USER))
|
Button::submit(Lc::t("btn-login", &LOCALES_USER))
|
||||||
.with_style(button::Style::Solid(Intent::Primary)),
|
.with_style(button::Style::Solid(Intent::Primary)),
|
||||||
)
|
)
|
||||||
.with_child(links(SETTINGS.allow_registration, notes, reset));
|
.with_child(links(config::SETTINGS.allow_registration, notes, reset));
|
||||||
|
|
||||||
if strict {
|
if strict {
|
||||||
form = form
|
form = form
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
use crate::LOCALES_USER;
|
use crate::LOCALES_USER;
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
|
|
||||||
/// Campos de contraseña y confirmación, compuestos a partir de
|
/// Campos de contraseña y confirmación, compuestos a partir de
|
||||||
/// [`form::input::Field::password()`] del core. No valida en ningún momento que ambos valores
|
/// [`form::input::Field::password()`] del core. No valida en ningún momento que ambos valores
|
||||||
|
|
@ -35,7 +35,7 @@ impl Component for PasswordConfirm {
|
||||||
// `minlength` cuenta unidades UTF-16 y el servidor caracteres: con caracteres fuera del
|
// `minlength` cuenta unidades UTF-16 y el servidor caracteres: con caracteres fuera del
|
||||||
// plano básico (emojis) el navegador puede aceptar una contraseña que el servidor rechaza,
|
// plano básico (emojis) el navegador puede aceptar una contraseña que el servidor rechaza,
|
||||||
// pero nunca al revés.
|
// pero nunca al revés.
|
||||||
let min_length = SETTINGS.password.min_length;
|
let min_length = config::SETTINGS.password.min_length;
|
||||||
let mut password = form::input::Field::password()
|
let mut password = form::input::Field::password()
|
||||||
.with_name("password")
|
.with_name("password")
|
||||||
.with_label(self.password_label().clone())
|
.with_label(self.password_label().clone())
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,7 @@ use pagetop::prelude::*;
|
||||||
use crate::LOCALES_USER;
|
use crate::LOCALES_USER;
|
||||||
use crate::REGISTER_PATH;
|
use crate::REGISTER_PATH;
|
||||||
use crate::component::{PasswordConfirm, error_banner};
|
use crate::component::{PasswordConfirm, error_banner};
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::identity::{EMAIL_MAX_CHARS, USERNAME_MIN_CHARS, username_help, username_max_chars};
|
use crate::identity::{EMAIL_MAX_CHARS, USERNAME_MIN_CHARS, username_help, username_max_chars};
|
||||||
|
|
||||||
/// Formulario de registro de una cuenta nueva.
|
/// Formulario de registro de una cuenta nueva.
|
||||||
|
|
@ -37,9 +37,9 @@ impl Component for RegisterForm {
|
||||||
.with_name("username")
|
.with_name("username")
|
||||||
.with_value(&self.username)
|
.with_value(&self.username)
|
||||||
.with_label(Lc::t("field-username-admin", &LOCALES_USER))
|
.with_label(Lc::t("field-username-admin", &LOCALES_USER))
|
||||||
.with_help_text(username_help(SETTINGS.identity_policy))
|
.with_help_text(username_help(config::SETTINGS.identity_policy))
|
||||||
.with_minlength(USERNAME_MIN_CHARS)
|
.with_minlength(USERNAME_MIN_CHARS)
|
||||||
.with_maxlength(username_max_chars(SETTINGS.identity_policy))
|
.with_maxlength(username_max_chars(config::SETTINGS.identity_policy))
|
||||||
.with_autocomplete(Some(form::Autocomplete::username()))
|
.with_autocomplete(Some(form::Autocomplete::username()))
|
||||||
.with_autofocus(true)
|
.with_autofocus(true)
|
||||||
.with_required(true),
|
.with_required(true),
|
||||||
|
|
|
||||||
|
|
@ -427,6 +427,12 @@ pub(crate) fn user_timezone_applies() -> bool {
|
||||||
global::SETTINGS.app.timezone_per_user
|
global::SETTINGS.app.timezone_per_user
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Si se aplica el tema propio del usuario (`app.theme_per_user`). Si no se aplica, no se ofrece
|
||||||
|
// elegirlo ni se borra el guardado.
|
||||||
|
pub(crate) fn user_theme_applies() -> bool {
|
||||||
|
global::SETTINGS.app.theme_per_user
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{UserSettings, config};
|
use super::{UserSettings, config};
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ use pagetop::prelude::*;
|
||||||
use pagetop_seaorm::db::*;
|
use pagetop_seaorm::db::*;
|
||||||
|
|
||||||
use crate::account::UserStatus;
|
use crate::account::UserStatus;
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::entity::{role, user, user_role};
|
use crate::entity::{role, user, user_role};
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
use crate::identity;
|
use crate::identity;
|
||||||
|
|
@ -91,8 +91,11 @@ async fn create_demo_users(
|
||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
|
|
||||||
for n in 1..=USER_COUNT {
|
for n in 1..=USER_COUNT {
|
||||||
let username =
|
let username = identity::username(
|
||||||
identity::username(&format!("demo_user_{n:02}"), SETTINGS.identity_policy, None)?;
|
&format!("demo_user_{n:02}"),
|
||||||
|
config::SETTINGS.identity_policy,
|
||||||
|
None,
|
||||||
|
)?;
|
||||||
let email = identity::email(&format!("demo_user_{n:02}@example.com"))?;
|
let email = identity::email(&format!("demo_user_{n:02}@example.com"))?;
|
||||||
let mut new_user = user::ActiveModel {
|
let mut new_user = user::ActiveModel {
|
||||||
id: ActiveValue::NotSet,
|
id: ActiveValue::NotSet,
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ use crate::LOCALES_USER;
|
||||||
use crate::component::admin::{
|
use crate::component::admin::{
|
||||||
PermissionGroups, RoleForm, RoleFormMode, RolePermissionsForm, RoleTable, delete_dialog,
|
PermissionGroups, RoleForm, RoleFormMode, RolePermissionsForm, RoleTable, delete_dialog,
|
||||||
};
|
};
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::entity::role;
|
use crate::entity::role;
|
||||||
use crate::handlers::admin::{back_link, map_auth_error};
|
use crate::handlers::admin::{back_link, map_auth_error};
|
||||||
use crate::permission::UserPermission;
|
use crate::permission::UserPermission;
|
||||||
|
|
@ -38,7 +38,7 @@ pub(crate) async fn list_get(
|
||||||
sort: RoleSortField::from_query(query.sort.as_deref()),
|
sort: RoleSortField::from_query(query.sort.as_deref()),
|
||||||
dir: SortDir::from_query(query.dir.as_deref()),
|
dir: SortDir::from_query(query.dir.as_deref()),
|
||||||
page: query.page.unwrap_or(1).max(1),
|
page: query.page.unwrap_or(1).max(1),
|
||||||
per_page: SETTINGS.admin.list_page_size,
|
per_page: config::SETTINGS.admin.list_page_size,
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = match role_admin::list_roles_page(¶ms).await {
|
let result = match role_admin::list_roles_page(¶ms).await {
|
||||||
|
|
@ -350,7 +350,7 @@ pub(crate) async fn delete_post(
|
||||||
sort: RoleSortField::from_query(query.sort.as_deref()),
|
sort: RoleSortField::from_query(query.sort.as_deref()),
|
||||||
dir: SortDir::from_query(query.dir.as_deref()),
|
dir: SortDir::from_query(query.dir.as_deref()),
|
||||||
page: query.page.unwrap_or(1).max(1),
|
page: query.page.unwrap_or(1).max(1),
|
||||||
per_page: SETTINGS.admin.list_page_size,
|
per_page: config::SETTINGS.admin.list_page_size,
|
||||||
};
|
};
|
||||||
let page_result = role_admin::list_roles_page(¶ms)
|
let page_result = role_admin::list_roles_page(¶ms)
|
||||||
.await
|
.await
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ use crate::component::admin::{
|
||||||
AdminPasswordForm, USER_ADMIN_FORM_ID, UserForm, UserFormMode, UserTable,
|
AdminPasswordForm, USER_ADMIN_FORM_ID, UserForm, UserFormMode, UserTable,
|
||||||
};
|
};
|
||||||
use crate::component::{cancel_link, user_details};
|
use crate::component::{cancel_link, user_details};
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::entity::{role, user};
|
use crate::entity::{role, user};
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
use crate::handlers::account::managed_or;
|
use crate::handlers::account::managed_or;
|
||||||
|
|
@ -51,7 +51,7 @@ pub(crate) async fn list_get(
|
||||||
sort: UserSortField::from_query(query.sort.as_deref()),
|
sort: UserSortField::from_query(query.sort.as_deref()),
|
||||||
dir: SortDir::from_query(query.dir.as_deref()),
|
dir: SortDir::from_query(query.dir.as_deref()),
|
||||||
page: query.page.unwrap_or(1).max(1),
|
page: query.page.unwrap_or(1).max(1),
|
||||||
per_page: SETTINGS.admin.list_page_size,
|
per_page: config::SETTINGS.admin.list_page_size,
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = match user_admin::list_users(¶ms).await {
|
let result = match user_admin::list_users(¶ms).await {
|
||||||
|
|
@ -408,9 +408,10 @@ struct EditActions {
|
||||||
linking: Vec<(&'static str, Lc, bool)>,
|
linking: Vec<(&'static str, Lc, bool)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Botonera de la edición: "Guardar", "Cancelar", el enlace a la pantalla de restablecer contraseña
|
// Botonera de la edición: el enlace a la pantalla de restablecer contraseña, los botones de
|
||||||
// y los botones de bloqueo/activación (sólo si `can_change_status`) y de concesión/revocación de
|
// bloqueo/activación (sólo si `can_change_status`), de vinculación con proveedores y de
|
||||||
// acceso total (sólo si `can_toggle_admin`).
|
// concesión/revocación de acceso total (sólo si `can_toggle_admin`) y, al final, "Guardar" y
|
||||||
|
// "Cancelar", que cierran el formulario como en el resto de formularios.
|
||||||
//
|
//
|
||||||
// "Guardar" (envía el `<form>` de `UserForm` vía el atributo `form`, ver `USER_ADMIN_FORM_ID`),
|
// "Guardar" (envía el `<form>` de `UserForm` vía el atributo `form`, ver `USER_ADMIN_FORM_ID`),
|
||||||
// "Cancelar" y "Restablecer contraseña" son botones sueltos; bloqueo/activación y
|
// "Cancelar" y "Restablecer contraseña" son botones sueltos; bloqueo/activación y
|
||||||
|
|
@ -442,7 +443,7 @@ fn edit_actions(user_id: i32, state: EditActions, cx: &mut Context) -> Flex {
|
||||||
.with_child(form::Hidden::field("status", next_status))
|
.with_child(form::Hidden::field("status", next_status))
|
||||||
.with_child(
|
.with_child(
|
||||||
Button::submit(Lc::t(label_key, &LOCALES_USER))
|
Button::submit(Lc::t(label_key, &LOCALES_USER))
|
||||||
.with_style(button::Style::Solid(Intent::Warning)),
|
.with_style(button::Style::Solid(Intent::Neutral)),
|
||||||
);
|
);
|
||||||
if let Some(confirm) = Lc::t("confirm-change-status", &LOCALES_USER).lookup(cx) {
|
if let Some(confirm) = Lc::t("confirm-change-status", &LOCALES_USER).lookup(cx) {
|
||||||
status_form = status_form.with_prop(PropsOp::set(hx::CONFIRM, confirm));
|
status_form = status_form.with_prop(PropsOp::set(hx::CONFIRM, confirm));
|
||||||
|
|
@ -451,13 +452,7 @@ fn edit_actions(user_id: i32, state: EditActions, cx: &mut Context) -> Flex {
|
||||||
let mut container = Flex::new()
|
let mut container = Flex::new()
|
||||||
.with_wrap(flex::Behavior::Wrap)
|
.with_wrap(flex::Behavior::Wrap)
|
||||||
.with_align(align::Items::Center)
|
.with_align(align::Items::Center)
|
||||||
.with_gap(align::Gap::Both(UnitValue::RelRem(0.5)))
|
.with_gap(align::Gap::Both(UnitValue::RelRem(0.5)));
|
||||||
.with_child(
|
|
||||||
Button::submit(Lc::t("btn-save", &LOCALES_USER))
|
|
||||||
.with_style(button::Style::Solid(Intent::Primary))
|
|
||||||
.with_prop(PropsOp::set("form", USER_ADMIN_FORM_ID)),
|
|
||||||
)
|
|
||||||
.with_child(cancel_link(cx.route(ADMIN_USERS_PATH.as_str())));
|
|
||||||
if state.can_reset_password {
|
if state.can_reset_password {
|
||||||
container = container.with_child(
|
container = container.with_child(
|
||||||
Button::anchor(Lc::t("btn-reset-password", &LOCALES_USER), password_href)
|
Button::anchor(Lc::t("btn-reset-password", &LOCALES_USER), password_href)
|
||||||
|
|
@ -505,6 +500,12 @@ fn edit_actions(user_id: i32, state: EditActions, cx: &mut Context) -> Flex {
|
||||||
}
|
}
|
||||||
|
|
||||||
container
|
container
|
||||||
|
.with_child(
|
||||||
|
Button::submit(Lc::t("btn-save", &LOCALES_USER))
|
||||||
|
.with_style(button::Style::Solid(Intent::Primary))
|
||||||
|
.with_prop(PropsOp::set("form", USER_ADMIN_FORM_ID)),
|
||||||
|
)
|
||||||
|
.with_child(cancel_link(cx.route(ADMIN_USERS_PATH.as_str())))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// GET /admin/user/users/{id}/edit - Formulario de edición de usuario.
|
/// GET /admin/user/users/{id}/edit - Formulario de edición de usuario.
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ use pagetop_htmx::prelude::*;
|
||||||
|
|
||||||
use crate::auth;
|
use crate::auth;
|
||||||
use crate::component::{LoginForm, PasswordResetConfirmForm, PasswordResetForm, RegisterForm};
|
use crate::component::{LoginForm, PasswordResetConfirmForm, PasswordResetForm, RegisterForm};
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
use crate::handlers::admin::map_auth_error;
|
use crate::handlers::admin::map_auth_error;
|
||||||
use crate::handlers::{confirm_page, message_page, no_referrer};
|
use crate::handlers::{confirm_page, message_page, no_referrer};
|
||||||
|
|
@ -195,7 +195,7 @@ pub async fn logout_post(request: HttpRequest) -> Response {
|
||||||
|
|
||||||
/// GET /user/register - Formulario de registro de cuenta.
|
/// GET /user/register - Formulario de registro de cuenta.
|
||||||
pub async fn register_get(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
pub async fn register_get(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
if !SETTINGS.allow_registration {
|
if !config::SETTINGS.allow_registration {
|
||||||
return Err(ErrorPage::NotFound(request));
|
return Err(ErrorPage::NotFound(request));
|
||||||
}
|
}
|
||||||
Page::new(request)
|
Page::new(request)
|
||||||
|
|
@ -212,7 +212,7 @@ pub async fn register_post(
|
||||||
request: HttpRequest,
|
request: HttpRequest,
|
||||||
web::Form(form): web::Form<RegisterFormData>,
|
web::Form(form): web::Form<RegisterFormData>,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
if !SETTINGS.allow_registration {
|
if !config::SETTINGS.allow_registration {
|
||||||
return ErrorPage::NotFound(request).into_response();
|
return ErrorPage::NotFound(request).into_response();
|
||||||
}
|
}
|
||||||
let cx = Context::new(request.clone());
|
let cx = Context::new(request.clone());
|
||||||
|
|
@ -228,7 +228,7 @@ pub async fn register_post(
|
||||||
Err(AuthError::TooManyRequests)
|
Err(AuthError::TooManyRequests)
|
||||||
};
|
};
|
||||||
match result {
|
match result {
|
||||||
Ok(user_id) if SETTINGS.require_email_verification => {
|
Ok(user_id) if config::SETTINGS.require_email_verification => {
|
||||||
send_verification_mail(&request, user_id).await;
|
send_verification_mail(&request, user_id).await;
|
||||||
let title = Lc::t("title-register", &LOCALES_USER);
|
let title = Lc::t("title-register", &LOCALES_USER);
|
||||||
message_page(
|
message_page(
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
//! Nombre de usuario y email que identifican una cuenta: normalización y validación.
|
//! Nombre de usuario y email que identifican una cuenta: normalización y validación.
|
||||||
//!
|
//!
|
||||||
//! Las reglas públicas se documentan en `IdentityPolicy`. Aquí se separan dos cosas:
|
//! Las reglas públicas se documentan en `config::IdentityPolicy`. Aquí se separan dos cosas:
|
||||||
//!
|
//!
|
||||||
//! - **Buscar y comparar**, igual con cualquier política: `*_key` (sin espacios en los extremos,
|
//! - **Buscar y comparar**, igual con cualquier política: `*_key` (sin espacios en los extremos,
|
||||||
//! NFKC en el nombre de usuario y en minúsculas) y el esqueleto de confusión del nombre
|
//! NFKC en el nombre de usuario y en minúsculas) y el esqueleto de confusión del nombre
|
||||||
|
|
@ -23,7 +23,7 @@ use unicode_security::{GeneralSecurityProfile, MixedScript, skeleton};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
use crate::LOCALES_USER;
|
use crate::LOCALES_USER;
|
||||||
use crate::config::IdentityPolicy;
|
use crate::config;
|
||||||
use crate::entity::user;
|
use crate::entity::user;
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
|
|
||||||
|
|
@ -35,10 +35,10 @@ pub(crate) const USERNAME_MIN_CHARS: u16 = 3;
|
||||||
pub(crate) const EMAIL_MAX_CHARS: u16 = 254;
|
pub(crate) const EMAIL_MAX_CHARS: u16 = 254;
|
||||||
|
|
||||||
// Longitud máxima del nombre de usuario según la política. La de `Permissive` es la de Drupal.
|
// Longitud máxima del nombre de usuario según la política. La de `Permissive` es la de Drupal.
|
||||||
pub(crate) fn username_max_chars(policy: IdentityPolicy) -> u16 {
|
pub(crate) fn username_max_chars(policy: config::IdentityPolicy) -> u16 {
|
||||||
match policy {
|
match policy {
|
||||||
IdentityPolicy::Strict | IdentityPolicy::Unicode => 32,
|
config::IdentityPolicy::Strict | config::IdentityPolicy::Unicode => 32,
|
||||||
IdentityPolicy::Permissive => 60,
|
config::IdentityPolicy::Permissive => 60,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -69,7 +69,7 @@ impl Username {
|
||||||
// más abierta pueda seguir guardando su perfil.
|
// más abierta pueda seguir guardando su perfil.
|
||||||
pub(crate) fn username(
|
pub(crate) fn username(
|
||||||
raw: &str,
|
raw: &str,
|
||||||
policy: IdentityPolicy,
|
policy: config::IdentityPolicy,
|
||||||
current_key: Option<&str>,
|
current_key: Option<&str>,
|
||||||
) -> Result<Username, AuthError> {
|
) -> Result<Username, AuthError> {
|
||||||
let value = raw.trim().nfkc().collect::<String>();
|
let value = raw.trim().nfkc().collect::<String>();
|
||||||
|
|
@ -119,10 +119,10 @@ fn skeleton_hash(key: &str) -> String {
|
||||||
// clases que definen los identificadores de Rust (XID, UAX #31), que incluyen las marcas
|
// clases que definen los identificadores de Rust (XID, UAX #31), que incluyen las marcas
|
||||||
// combinables de escrituras como el devanagari; `identifier_allowed()` descarta los caracteres
|
// combinables de escrituras como el devanagari; `identifier_allowed()` descarta los caracteres
|
||||||
// que UTS #39 desaconseja (invisibles, obsoletos...) y `is_single_script()` la mezcla de alfabetos.
|
// que UTS #39 desaconseja (invisibles, obsoletos...) y `is_single_script()` la mezcla de alfabetos.
|
||||||
fn accepts(name: &str, policy: IdentityPolicy) -> bool {
|
fn accepts(name: &str, policy: config::IdentityPolicy) -> bool {
|
||||||
let symbols: &[char] = match policy {
|
let symbols: &[char] = match policy {
|
||||||
IdentityPolicy::Strict | IdentityPolicy::Unicode => &['.', '_', '-'],
|
config::IdentityPolicy::Strict | config::IdentityPolicy::Unicode => &['.', '_', '-'],
|
||||||
IdentityPolicy::Permissive => &['.', '_', '-', ' ', '\'', '+'],
|
config::IdentityPolicy::Permissive => &['.', '_', '-', ' ', '\'', '+'],
|
||||||
};
|
};
|
||||||
let length = usize::from(USERNAME_MIN_CHARS)..=usize::from(username_max_chars(policy));
|
let length = usize::from(USERNAME_MIN_CHARS)..=usize::from(username_max_chars(policy));
|
||||||
if !length.contains(&name.chars().count()) {
|
if !length.contains(&name.chars().count()) {
|
||||||
|
|
@ -132,13 +132,13 @@ fn accepts(name: &str, policy: IdentityPolicy) -> bool {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
match policy {
|
match policy {
|
||||||
IdentityPolicy::Strict => {
|
config::IdentityPolicy::Strict => {
|
||||||
first.is_ascii_alphanumeric()
|
first.is_ascii_alphanumeric()
|
||||||
&& name
|
&& name
|
||||||
.chars()
|
.chars()
|
||||||
.all(|c| c.is_ascii_alphanumeric() || symbols.contains(&c))
|
.all(|c| c.is_ascii_alphanumeric() || symbols.contains(&c))
|
||||||
}
|
}
|
||||||
IdentityPolicy::Unicode | IdentityPolicy::Permissive => {
|
config::IdentityPolicy::Unicode | config::IdentityPolicy::Permissive => {
|
||||||
let letter_or_digit = |c: char| {
|
let letter_or_digit = |c: char| {
|
||||||
c.identifier_allowed()
|
c.identifier_allowed()
|
||||||
&& (is_xid_start(c) || (is_xid_continue(c) && c.is_numeric()))
|
&& (is_xid_start(c) || (is_xid_continue(c) && c.is_numeric()))
|
||||||
|
|
@ -196,11 +196,11 @@ pub(crate) fn email_key(raw: &str) -> String {
|
||||||
// **< Textos >*************************************************************************************
|
// **< Textos >*************************************************************************************
|
||||||
|
|
||||||
// Reglas del nombre de usuario de la política, como texto de ayuda de los formularios.
|
// Reglas del nombre de usuario de la política, como texto de ayuda de los formularios.
|
||||||
pub(crate) fn username_help(policy: IdentityPolicy) -> Lc {
|
pub(crate) fn username_help(policy: config::IdentityPolicy) -> Lc {
|
||||||
let key = match policy {
|
let key = match policy {
|
||||||
IdentityPolicy::Strict => "help-username-strict",
|
config::IdentityPolicy::Strict => "help-username-strict",
|
||||||
IdentityPolicy::Unicode => "help-username-unicode",
|
config::IdentityPolicy::Unicode => "help-username-unicode",
|
||||||
IdentityPolicy::Permissive => "help-username-permissive",
|
config::IdentityPolicy::Permissive => "help-username-permissive",
|
||||||
};
|
};
|
||||||
Lc::t(key, &LOCALES_USER)
|
Lc::t(key, &LOCALES_USER)
|
||||||
.with_number("min", u32::from(USERNAME_MIN_CHARS))
|
.with_number("min", u32::from(USERNAME_MIN_CHARS))
|
||||||
|
|
@ -211,14 +211,18 @@ pub(crate) fn username_help(policy: IdentityPolicy) -> Lc {
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
fn accepted(raw: &str, policy: IdentityPolicy) -> bool {
|
fn accepted(raw: &str, policy: config::IdentityPolicy) -> bool {
|
||||||
username(raw, policy, None).is_ok()
|
username(raw, policy, None).is_ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn skeleton_of(raw: &str) -> String {
|
fn skeleton_of(raw: &str) -> String {
|
||||||
username(raw, IdentityPolicy::Permissive, Some(&username_key(raw)))
|
username(
|
||||||
.unwrap()
|
raw,
|
||||||
.skeleton
|
config::IdentityPolicy::Permissive,
|
||||||
|
Some(&username_key(raw)),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
.skeleton
|
||||||
}
|
}
|
||||||
|
|
||||||
const ALWAYS_REJECTED: &[&str] = &[
|
const ALWAYS_REJECTED: &[&str] = &[
|
||||||
|
|
@ -234,13 +238,13 @@ mod tests {
|
||||||
|
|
||||||
#[pagetop::test]
|
#[pagetop::test]
|
||||||
async fn strict_accepts_only_ascii_identifiers() {
|
async fn strict_accepts_only_ascii_identifiers() {
|
||||||
let name = username(" Ana.Perez_01 ", IdentityPolicy::Strict, None).unwrap();
|
let name = username(" Ana.Perez_01 ", config::IdentityPolicy::Strict, None).unwrap();
|
||||||
assert_eq!(name.value, "Ana.Perez_01", "the value keeps its case");
|
assert_eq!(name.value, "Ana.Perez_01", "the value keeps its case");
|
||||||
assert_eq!(name.key, "ana.perez_01");
|
assert_eq!(name.key, "ana.perez_01");
|
||||||
assert!(accepted("a-b", IdentityPolicy::Strict));
|
assert!(accepted("a-b", config::IdentityPolicy::Strict));
|
||||||
// Full-width letters are normalized to ASCII (NFKC).
|
// Full-width letters are normalized to ASCII (NFKC).
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
username("Ana", IdentityPolicy::Strict, None)
|
username("Ana", config::IdentityPolicy::Strict, None)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.value,
|
.value,
|
||||||
"Ana"
|
"Ana"
|
||||||
|
|
@ -253,7 +257,7 @@ mod tests {
|
||||||
.chain(["peña", "аna", "ana perez", too_long.as_str()])
|
.chain(["peña", "аna", "ana perez", too_long.as_str()])
|
||||||
{
|
{
|
||||||
assert!(
|
assert!(
|
||||||
!accepted(name, IdentityPolicy::Strict),
|
!accepted(name, config::IdentityPolicy::Strict),
|
||||||
"{name:?} must be rejected"
|
"{name:?} must be rejected"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -274,7 +278,7 @@ mod tests {
|
||||||
"ana_01",
|
"ana_01",
|
||||||
] {
|
] {
|
||||||
assert!(
|
assert!(
|
||||||
accepted(name, IdentityPolicy::Unicode),
|
accepted(name, config::IdentityPolicy::Unicode),
|
||||||
"{name:?} must be accepted"
|
"{name:?} must be accepted"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -288,7 +292,7 @@ mod tests {
|
||||||
too_long.as_str(),
|
too_long.as_str(),
|
||||||
]) {
|
]) {
|
||||||
assert!(
|
assert!(
|
||||||
!accepted(name, IdentityPolicy::Unicode),
|
!accepted(name, config::IdentityPolicy::Unicode),
|
||||||
"{name:?} must be rejected"
|
"{name:?} must be rejected"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -298,7 +302,7 @@ mod tests {
|
||||||
async fn permissive_adds_spaces_apostrophes_and_plus() {
|
async fn permissive_adds_spaces_apostrophes_and_plus() {
|
||||||
for name in ["Ana Pérez", "O'Brien", "ana+test", "José María"] {
|
for name in ["Ana Pérez", "O'Brien", "ana+test", "José María"] {
|
||||||
assert!(
|
assert!(
|
||||||
accepted(name, IdentityPolicy::Permissive),
|
accepted(name, config::IdentityPolicy::Permissive),
|
||||||
"{name:?} must be accepted"
|
"{name:?} must be accepted"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -310,7 +314,7 @@ mod tests {
|
||||||
.chain(["ana perez", "pаypal", too_long.as_str()])
|
.chain(["ana perez", "pаypal", too_long.as_str()])
|
||||||
{
|
{
|
||||||
assert!(
|
assert!(
|
||||||
!accepted(name, IdentityPolicy::Permissive),
|
!accepted(name, config::IdentityPolicy::Permissive),
|
||||||
"{name:?} must be rejected"
|
"{name:?} must be rejected"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -328,7 +332,7 @@ mod tests {
|
||||||
// the column, whatever the name.
|
// the column, whatever the name.
|
||||||
#[pagetop::test]
|
#[pagetop::test]
|
||||||
async fn longest_names_fit_their_columns() {
|
async fn longest_names_fit_their_columns() {
|
||||||
let name = username(&"꽦".repeat(60), IdentityPolicy::Permissive, None).unwrap();
|
let name = username(&"꽦".repeat(60), config::IdentityPolicy::Permissive, None).unwrap();
|
||||||
assert_eq!(name.skeleton.len(), 64);
|
assert_eq!(name.skeleton.len(), 64);
|
||||||
assert!(name.key.chars().count() <= 255);
|
assert!(name.key.chars().count() <= 255);
|
||||||
}
|
}
|
||||||
|
|
@ -336,8 +340,8 @@ mod tests {
|
||||||
#[pagetop::test]
|
#[pagetop::test]
|
||||||
async fn unchanged_names_skip_the_policy() {
|
async fn unchanged_names_skip_the_policy() {
|
||||||
let current = username_key("Ana Pérez");
|
let current = username_key("Ana Pérez");
|
||||||
assert!(username("ana pérez", IdentityPolicy::Strict, Some(¤t)).is_ok());
|
assert!(username("ana pérez", config::IdentityPolicy::Strict, Some(¤t)).is_ok());
|
||||||
assert!(username("Eva Pérez", IdentityPolicy::Strict, Some(¤t)).is_err());
|
assert!(username("Eva Pérez", config::IdentityPolicy::Strict, Some(¤t)).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[pagetop::test]
|
#[pagetop::test]
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,7 @@ use pagetop::prelude::*;
|
||||||
|
|
||||||
use crate::account::{Account, PermissionSet};
|
use crate::account::{Account, PermissionSet};
|
||||||
use crate::actions::AfterSessionResolved;
|
use crate::actions::AfterSessionResolved;
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::session;
|
use crate::session;
|
||||||
|
|
||||||
// Permisos del rol "anonymous", insertados en las peticiones sin sesión. Un tipo propio para que no
|
// Permisos del rol "anonymous", insertados en las peticiones sin sesión. Un tipo propio para que no
|
||||||
|
|
@ -62,7 +62,7 @@ pub(crate) async fn session_middleware(
|
||||||
// sesión). Las demás (mensajes, estado de un listado) conviven con la renovación: si la
|
// sesión). Las demás (mensajes, estado de un listado) conviven con la renovación: si la
|
||||||
// impidieran, la cookie caducaría en el navegador antes que la sesión.
|
// impidieran, la cookie caducaría en el navegador antes que la sesión.
|
||||||
if let Some(cookie) = renewed_cookie
|
if let Some(cookie) = renewed_cookie
|
||||||
&& !sets_cookie(response.headers(), &SETTINGS.session.cookie_name)
|
&& !sets_cookie(response.headers(), &config::SETTINGS.session.cookie_name)
|
||||||
{
|
{
|
||||||
match web::http::HeaderValue::try_from(cookie) {
|
match web::http::HeaderValue::try_from(cookie) {
|
||||||
Ok(value) => {
|
Ok(value) => {
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ use rand_core::OsRng;
|
||||||
|
|
||||||
use std::sync::LazyLock;
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
|
|
||||||
// Lo que se guarda como contraseña de una cuenta sin contraseña local (las que gestiona un
|
// Lo que se guarda como contraseña de una cuenta sin contraseña local (las que gestiona un
|
||||||
|
|
@ -22,9 +22,9 @@ pub(crate) const UNUSABLE_HASH: &str = "!external";
|
||||||
/// Genera el hash PHC de una contraseña usando Argon2id con los parámetros configurados.
|
/// Genera el hash PHC de una contraseña usando Argon2id con los parámetros configurados.
|
||||||
pub fn hash_password(plain: &str) -> Result<String, AuthError> {
|
pub fn hash_password(plain: &str) -> Result<String, AuthError> {
|
||||||
let params = ParamsBuilder::new()
|
let params = ParamsBuilder::new()
|
||||||
.m_cost(SETTINGS.password.argon2_m_cost)
|
.m_cost(config::SETTINGS.password.argon2_m_cost)
|
||||||
.t_cost(SETTINGS.password.argon2_t_cost)
|
.t_cost(config::SETTINGS.password.argon2_t_cost)
|
||||||
.p_cost(SETTINGS.password.argon2_p_cost)
|
.p_cost(config::SETTINGS.password.argon2_p_cost)
|
||||||
.build()
|
.build()
|
||||||
.map_err(|e| AuthError::PasswordHash(e.to_string()))?;
|
.map_err(|e| AuthError::PasswordHash(e.to_string()))?;
|
||||||
|
|
||||||
|
|
@ -85,7 +85,7 @@ pub fn needs_rehash(phc: &str) -> bool {
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
let cost = |name: &str| parsed.params.get_decimal(name);
|
let cost = |name: &str| parsed.params.get_decimal(name);
|
||||||
let password = &SETTINGS.password;
|
let password = &config::SETTINGS.password;
|
||||||
parsed.algorithm != argon2::Algorithm::Argon2id.ident()
|
parsed.algorithm != argon2::Algorithm::Argon2id.ident()
|
||||||
|| cost("m") != Some(password.argon2_m_cost)
|
|| cost("m") != Some(password.argon2_m_cost)
|
||||||
|| cost("t") != Some(password.argon2_t_cost)
|
|| cost("t") != Some(password.argon2_t_cost)
|
||||||
|
|
@ -94,7 +94,7 @@ pub fn needs_rehash(phc: &str) -> bool {
|
||||||
|
|
||||||
/// Valida la longitud mínima, en caracteres, y devuelve error si no se cumple.
|
/// Valida la longitud mínima, en caracteres, y devuelve error si no se cumple.
|
||||||
pub fn validate_strength(plain: &str) -> Result<(), AuthError> {
|
pub fn validate_strength(plain: &str) -> Result<(), AuthError> {
|
||||||
let min = SETTINGS.password.min_length;
|
let min = config::SETTINGS.password.min_length;
|
||||||
if plain.chars().count() < min {
|
if plain.chars().count() < min {
|
||||||
Err(AuthError::PasswordTooShort(min))
|
Err(AuthError::PasswordTooShort(min))
|
||||||
} else {
|
} else {
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,7 @@ use pagetop::prelude::*;
|
||||||
use pagetop_seaorm::db::{ColumnTrait, EntityTrait, QueryFilter, dbconn};
|
use pagetop_seaorm::db::{ColumnTrait, EntityTrait, QueryFilter, dbconn};
|
||||||
|
|
||||||
use crate::account::UserStatus;
|
use crate::account::UserStatus;
|
||||||
use crate::config::{LocalFallback, SETTINGS};
|
use crate::config;
|
||||||
use crate::entity::{user, user_identity};
|
use crate::entity::{user, user_identity};
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
|
|
||||||
|
|
@ -240,8 +240,8 @@ pub trait AuthProvider: Send + Sync + 'static {
|
||||||
///
|
///
|
||||||
/// Una cuenta liberada se trata como local:
|
/// Una cuenta liberada se trata como local:
|
||||||
///
|
///
|
||||||
/// - **Al iniciar sesión**, con [`LocalFallback::Released`], puede entrar con su contraseña
|
/// - **Al iniciar sesión**, con [`config::LocalFallback::Released`], puede entrar con su
|
||||||
/// local aunque `"local"` no esté en `sources`.
|
/// contraseña local aunque `"local"` no esté en `sources`.
|
||||||
/// - **Al confirmar una operación sensible** (cambiar el email o la contraseña), se comprueba
|
/// - **Al confirmar una operación sensible** (cambiar el email o la contraseña), se comprueba
|
||||||
/// su contraseña local en lugar de llamar a [`reauthenticate()`](Self::reauthenticate).
|
/// su contraseña local en lugar de llamar a [`reauthenticate()`](Self::reauthenticate).
|
||||||
///
|
///
|
||||||
|
|
@ -417,7 +417,7 @@ pub(crate) fn initialize() -> Result<(), AuthError> {
|
||||||
}
|
}
|
||||||
let mut declared = AuthProviders::default();
|
let mut declared = AuthProviders::default();
|
||||||
dispatch_actions(|action: &DeclareAuthProviders| (action.f)(&mut declared));
|
dispatch_actions(|action: &DeclareAuthProviders| (action.f)(&mut declared));
|
||||||
let sources = resolve_sources(&SETTINGS.login.sources, &declared.providers)?;
|
let sources = resolve_sources(&config::SETTINGS.login.sources, &declared.providers)?;
|
||||||
|
|
||||||
for provider in &declared.providers {
|
for provider in &declared.providers {
|
||||||
if !sources
|
if !sources
|
||||||
|
|
@ -432,7 +432,7 @@ pub(crate) fn initialize() -> Result<(), AuthError> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let has_providers = sources.iter().any(|s| matches!(s, Source::Provider(_)));
|
let has_providers = sources.iter().any(|s| matches!(s, Source::Provider(_)));
|
||||||
if has_providers && SETTINGS.allow_registration {
|
if has_providers && config::SETTINGS.allow_registration {
|
||||||
trace::warn!(
|
trace::warn!(
|
||||||
"Local registration is open (user.allow_registration) while an authentication \
|
"Local registration is open (user.allow_registration) while an authentication \
|
||||||
provider is active: anyone can create a local account, and a name taken here can \
|
provider is active: anyone can create a local account, and a name taken here can \
|
||||||
|
|
@ -503,15 +503,15 @@ pub(crate) fn local_is_source() -> bool {
|
||||||
// cuenta que algún proveedor libera (`released`) con `Released` o `Admins`.
|
// cuenta que algún proveedor libera (`released`) con `Released` o `Admins`.
|
||||||
pub(crate) fn login_chain(
|
pub(crate) fn login_chain(
|
||||||
sources: &[Source],
|
sources: &[Source],
|
||||||
fallback: LocalFallback,
|
fallback: config::LocalFallback,
|
||||||
local: Option<&UserRef>,
|
local: Option<&UserRef>,
|
||||||
released: bool,
|
released: bool,
|
||||||
) -> Vec<Source> {
|
) -> Vec<Source> {
|
||||||
let mut chain = Vec::with_capacity(sources.len() + 1);
|
let mut chain = Vec::with_capacity(sources.len() + 1);
|
||||||
let has_local = sources.iter().any(|s| matches!(s, Source::Local));
|
let has_local = sources.iter().any(|s| matches!(s, Source::Local));
|
||||||
if !has_local && let Some(user) = local {
|
if !has_local && let Some(user) = local {
|
||||||
let admin = fallback == LocalFallback::Admins && user.is_admin();
|
let admin = fallback == config::LocalFallback::Admins && user.is_admin();
|
||||||
let freed = fallback != LocalFallback::None && released;
|
let freed = fallback != config::LocalFallback::None && released;
|
||||||
if admin || freed {
|
if admin || freed {
|
||||||
chain.push(Source::Local);
|
chain.push(Source::Local);
|
||||||
}
|
}
|
||||||
|
|
@ -521,10 +521,13 @@ pub(crate) fn login_chain(
|
||||||
}
|
}
|
||||||
|
|
||||||
// Si hace falta preguntar a los proveedores si liberan la cuenta para construir la cadena.
|
// Si hace falta preguntar a los proveedores si liberan la cuenta para construir la cadena.
|
||||||
pub(crate) fn needs_release_check(fallback: LocalFallback, local: Option<&UserRef>) -> bool {
|
pub(crate) fn needs_release_check(
|
||||||
|
fallback: config::LocalFallback,
|
||||||
|
local: Option<&UserRef>,
|
||||||
|
) -> bool {
|
||||||
!local_is_source()
|
!local_is_source()
|
||||||
&& fallback != LocalFallback::None
|
&& fallback != config::LocalFallback::None
|
||||||
&& local.is_some_and(|user| !(fallback == LocalFallback::Admins && user.is_admin()))
|
&& local.is_some_and(|user| !(fallback == config::LocalFallback::Admins && user.is_admin()))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Proveedores (por identificador) a los que está vinculada la cuenta; vacío si es local.
|
// Proveedores (por identificador) a los que está vinculada la cuenta; vacío si es local.
|
||||||
|
|
@ -668,7 +671,7 @@ mod tests {
|
||||||
let both = resolve_sources(&ids(&["fake", "local"]), &declared).unwrap();
|
let both = resolve_sources(&ids(&["fake", "local"]), &declared).unwrap();
|
||||||
let admin = user(true);
|
let admin = user(true);
|
||||||
let plain = user(false);
|
let plain = user(false);
|
||||||
use LocalFallback::*;
|
use config::LocalFallback::*;
|
||||||
|
|
||||||
// "local" already in the sources: the chain is the configured one.
|
// "local" already in the sources: the chain is the configured one.
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ use pagetop_seaorm::db::*;
|
||||||
|
|
||||||
use crate::account::UserStatus;
|
use crate::account::UserStatus;
|
||||||
use crate::actions::AfterUserStatusChanged;
|
use crate::actions::AfterUserStatusChanged;
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::entity::{role, session, user, user_identity, user_role, user_token};
|
use crate::entity::{role, session, user, user_identity, user_role, user_token};
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
use crate::identity::{self, Email, Username};
|
use crate::identity::{self, Email, Username};
|
||||||
|
|
@ -22,7 +22,8 @@ use crate::service::user_admin::{
|
||||||
/// Aplica la política de identidad configurada ([`IdentityPolicy`](crate::config::IdentityPolicy))
|
/// Aplica la política de identidad configurada ([`IdentityPolicy`](crate::config::IdentityPolicy))
|
||||||
/// y lo devuelve normalizado, tal como se guardaría. No comprueba si está en uso.
|
/// y lo devuelve normalizado, tal como se guardaría. No comprueba si está en uso.
|
||||||
pub fn validate_username(username: &str) -> Result<String, AuthError> {
|
pub fn validate_username(username: &str) -> Result<String, AuthError> {
|
||||||
identity::username(username, SETTINGS.identity_policy, None).map(|u| u.value().to_owned())
|
identity::username(username, config::SETTINGS.identity_policy, None)
|
||||||
|
.map(|u| u.value().to_owned())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Comprueba que `email` es una dirección válida y la devuelve tal como se guardaría.
|
/// Comprueba que `email` es una dirección válida y la devuelve tal como se guardaría.
|
||||||
|
|
@ -375,7 +376,7 @@ impl ProviderHandle {
|
||||||
) {
|
) {
|
||||||
return Err(AuthError::InvalidStatus);
|
return Err(AuthError::InvalidStatus);
|
||||||
}
|
}
|
||||||
let username = identity::username(&data.username, SETTINGS.identity_policy, None)?;
|
let username = identity::username(&data.username, config::SETTINGS.identity_policy, None)?;
|
||||||
let email = identity::email(&data.email)?;
|
let email = identity::email(&data.email)?;
|
||||||
ensure_username_available(&username, None).await?;
|
ensure_username_available(&username, None).await?;
|
||||||
ensure_email_available(&email, None).await?;
|
ensure_email_available(&email, None).await?;
|
||||||
|
|
@ -723,7 +724,7 @@ impl ProviderHandle {
|
||||||
let current = find_user(user_id).await?;
|
let current = find_user(user_id).await?;
|
||||||
let username: Username = identity::username(
|
let username: Username = identity::username(
|
||||||
new_username,
|
new_username,
|
||||||
SETTINGS.identity_policy,
|
config::SETTINGS.identity_policy,
|
||||||
Some(¤t.username_key),
|
Some(¤t.username_key),
|
||||||
)?;
|
)?;
|
||||||
ensure_username_available(&username, Some(user_id)).await?;
|
ensure_username_available(&username, Some(user_id)).await?;
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ use pagetop::prelude::*;
|
||||||
use pagetop_seaorm::db::*;
|
use pagetop_seaorm::db::*;
|
||||||
|
|
||||||
use crate::account::UserStatus;
|
use crate::account::UserStatus;
|
||||||
use crate::config::{SETTINGS, user_language_applies, user_timezone_applies};
|
use crate::config;
|
||||||
use crate::entity::{role, user, user_role};
|
use crate::entity::{role, user, user_role};
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
use crate::identity::{self, Email, Username};
|
use crate::identity::{self, Email, Username};
|
||||||
|
|
@ -211,25 +211,29 @@ pub(crate) async fn create_user(data: NewUserData<'_>) -> Result<i32, AuthError>
|
||||||
if data.link_provider.is_some() && data.is_admin {
|
if data.link_provider.is_some() && data.is_admin {
|
||||||
return Err(AuthError::ProtectedAccount);
|
return Err(AuthError::ProtectedAccount);
|
||||||
}
|
}
|
||||||
let username = identity::username(data.username, SETTINGS.identity_policy, None)?;
|
let username = identity::username(data.username, config::SETTINGS.identity_policy, None)?;
|
||||||
let email = identity::email(data.email)?;
|
let email = identity::email(data.email)?;
|
||||||
if let Some((plain, confirm)) = data.password {
|
if let Some((plain, confirm)) = data.password {
|
||||||
password::validate_strength(plain)?;
|
password::validate_strength(plain)?;
|
||||||
password::passwords_match(plain, confirm)?;
|
password::passwords_match(plain, confirm)?;
|
||||||
}
|
}
|
||||||
// El idioma y la zona horaria que no se aplican no se ofrecen en el formulario: se ignora lo
|
// El idioma, la zona horaria y el tema que no se aplican no se ofrecen en el formulario: se
|
||||||
// que pudiera llegar y el usuario se crea sin ellos.
|
// ignora lo que pudiera llegar y el usuario se crea sin ellos.
|
||||||
let language = if user_language_applies() {
|
let language = if config::user_language_applies() {
|
||||||
validate_language(data.language)?
|
validate_language(data.language)?
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
let timezone = if user_timezone_applies() {
|
let timezone = if config::user_timezone_applies() {
|
||||||
validate_timezone(data.timezone)?
|
validate_timezone(data.timezone)?
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
let theme = validate_theme(data.theme)?;
|
let theme = if config::user_theme_applies() {
|
||||||
|
validate_theme(data.theme)?
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
validate_display_name(data.display_name)?;
|
validate_display_name(data.display_name)?;
|
||||||
ensure_username_available(&username, None).await?;
|
ensure_username_available(&username, None).await?;
|
||||||
ensure_email_available(&email, None).await?;
|
ensure_email_available(&email, None).await?;
|
||||||
|
|
@ -343,18 +347,18 @@ pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Resul
|
||||||
let current = find_user(user_id).await?;
|
let current = find_user(user_id).await?;
|
||||||
let username = identity::username(
|
let username = identity::username(
|
||||||
data.username,
|
data.username,
|
||||||
SETTINGS.identity_policy,
|
config::SETTINGS.identity_policy,
|
||||||
Some(¤t.username_key),
|
Some(¤t.username_key),
|
||||||
)?;
|
)?;
|
||||||
let email = identity::email(data.email)?;
|
let email = identity::email(data.email)?;
|
||||||
// El idioma y la zona horaria que no se aplican tampoco se ofrecen en el formulario, así que no
|
// El idioma, la zona horaria y el tema que no se aplican tampoco se ofrecen en el formulario,
|
||||||
// llegan: se conserva lo guardado por si se vuelven a aplicar.
|
// así que no llegan: se conserva lo guardado por si se vuelven a aplicar.
|
||||||
let language = if user_language_applies() {
|
let language = if config::user_language_applies() {
|
||||||
Set(validate_language(data.language)?.map(str::to_owned))
|
Set(validate_language(data.language)?.map(str::to_owned))
|
||||||
} else {
|
} else {
|
||||||
ActiveValue::NotSet
|
ActiveValue::NotSet
|
||||||
};
|
};
|
||||||
let timezone = if user_timezone_applies() {
|
let timezone = if config::user_timezone_applies() {
|
||||||
let timezone = match validate_timezone(data.timezone) {
|
let timezone = match validate_timezone(data.timezone) {
|
||||||
Err(AuthError::InvalidTimezone) => {
|
Err(AuthError::InvalidTimezone) => {
|
||||||
keep_current_timezone(data.timezone, current.timezone.as_deref())?
|
keep_current_timezone(data.timezone, current.timezone.as_deref())?
|
||||||
|
|
@ -365,7 +369,11 @@ pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Resul
|
||||||
} else {
|
} else {
|
||||||
ActiveValue::NotSet
|
ActiveValue::NotSet
|
||||||
};
|
};
|
||||||
let theme = validate_theme(data.theme)?;
|
let theme = if config::user_theme_applies() {
|
||||||
|
Set(validate_theme(data.theme)?.map(str::to_owned))
|
||||||
|
} else {
|
||||||
|
ActiveValue::NotSet
|
||||||
|
};
|
||||||
validate_display_name(data.display_name)?;
|
validate_display_name(data.display_name)?;
|
||||||
// El navegador envía los saltos de línea de un `<textarea>` como `\r\n`, pero `maxlength` puede
|
// El navegador envía los saltos de línea de un `<textarea>` como `\r\n`, pero `maxlength` puede
|
||||||
// contarlos como un único carácter: se normalizan antes de medir para no rechazar un texto que
|
// contarlos como un único carácter: se normalizan antes de medir para no rechazar un texto que
|
||||||
|
|
@ -382,7 +390,7 @@ pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Resul
|
||||||
about: Set(about),
|
about: Set(about),
|
||||||
language,
|
language,
|
||||||
timezone,
|
timezone,
|
||||||
theme: Set(theme.map(str::to_owned)),
|
theme,
|
||||||
updated_at: Set(now),
|
updated_at: Set(now),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ use pagetop_seaorm::db::{ColumnTrait, EntityTrait, QueryFilter, QuerySelect};
|
||||||
use pagetop_seaorm::db::{Condition, DbErr, Set, dbconn};
|
use pagetop_seaorm::db::{Condition, DbErr, Set, dbconn};
|
||||||
|
|
||||||
use crate::account::{Account, PermissionSet, UserStatus};
|
use crate::account::{Account, PermissionSet, UserStatus};
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::entity::{role_permission, session, user, user_role};
|
use crate::entity::{role_permission, session, user, user_role};
|
||||||
use crate::{ANONYMOUS_ROLE_ID, AUTHENTICATED_ROLE_ID};
|
use crate::{ANONYMOUS_ROLE_ID, AUTHENTICATED_ROLE_ID};
|
||||||
|
|
||||||
|
|
@ -42,20 +42,20 @@ fn bytes_to_hex(bytes: &[u8]) -> String {
|
||||||
/// Con `remember`, la cookie dura `remember_idle_secs`; sin él, es de sesión del navegador. Se marca
|
/// Con `remember`, la cookie dura `remember_idle_secs`; sin él, es de sesión del navegador. Se marca
|
||||||
/// como `Secure` según `secure_cookies` de `[server]`.
|
/// como `Secure` según `secure_cookies` de `[server]`.
|
||||||
pub fn build_cookie(sid: &str, remember: bool) -> String {
|
pub fn build_cookie(sid: &str, remember: bool) -> String {
|
||||||
let max_age =
|
let max_age = remember
|
||||||
remember.then(|| u64::try_from(SETTINGS.session.remember_idle_secs).unwrap_or_default());
|
.then(|| u64::try_from(config::SETTINGS.session.remember_idle_secs).unwrap_or_default());
|
||||||
web::cookie_header(&SETTINGS.session.cookie_name, sid, "/", max_age)
|
web::cookie_header(&config::SETTINGS.session.cookie_name, sid, "/", max_age)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Construye la cookie de expiración (Max-Age=0) para borrar la sesión del navegador.
|
/// Construye la cookie de expiración (Max-Age=0) para borrar la sesión del navegador.
|
||||||
pub fn expiry_cookie() -> String {
|
pub fn expiry_cookie() -> String {
|
||||||
web::cookie_header(&SETTINGS.session.cookie_name, "", "/", Some(0))
|
web::cookie_header(&config::SETTINGS.session.cookie_name, "", "/", Some(0))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Extrae el session ID de las cabeceras HTTP de la petición, si existe y tiene el formato de los
|
/// Extrae el session ID de las cabeceras HTTP de la petición, si existe y tiene el formato de los
|
||||||
/// que genera [`generate_sid`].
|
/// que genera [`generate_sid`].
|
||||||
pub fn extract_sid(headers: Option<&web::http::HeaderMap>) -> Option<&str> {
|
pub fn extract_sid(headers: Option<&web::http::HeaderMap>) -> Option<&str> {
|
||||||
let name = SETTINGS.session.cookie_name.as_str();
|
let name = config::SETTINGS.session.cookie_name.as_str();
|
||||||
// Con HTTP/2 el navegador puede repartir las cookies en varias cabeceras `cookie`.
|
// Con HTTP/2 el navegador puede repartir las cookies en varias cabeceras `cookie`.
|
||||||
headers?
|
headers?
|
||||||
.get_all(web::http::header::COOKIE)
|
.get_all(web::http::header::COOKIE)
|
||||||
|
|
@ -156,7 +156,7 @@ pub async fn load_user_from_session(sid: &str) -> (CurrentUser, Option<Account>,
|
||||||
sess.last_activity_at,
|
sess.last_activity_at,
|
||||||
now,
|
now,
|
||||||
idle_period(sess.remember),
|
idle_period(sess.remember),
|
||||||
Duration::seconds(SETTINGS.session.write_interval_secs),
|
Duration::seconds(config::SETTINGS.session.write_interval_secs),
|
||||||
) {
|
) {
|
||||||
if sess.remember {
|
if sess.remember {
|
||||||
renewed_cookie = Some(build_cookie(sid, true));
|
renewed_cookie = Some(build_cookie(sid, true));
|
||||||
|
|
@ -198,9 +198,9 @@ pub async fn load_user_from_session(sid: &str) -> (CurrentUser, Option<Account>,
|
||||||
// Tiempo sin uso tras el que caduca una sesión, según se iniciara o no con "recordarme".
|
// Tiempo sin uso tras el que caduca una sesión, según se iniciara o no con "recordarme".
|
||||||
fn idle_period(remember: bool) -> Duration {
|
fn idle_period(remember: bool) -> Duration {
|
||||||
Duration::seconds(if remember {
|
Duration::seconds(if remember {
|
||||||
SETTINGS.session.remember_idle_secs
|
config::SETTINGS.session.remember_idle_secs
|
||||||
} else {
|
} else {
|
||||||
SETTINGS.session.idle_secs
|
config::SETTINGS.session.idle_secs
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -341,7 +341,7 @@ pub(crate) fn invalidate_anonymous_permissions() {
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
DateTime, Duration, SETTINGS, Utc, bytes_to_hex, extract_sid, generate_sid, renewed_expiry,
|
DateTime, Duration, Utc, bytes_to_hex, config, extract_sid, generate_sid, renewed_expiry,
|
||||||
web,
|
web,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -419,7 +419,7 @@ mod tests {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn extracts_sid_among_other_cookies() {
|
fn extracts_sid_among_other_cookies() {
|
||||||
let name = &SETTINGS.session.cookie_name;
|
let name = &config::SETTINGS.session.cookie_name;
|
||||||
let headers = cookie_headers(&[&format!("a=1; {name}={SID}; b=2")]);
|
let headers = cookie_headers(&[&format!("a=1; {name}={SID}; b=2")]);
|
||||||
assert_eq!(extract_sid(Some(&headers)), Some(SID));
|
assert_eq!(extract_sid(Some(&headers)), Some(SID));
|
||||||
}
|
}
|
||||||
|
|
@ -427,14 +427,14 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn extracts_sid_from_split_cookie_headers() {
|
fn extracts_sid_from_split_cookie_headers() {
|
||||||
// HTTP/2 clients may send each cookie in its own header field.
|
// HTTP/2 clients may send each cookie in its own header field.
|
||||||
let name = &SETTINGS.session.cookie_name;
|
let name = &config::SETTINGS.session.cookie_name;
|
||||||
let headers = cookie_headers(&["a=1", &format!("{name}={SID}")]);
|
let headers = cookie_headers(&["a=1", &format!("{name}={SID}")]);
|
||||||
assert_eq!(extract_sid(Some(&headers)), Some(SID));
|
assert_eq!(extract_sid(Some(&headers)), Some(SID));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn skips_cookies_with_a_longer_name_or_invalid_value() {
|
fn skips_cookies_with_a_longer_name_or_invalid_value() {
|
||||||
let name = &SETTINGS.session.cookie_name;
|
let name = &config::SETTINGS.session.cookie_name;
|
||||||
let headers = cookie_headers(&[&format!("{name}x={SID}; {name}=bogus")]);
|
let headers = cookie_headers(&[&format!("{name}x={SID}; {name}=bogus")]);
|
||||||
assert_eq!(extract_sid(Some(&headers)), None);
|
assert_eq!(extract_sid(Some(&headers)), None);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
|
|
||||||
use std::collections::{HashMap, VecDeque};
|
use std::collections::{HashMap, VecDeque};
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
|
|
@ -53,8 +53,8 @@ pub(crate) fn allow(request: &HttpRequest) -> bool {
|
||||||
&mut lock(&REQUESTS),
|
&mut lock(&REQUESTS),
|
||||||
network(ip),
|
network(ip),
|
||||||
Instant::now(),
|
Instant::now(),
|
||||||
SETTINGS.max_ip_requests,
|
config::SETTINGS.max_ip_requests,
|
||||||
window(SETTINGS.ip_request_window_secs),
|
window(config::SETTINGS.ip_request_window_secs),
|
||||||
);
|
);
|
||||||
if !allowed {
|
if !allowed {
|
||||||
trace::warn!("Request limit reached for address {ip}");
|
trace::warn!("Request limit reached for address {ip}");
|
||||||
|
|
@ -95,20 +95,20 @@ impl LoginKeys {
|
||||||
/// se anota en ningún límite.
|
/// se anota en ningún límite.
|
||||||
pub(crate) fn allow_login(keys: &LoginKeys) -> bool {
|
pub(crate) fn allow_login(keys: &LoginKeys) -> bool {
|
||||||
let now = Instant::now();
|
let now = Instant::now();
|
||||||
let ip_window = window(SETTINGS.ip_failed_login_window_secs);
|
let ip_window = window(config::SETTINGS.ip_failed_login_window_secs);
|
||||||
let ip_allowed = match keys.ip {
|
let ip_allowed = match keys.ip {
|
||||||
Some(ip) => allow_at(
|
Some(ip) => allow_at(
|
||||||
&mut lock(&FAILED_LOGINS),
|
&mut lock(&FAILED_LOGINS),
|
||||||
ip,
|
ip,
|
||||||
now,
|
now,
|
||||||
SETTINGS.max_ip_failed_logins,
|
config::SETTINGS.max_ip_failed_logins,
|
||||||
ip_window,
|
ip_window,
|
||||||
),
|
),
|
||||||
None if keys.anywhere => allow_at(
|
None if keys.anywhere => allow_at(
|
||||||
&mut lock(&FAILED_ANYWHERE),
|
&mut lock(&FAILED_ANYWHERE),
|
||||||
(),
|
(),
|
||||||
now,
|
now,
|
||||||
SETTINGS.max_ip_failed_logins,
|
config::SETTINGS.max_ip_failed_logins,
|
||||||
ip_window,
|
ip_window,
|
||||||
),
|
),
|
||||||
None => true,
|
None => true,
|
||||||
|
|
@ -120,13 +120,13 @@ pub(crate) fn allow_login(keys: &LoginKeys) -> bool {
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
let max = u32::try_from(SETTINGS.max_failed_logins).unwrap_or(0);
|
let max = u32::try_from(config::SETTINGS.max_failed_logins).unwrap_or(0);
|
||||||
let identifier_allowed = allow_at(
|
let identifier_allowed = allow_at(
|
||||||
&mut lock(&FAILED_IDENTIFIERS),
|
&mut lock(&FAILED_IDENTIFIERS),
|
||||||
keys.identifier.clone(),
|
keys.identifier.clone(),
|
||||||
now,
|
now,
|
||||||
max,
|
max,
|
||||||
window(SETTINGS.failed_login_window_secs),
|
window(config::SETTINGS.failed_login_window_secs),
|
||||||
);
|
);
|
||||||
if !identifier_allowed {
|
if !identifier_allowed {
|
||||||
trace::warn!("Failed login limit reached for an identifier");
|
trace::warn!("Failed login limit reached for an identifier");
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ use pagetop_seaorm::db::{
|
||||||
ActiveValue, ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, Set, dbconn,
|
ActiveValue, ColumnTrait, EntityTrait, PaginatorTrait, QueryFilter, Set, dbconn,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::config::SETTINGS;
|
use crate::config;
|
||||||
use crate::entity::user_token;
|
use crate::entity::user_token;
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
|
|
||||||
|
|
@ -85,12 +85,12 @@ impl TokenKind {
|
||||||
fn limit(self) -> (u32, i64) {
|
fn limit(self) -> (u32, i64) {
|
||||||
match self {
|
match self {
|
||||||
TokenKind::PasswordReset => (
|
TokenKind::PasswordReset => (
|
||||||
SETTINGS.max_password_resets,
|
config::SETTINGS.max_password_resets,
|
||||||
SETTINGS.password_reset_window_secs,
|
config::SETTINGS.password_reset_window_secs,
|
||||||
),
|
),
|
||||||
TokenKind::EmailChange => (
|
TokenKind::EmailChange => (
|
||||||
SETTINGS.max_email_changes,
|
config::SETTINGS.max_email_changes,
|
||||||
SETTINGS.email_change_window_secs,
|
config::SETTINGS.email_change_window_secs,
|
||||||
),
|
),
|
||||||
TokenKind::EmailVerification => (0, 0),
|
TokenKind::EmailVerification => (0, 0),
|
||||||
}
|
}
|
||||||
|
|
|
||||||
26
src/admin.rs
26
src/admin.rs
|
|
@ -83,7 +83,9 @@
|
||||||
//! [`DeclareAdminTasks`]: crate::base::action::admin::DeclareAdminTasks
|
//! [`DeclareAdminTasks`]: crate::base::action::admin::DeclareAdminTasks
|
||||||
//! [`DeclareAdminActions`]: crate::base::action::admin::DeclareAdminActions
|
//! [`DeclareAdminActions`]: crate::base::action::admin::DeclareAdminActions
|
||||||
|
|
||||||
use crate::core::component::Context;
|
use crate::core::AnyCast;
|
||||||
|
use crate::core::component::{Context, Contextual};
|
||||||
|
use crate::core::theme::CoreTemplates;
|
||||||
use crate::{global, util};
|
use crate::{global, util};
|
||||||
|
|
||||||
mod bag;
|
mod bag;
|
||||||
|
|
@ -136,3 +138,25 @@ pub fn can_access_admin(cx: &Context) -> bool {
|
||||||
.iter()
|
.iter()
|
||||||
.any(|page| registry.section(page.section()).is_some() && page.is_accessible(cx))
|
.any(|page| registry.section(page.section()).is_some() && page.is_accessible(cx))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Devuelve `true` si la página es del panel de administración y el usuario tiene acceso a él.
|
||||||
|
///
|
||||||
|
/// Concretamente, devuelve `true` cuando la página actual del contexto utiliza la plantilla
|
||||||
|
/// [`CoreTemplates::Admin`] y el usuario de la petición puede acceder a alguna de las páginas del
|
||||||
|
/// panel ([`can_access_admin()`]).
|
||||||
|
///
|
||||||
|
/// Es la condición con la que se muestra la navegación del panel ([`Nav::admin()`]). Una página del
|
||||||
|
/// panel puede responder a quien no tiene acceso (el error 403 se pinta con la plantilla de la
|
||||||
|
/// página), así que no basta con comprobar la plantilla.
|
||||||
|
///
|
||||||
|
/// Sirve también para ocultar en el panel uno o más menús, negando esta función en su
|
||||||
|
/// [`Nav::with_renderable()`].
|
||||||
|
///
|
||||||
|
/// [`Nav::admin()`]: crate::base::component::Nav::admin
|
||||||
|
/// [`Nav::with_renderable()`]: crate::base::component::Nav::with_renderable
|
||||||
|
pub fn is_admin_panel(cx: &Context) -> bool {
|
||||||
|
matches!(
|
||||||
|
cx.template().downcast_ref::<CoreTemplates>(),
|
||||||
|
Some(CoreTemplates::Admin)
|
||||||
|
) && can_access_admin(cx)
|
||||||
|
}
|
||||||
|
|
|
||||||
19
src/auth.rs
19
src/auth.rs
|
|
@ -86,11 +86,8 @@ pub struct CurrentUser {
|
||||||
// Ver `timezone()`, que devuelve la zona horaria efectiva.
|
// Ver `timezone()`, que devuelve la zona horaria efectiva.
|
||||||
#[getters(skip)]
|
#[getters(skip)]
|
||||||
timezone: Option<Tz>,
|
timezone: Option<Tz>,
|
||||||
/// Devuelve el tema preferido del usuario, o `None` si no tiene ninguno.
|
// Ver `theme()`, que devuelve el tema preferido sólo si se aplica.
|
||||||
///
|
#[getters(skip)]
|
||||||
/// Lo tiene en cuenta el [`Context`](crate::core::component::Context) de la petición al elegir
|
|
||||||
/// el tema con el que se renderiza.
|
|
||||||
#[getters(copy)]
|
|
||||||
theme: Option<ThemeRef>,
|
theme: Option<ThemeRef>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -176,6 +173,18 @@ impl CurrentUser {
|
||||||
_ => Timezone::default_tz(),
|
_ => Timezone::default_tz(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Devuelve el tema preferido del usuario, o `None` si no tiene ninguno.
|
||||||
|
///
|
||||||
|
/// También devuelve `None` si [`global::SETTINGS.app.theme_per_user`] es *false*, aunque el
|
||||||
|
/// usuario tenga uno. Lo tiene en cuenta el [`Context`] de la petición al elegir el tema con el
|
||||||
|
/// que se renderiza: sin tema preferido, usa el predeterminado de la aplicación.
|
||||||
|
///
|
||||||
|
/// [`global::SETTINGS.app.theme_per_user`]: crate::global::AppSettings::theme_per_user
|
||||||
|
/// [`Context`]: crate::core::component::Context
|
||||||
|
pub fn theme(&self) -> Option<ThemeRef> {
|
||||||
|
self.theme.filter(|_| global::SETTINGS.app.theme_per_user)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< Permission >*********************************************************************************
|
// **< Permission >*********************************************************************************
|
||||||
|
|
|
||||||
|
|
@ -2,12 +2,6 @@
|
||||||
|
|
||||||
pub mod layout;
|
pub mod layout;
|
||||||
|
|
||||||
mod admin_frame;
|
|
||||||
pub use admin_frame::AdminFrame;
|
|
||||||
|
|
||||||
mod admin_menu;
|
|
||||||
pub use admin_menu::AdminMenu;
|
|
||||||
|
|
||||||
mod badge;
|
mod badge;
|
||||||
pub use badge::Badge;
|
pub use badge::Badge;
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,60 +0,0 @@
|
||||||
use crate::prelude::*;
|
|
||||||
|
|
||||||
/// Navegación del panel de administración para el usuario de la petición actual.
|
|
||||||
///
|
|
||||||
/// Es una [`Navbar`] con un enlace al inicio del panel (*dashboard*) seguido de un desplegable por
|
|
||||||
/// sección, con las páginas de cada una a las que el usuario puede acceder; las secciones sin
|
|
||||||
/// ninguna no se muestran. Lo construye en cada petición a partir de [`AdminRegistry`].
|
|
||||||
///
|
|
||||||
/// La plantilla [`CoreTemplates::Admin`] lo pinta tras la región [`CoreRegions::Header`]. Se
|
|
||||||
/// construye sólo con componentes del núcleo (`Navbar`, `Nav` y `Dropdown`), así que un tema le da
|
|
||||||
/// su aspecto capturando esos componentes o éste mismo en [`Theme::render_component()`].
|
|
||||||
///
|
|
||||||
/// Sin acceso a ninguna página del panel ([`can_access_admin()`]) no se renderiza: no se despachan
|
|
||||||
/// sus acciones ni intervienen los temas.
|
|
||||||
///
|
|
||||||
/// [`Theme::render_component()`]: crate::core::theme::Theme::render_component
|
|
||||||
#[derive(AutoDefault, Clone, Debug)]
|
|
||||||
pub struct AdminMenu;
|
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl Component for AdminMenu {
|
|
||||||
fn new() -> Self {
|
|
||||||
Self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_renderable(&self, cx: &Context) -> bool {
|
|
||||||
can_access_admin(cx)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
|
||||||
let registry = AdminRegistry::global();
|
|
||||||
|
|
||||||
let mut nav =
|
|
||||||
Nav::new().with_item(nav::Item::link(Lc::l("admin_dashboard"), admin_path("")));
|
|
||||||
for section in registry.sections() {
|
|
||||||
let pages: Vec<_> = registry
|
|
||||||
.pages_for_section(section.key())
|
|
||||||
.iter()
|
|
||||||
.filter(|p| p.is_accessible(cx))
|
|
||||||
.collect();
|
|
||||||
if pages.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let mut menu = Dropdown::new().with_title(section.title().clone());
|
|
||||||
for page in pages {
|
|
||||||
menu = menu.with_item(dropdown::Item::link(
|
|
||||||
page.title().clone(),
|
|
||||||
admin_path(page.path()),
|
|
||||||
));
|
|
||||||
}
|
|
||||||
nav = nav.with_item(nav::Item::dropdown(menu));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Navbar::simple()
|
|
||||||
.with_prop(PropsOp::add_classes("admin-menu"))
|
|
||||||
.with_item(navbar::Item::nav(nav))
|
|
||||||
.render(cx)
|
|
||||||
.await)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -19,6 +19,9 @@ use crate::prelude::*;
|
||||||
/// deja enviar el formulario sin elegir un tema. El valor recibido debe validarse igualmente en
|
/// deja enviar el formulario sin elegir un tema. El valor recibido debe validarse igualmente en
|
||||||
/// el servidor.
|
/// el servidor.
|
||||||
///
|
///
|
||||||
|
/// Si [`global::SETTINGS.app.theme_per_user`] es *false*, el tema propio del usuario no se aplica y
|
||||||
|
/// no conviene mostrar este campo.
|
||||||
|
///
|
||||||
/// # Ejemplo
|
/// # Ejemplo
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
|
|
@ -28,6 +31,8 @@ use crate::prelude::*;
|
||||||
/// .with_label(Lc::n("Theme"))
|
/// .with_label(Lc::n("Theme"))
|
||||||
/// .with_selected("Basic");
|
/// .with_selected("Basic");
|
||||||
/// ```
|
/// ```
|
||||||
|
///
|
||||||
|
/// [`global::SETTINGS.app.theme_per_user`]: crate::global::AppSettings::theme_per_user
|
||||||
#[derive(AutoDefault, Clone, Debug, Getters)]
|
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||||
pub struct SelectTheme {
|
pub struct SelectTheme {
|
||||||
/// Devuelve la lista de selección interna con la configuración común (nombre, etiqueta, ayuda,
|
/// Devuelve la lista de selección interna con la configuración común (nombre, etiqueta, ayuda,
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,7 @@
|
||||||
//! Definiciones para la composición de documentos ([`Region`] y [`Template`]).
|
//! Definiciones para la composición de documentos ([`Region`], [`Template`] y [`AdminFrame`]).
|
||||||
|
|
||||||
|
mod admin_frame;
|
||||||
|
pub use admin_frame::AdminFrame;
|
||||||
|
|
||||||
mod region;
|
mod region;
|
||||||
pub use region::Region;
|
pub use region::Region;
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ use crate::prelude::*;
|
||||||
|
|
||||||
/// Marco de las páginas de administración, alrededor de [`CoreRegions::Content`].
|
/// Marco de las páginas de administración, alrededor de [`CoreRegions::Content`].
|
||||||
///
|
///
|
||||||
/// Pinta, para la ruta de la petición actual, las migas de pan del panel, el título de la página
|
/// Muestra, para la ruta de la petición actual, el *breadcrumb* del panel, el título de la página
|
||||||
/// ([`Contextual::title()`]) con sus botones de acción ([`AdminAction`]), las pestañas de la
|
/// ([`Contextual::title()`]) con sus botones de acción ([`AdminAction`]), las pestañas de la
|
||||||
/// página ([`AdminTask`]) y, después, el contenido. Si la página no tiene título, usa el de la
|
/// página ([`AdminTask`]) y, después, el contenido. Si la página no tiene título, usa el de la
|
||||||
/// página declarada para esa ruta, también en el `<title>` del documento:
|
/// página declarada para esa ruta, también en el `<title>` del documento:
|
||||||
|
|
@ -17,10 +17,10 @@ use crate::prelude::*;
|
||||||
/// <div class="admin-content">...</div>
|
/// <div class="admin-content">...</div>
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// La plantilla [`CoreTemplates::Admin`] lo pinta en lugar de la región `Content`, así que un
|
/// La plantilla [`CoreTemplates::Admin`] lo muestra en lugar de la región `Content`, así que un
|
||||||
/// *handler* sólo tiene que crear la página con [`Page::admin()`], darle título y añadir su
|
/// *handler* sólo tiene que crear la página con [`Page::admin()`], darle título y añadir su
|
||||||
/// contenido. Un tema puede capturarlo en [`Theme::render_component()`] para darle otro aspecto,
|
/// contenido. Un tema puede capturarlo en [`Theme::render_component()`] para darle otro aspecto,
|
||||||
/// pero entonces le corresponde pintar también la región `Content`
|
/// pero entonces le corresponde mostrar también la región `Content`
|
||||||
/// ([`layout::Region::content()`](crate::base::component::layout::Region::content)).
|
/// ([`layout::Region::content()`](crate::base::component::layout::Region::content)).
|
||||||
///
|
///
|
||||||
/// Para una ruta que no es una página declarada (p. ej. la edición de un elemento de un listado),
|
/// Para una ruta que no es una página declarada (p. ej. la edición de un elemento de un listado),
|
||||||
|
|
@ -10,9 +10,10 @@ use std::fmt;
|
||||||
/// su gusto (por ejemplo, usando CSS Grid, para que `Aside` se muestre como columna lateral junto a
|
/// su gusto (por ejemplo, usando CSS Grid, para que `Aside` se muestre como columna lateral junto a
|
||||||
/// `Content`). Si `Aside`, o cualquier otra región, no tiene contenido, no se renderiza.
|
/// `Content`). Si `Aside`, o cualquier otra región, no tiene contenido, no se renderiza.
|
||||||
///
|
///
|
||||||
/// [`CoreTemplates::Admin`] añade el panel de administración: tras `Header` pinta la navegación
|
/// [`CoreTemplates::Admin`] añade el panel de administración: en lugar de `Content` pinta el marco
|
||||||
/// del panel ([`AdminMenu`]) y, en lugar de `Content`, el marco de la página ([`AdminFrame`]), que
|
/// de la página ([`AdminFrame`]), que contiene la región; el contenedor lleva además la clase
|
||||||
/// contiene la región; el contenedor lleva además la clase `wrapper-admin`.
|
/// `wrapper-admin`. La navegación del panel no forma parte de la plantilla: la coloca la aplicación
|
||||||
|
/// donde quiera, con [`Nav::admin()`] en una barra aparte o en la suya.
|
||||||
///
|
///
|
||||||
/// No incluye las regiones reservadas ([`ReservedRegions::PageTop`] y
|
/// No incluye las regiones reservadas ([`ReservedRegions::PageTop`] y
|
||||||
/// [`ReservedRegions::PageBottom`]) porque el propio [`Page::render()`] las añade antes y después
|
/// [`ReservedRegions::PageBottom`]) porque el propio [`Page::render()`] las añade antes y después
|
||||||
|
|
@ -28,6 +29,8 @@ use std::fmt;
|
||||||
/// intervenir en su renderizado.
|
/// intervenir en su renderizado.
|
||||||
///
|
///
|
||||||
/// [`Region`]: crate::base::component::layout::Region
|
/// [`Region`]: crate::base::component::layout::Region
|
||||||
|
/// [`AdminFrame`]: crate::base::component::layout::AdminFrame
|
||||||
|
/// [`Nav::admin()`]: crate::base::component::Nav::admin
|
||||||
/// [`ReservedRegions::PageTop`]: crate::response::ReservedRegions::PageTop
|
/// [`ReservedRegions::PageTop`]: crate::response::ReservedRegions::PageTop
|
||||||
/// [`ReservedRegions::PageBottom`]: crate::response::ReservedRegions::PageBottom
|
/// [`ReservedRegions::PageBottom`]: crate::response::ReservedRegions::PageBottom
|
||||||
/// [`Page::render()`]: crate::response::Page::render
|
/// [`Page::render()`]: crate::response::Page::render
|
||||||
|
|
@ -76,9 +79,8 @@ impl Component for Template {
|
||||||
let body = if admin {
|
let body = if admin {
|
||||||
html! {
|
html! {
|
||||||
(layout::Region::header().render(cx).await)
|
(layout::Region::header().render(cx).await)
|
||||||
(AdminMenu::new().render(cx).await)
|
|
||||||
(layout::Region::aside().render(cx).await)
|
(layout::Region::aside().render(cx).await)
|
||||||
(AdminFrame::new().render(cx).await)
|
(layout::AdminFrame::new().render(cx).await)
|
||||||
(layout::Region::footer().render(cx).await)
|
(layout::Region::footer().render(cx).await)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,9 @@ use crate::prelude::*;
|
||||||
/// Si no contiene elementos, o si ninguno se muestra (ver [`Endpoint`]), el componente **no se
|
/// Si no contiene elementos, o si ninguno se muestra (ver [`Endpoint`]), el componente **no se
|
||||||
/// renderiza**.
|
/// renderiza**.
|
||||||
///
|
///
|
||||||
|
/// Con [`with_renderable()`](Nav::with_renderable) se puede decidir en cada petición si se muestra,
|
||||||
|
/// y con [`Nav::admin()`] presenta la navegación del panel de administración.
|
||||||
|
///
|
||||||
/// # Ejemplo
|
/// # Ejemplo
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
|
|
@ -32,6 +35,13 @@ pub struct Nav {
|
||||||
nav_layout: nav::Layout,
|
nav_layout: nav::Layout,
|
||||||
/// Devuelve la lista de elementos del menú.
|
/// Devuelve la lista de elementos del menú.
|
||||||
items: Children,
|
items: Children,
|
||||||
|
/// Devuelve la función que decide en cada petición si se renderiza, si la hay (ver
|
||||||
|
/// [`with_renderable()`](Nav::with_renderable)).
|
||||||
|
#[getters(copy)]
|
||||||
|
renderable: Option<FnIsRenderable>,
|
||||||
|
/// Indica si presenta la navegación del panel de administración (ver [`Nav::admin()`]).
|
||||||
|
#[getters(copy)]
|
||||||
|
is_admin: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
|
|
@ -44,7 +54,11 @@ impl Component for Nav {
|
||||||
self.props.get_id()
|
self.props.get_id()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn setup(&mut self, _cx: &mut Context) {
|
fn is_renderable(&self, cx: &Context) -> bool {
|
||||||
|
self.renderable().is_none_or(|f| f(cx)) && (!self.is_admin() || is_admin_panel(cx))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup(&mut self, cx: &mut Context) {
|
||||||
self.alter_prop(PropsOp::prepend_classes(match self.nav_layout() {
|
self.alter_prop(PropsOp::prepend_classes(match self.nav_layout() {
|
||||||
nav::Layout::Default => "nav",
|
nav::Layout::Default => "nav",
|
||||||
nav::Layout::Start => "nav nav-start",
|
nav::Layout::Start => "nav nav-start",
|
||||||
|
|
@ -54,6 +68,10 @@ impl Component for Nav {
|
||||||
nav::Layout::Fill => "nav nav-fill",
|
nav::Layout::Fill => "nav nav-fill",
|
||||||
nav::Layout::Justified => "nav nav-justified",
|
nav::Layout::Justified => "nav nav-justified",
|
||||||
}));
|
}));
|
||||||
|
if self.is_admin() {
|
||||||
|
self.alter_prop(PropsOp::add_classes("nav-admin"));
|
||||||
|
self.add_admin_items(cx);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||||
|
|
@ -70,6 +88,89 @@ impl Component for Nav {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Nav {
|
||||||
|
/// Crea la navegación del panel de administración para el usuario de la petición actual.
|
||||||
|
///
|
||||||
|
/// Al renderizarse añade un enlace al inicio del panel (*dashboard*) seguido de un desplegable
|
||||||
|
/// por sección, con las páginas de cada una a las que el usuario puede acceder; las secciones
|
||||||
|
/// sin ninguna no se muestran. Los construye en cada petición a partir de [`AdminRegistry`],
|
||||||
|
/// detrás de los elementos que se hayan añadido con [`with_item()`](Self::with_item).
|
||||||
|
///
|
||||||
|
/// Sólo se renderiza en las páginas del panel y si el usuario puede acceder a él
|
||||||
|
/// ([`is_admin_panel()`]); en las demás no se despachan sus acciones ni intervienen los temas.
|
||||||
|
/// Así puede colocarse en una barra o región presente en todas las páginas. Para que ocupe en
|
||||||
|
/// el panel el sitio de otro menú, ese otro menú se oculta en el panel con
|
||||||
|
/// [`with_renderable()`](Self::with_renderable) (ver el ejemplo).
|
||||||
|
///
|
||||||
|
/// La plantilla [`CoreTemplates::Admin`] no la pinta: la coloca la aplicación donde quiera,
|
||||||
|
/// como cualquier otro menú, con su disposición, clases y propiedades. Lleva además la clase
|
||||||
|
/// `nav-admin`, para que los temas puedan darle un aspecto propio.
|
||||||
|
///
|
||||||
|
/// # Ejemplos
|
||||||
|
///
|
||||||
|
/// En una barra aparte bajo la cabecera, centrada:
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// # use pagetop::prelude::*;
|
||||||
|
/// let admin = Navbar::simple().with_item(navbar::Item::nav(
|
||||||
|
/// Nav::admin()
|
||||||
|
/// .with_layout(nav::Layout::Center)
|
||||||
|
/// .with_prop(FlexItem::new().with_grow(flex::ItemGrow::Is1)),
|
||||||
|
/// ));
|
||||||
|
///
|
||||||
|
/// InRegion::Global(&CoreRegions::Header).add(admin);
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// En la barra principal, junto al menú de la aplicación y centrada en el espacio libre:
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// # use pagetop::prelude::*;
|
||||||
|
/// let navbar = Navbar::brand_left(Brand::new().with_title(Lc::n("My app")))
|
||||||
|
/// .with_item(navbar::Item::nav(
|
||||||
|
/// Nav::new().with_item(nav::Item::link(Lc::n("Home"), "/")),
|
||||||
|
/// ))
|
||||||
|
/// .with_item(navbar::Item::nav(
|
||||||
|
/// Nav::admin()
|
||||||
|
/// .with_layout(nav::Layout::Center)
|
||||||
|
/// .with_prop(FlexItem::new().with_grow(flex::ItemGrow::Is1)),
|
||||||
|
/// ));
|
||||||
|
///
|
||||||
|
/// InRegion::Global(&CoreRegions::Header).add(navbar);
|
||||||
|
/// ```
|
||||||
|
pub fn admin() -> Self {
|
||||||
|
Self {
|
||||||
|
is_admin: true,
|
||||||
|
..Self::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Añade el enlace al *dashboard* y un desplegable por sección con las páginas a las que puede
|
||||||
|
// acceder el usuario de la petición.
|
||||||
|
fn add_admin_items(&mut self, cx: &Context) {
|
||||||
|
let registry = AdminRegistry::global();
|
||||||
|
|
||||||
|
self.alter_item(nav::Item::link(Lc::l("admin_dashboard"), admin_path("")));
|
||||||
|
for section in registry.sections() {
|
||||||
|
let mut pages = registry
|
||||||
|
.pages_for_section(section.key())
|
||||||
|
.iter()
|
||||||
|
.filter(|p| p.is_accessible(cx))
|
||||||
|
.peekable();
|
||||||
|
if pages.peek().is_none() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut menu = Dropdown::new().with_title(section.title().clone());
|
||||||
|
for page in pages {
|
||||||
|
menu = menu.with_item(dropdown::Item::link(
|
||||||
|
page.title().clone(),
|
||||||
|
admin_path(page.path()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
self.alter_item(nav::Item::dropdown(menu));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[builder_impl]
|
#[builder_impl]
|
||||||
impl Nav {
|
impl Nav {
|
||||||
// **< Nav BUILDER >****************************************************************************
|
// **< Nav BUILDER >****************************************************************************
|
||||||
|
|
@ -92,6 +193,38 @@ impl Nav {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Asigna una función que decide en cada petición si el menú se renderiza.
|
||||||
|
///
|
||||||
|
/// Se evalúa antes que cualquier otra fase de su ciclo: si devuelve `false`, el menú no se
|
||||||
|
/// renderiza, no se despachan sus acciones ni intervienen los temas. Así un menú creado una
|
||||||
|
/// sola vez (por ejemplo, en una barra registrada con [`InRegion`]) puede mostrarse sólo en
|
||||||
|
/// las páginas que corresponda. Un cierre sin capturas sirve como función.
|
||||||
|
///
|
||||||
|
/// # Ejemplo
|
||||||
|
///
|
||||||
|
/// Menú principal que, en las páginas del panel de administración, deja su sitio a la
|
||||||
|
/// navegación del panel ([`Nav::admin()`]). Como ésta se muestra justo cuando se cumple
|
||||||
|
/// [`is_admin_panel()`], el menú principal usa la condición contraria: en cada página se ve uno
|
||||||
|
/// de los dos, también en una página del panel que responde a quien no tiene acceso (un error
|
||||||
|
/// 403), donde se ve el menú principal:
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// # use pagetop::prelude::*;
|
||||||
|
/// let main = Nav::new()
|
||||||
|
/// .with_item(nav::Item::link(Lc::n("Home"), "/"))
|
||||||
|
/// .with_renderable(|cx| !is_admin_panel(cx));
|
||||||
|
///
|
||||||
|
/// let navbar = Navbar::brand_left(Brand::new().with_title(Lc::n("My app")))
|
||||||
|
/// .with_item(navbar::Item::nav(main))
|
||||||
|
/// .with_item(navbar::Item::nav(Nav::admin()));
|
||||||
|
///
|
||||||
|
/// InRegion::Global(&CoreRegions::Header).add(navbar);
|
||||||
|
/// ```
|
||||||
|
pub fn with_renderable(mut self, f: FnIsRenderable) -> Self {
|
||||||
|
self.renderable = Some(f);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Añade un nuevo elemento al menú o modifica la lista de elementos del menú con una
|
/// Añade un nuevo elemento al menú o modifica la lista de elementos del menú con una
|
||||||
/// operación [`TypedOp`].
|
/// operación [`TypedOp`].
|
||||||
///
|
///
|
||||||
|
|
|
||||||
|
|
@ -211,8 +211,10 @@ pub trait Contextual {
|
||||||
/// Establece el título del documento como un valor traducible.
|
/// Establece el título del documento como un valor traducible.
|
||||||
///
|
///
|
||||||
/// Además de usarse en el `<head>`, lo ven las plantillas y los componentes al renderizarse,
|
/// Además de usarse en el `<head>`, lo ven las plantillas y los componentes al renderizarse,
|
||||||
/// como el marco de las páginas del panel de administración
|
/// como el marco de las páginas del panel de administración ([`AdminFrame`]), que lo muestra
|
||||||
/// ([`AdminFrame`](crate::base::component::AdminFrame)), que lo muestra como encabezado.
|
/// como encabezado.
|
||||||
|
///
|
||||||
|
/// [`AdminFrame`]: crate::base::component::layout::AdminFrame
|
||||||
fn with_title(self, title: Lc) -> Self {
|
fn with_title(self, title: Lc) -> Self {
|
||||||
self.context_mut().title = title;
|
self.context_mut().title = title;
|
||||||
self
|
self
|
||||||
|
|
|
||||||
|
|
@ -177,13 +177,16 @@ pub enum CoreTemplates {
|
||||||
|
|
||||||
/// Plantilla para la **interfaz de administración**, de nombre `"admin"`.
|
/// Plantilla para la **interfaz de administración**, de nombre `"admin"`.
|
||||||
///
|
///
|
||||||
/// Se utiliza para las páginas del panel de administración ([`Page::admin()`]): además de las
|
/// Se utiliza para las páginas del panel de administración ([`Page::admin()`]). Además de las
|
||||||
/// regiones de `Standard`, pinta la navegación del panel ([`AdminMenu`]) y el marco de la
|
/// regiones de `Standard`, muestra también el marco de la página ([`AdminFrame`]) alrededor de
|
||||||
/// página ([`AdminFrame`]) alrededor de la región de contenido.
|
/// la región de contenido.
|
||||||
|
///
|
||||||
|
/// Sin embargo, no muestra el menú de navegación del panel: será la aplicación la que decida
|
||||||
|
/// dónde colocarlo, usando [`Nav::admin()`].
|
||||||
///
|
///
|
||||||
/// [`Page::admin()`]: crate::response::Page::admin
|
/// [`Page::admin()`]: crate::response::Page::admin
|
||||||
/// [`AdminMenu`]: crate::base::component::AdminMenu
|
/// [`AdminFrame`]: crate::base::component::layout::AdminFrame
|
||||||
/// [`AdminFrame`]: crate::base::component::AdminFrame
|
/// [`Nav::admin()`]: crate::base::component::Nav::admin
|
||||||
Admin,
|
Admin,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -82,11 +82,6 @@ pub struct AppSettings {
|
||||||
/// Nombre de la aplicación.
|
/// Nombre de la aplicación.
|
||||||
#[default = "PageTop App"]
|
#[default = "PageTop App"]
|
||||||
pub name: String,
|
pub name: String,
|
||||||
/// Tema predeterminado: *"Basic"* o el de una extensión enlazada por la aplicación, sin
|
|
||||||
/// distinguir mayúsculas y minúsculas. Si no está habilitado se usa *"Basic"*, con un aviso al
|
|
||||||
/// arrancar. Ver [`default_theme()`](crate::core::theme::default_theme).
|
|
||||||
#[default = "Basic"]
|
|
||||||
pub theme: String,
|
|
||||||
/// Idioma predeterminado de la aplicación (p. ej., *"es-ES"* o *"en-US"*).
|
/// Idioma predeterminado de la aplicación (p. ej., *"es-ES"* o *"en-US"*).
|
||||||
///
|
///
|
||||||
/// Cuando tiene un valor validado por [`Locale`](crate::locale::Locale), se usa como candidato
|
/// Cuando tiene un valor validado por [`Locale`](crate::locale::Locale), se usa como candidato
|
||||||
|
|
@ -163,9 +158,38 @@ pub struct AppSettings {
|
||||||
/// gestionan usuarios no deben ofrecer elegirla; la zona guardada se conserva por si se vuelve
|
/// gestionan usuarios no deben ofrecer elegirla; la zona guardada se conserva por si se vuelve
|
||||||
/// a activar. Es el equivalente de [`LangNegotiation::ConfigOnly`] para el idioma.
|
/// a activar. Es el equivalente de [`LangNegotiation::ConfigOnly`] para el idioma.
|
||||||
///
|
///
|
||||||
|
/// Sólo tiene efecto con una extensión que guarde la zona horaria de cada usuario y la asigne
|
||||||
|
/// con [`CurrentUser::with_timezone()`] (como `pagetop-user`); sin ella, ningún usuario tiene
|
||||||
|
/// zona horaria propia.
|
||||||
|
///
|
||||||
/// [`CurrentUser::timezone()`]: crate::auth::CurrentUser::timezone
|
/// [`CurrentUser::timezone()`]: crate::auth::CurrentUser::timezone
|
||||||
|
/// [`CurrentUser::with_timezone()`]: crate::auth::CurrentUser::with_timezone
|
||||||
#[default = true]
|
#[default = true]
|
||||||
pub timezone_per_user: bool,
|
pub timezone_per_user: bool,
|
||||||
|
/// Tema predeterminado: *"Basic"* o el de una extensión enlazada por la aplicación, sin
|
||||||
|
/// distinguir mayúsculas y minúsculas. Si no está habilitado se usa *"Basic"*, con un aviso al
|
||||||
|
/// arrancar. Ver [`default_theme()`](crate::core::theme::default_theme).
|
||||||
|
///
|
||||||
|
/// Se usa para las peticiones de usuarios anónimos o sin tema propio, y para todos si
|
||||||
|
/// [`theme_per_user`](Self::theme_per_user) es *false*.
|
||||||
|
#[default = "Basic"]
|
||||||
|
pub theme: String,
|
||||||
|
/// Si cada usuario puede tener su propio tema (*true*) o se usa siempre el de la aplicación
|
||||||
|
/// (*false*, por defecto).
|
||||||
|
///
|
||||||
|
/// Con *false*, [`CurrentUser::theme()`] devuelve siempre `None`, aunque el usuario tenga uno
|
||||||
|
/// guardado, así que todas las páginas se renderizan con [`theme`](Self::theme); y las
|
||||||
|
/// extensiones que gestionan usuarios no deben ofrecer elegirlo. El tema guardado se conserva
|
||||||
|
/// por si se activa. No afecta al tema que fije el código de una página concreta.
|
||||||
|
///
|
||||||
|
/// Sólo tiene efecto con una extensión que guarde el tema de cada usuario y lo asigne con
|
||||||
|
/// [`CurrentUser::with_theme()`] (como `pagetop-user`); sin ella, ningún usuario tiene tema
|
||||||
|
/// propio.
|
||||||
|
///
|
||||||
|
/// [`CurrentUser::theme()`]: crate::auth::CurrentUser::theme
|
||||||
|
/// [`CurrentUser::with_theme()`]: crate::auth::CurrentUser::with_theme
|
||||||
|
#[default = false]
|
||||||
|
pub theme_per_user: bool,
|
||||||
/// Ruta raíz del panel de administración (p. ej. *"/admin"* o *"/manage"*).
|
/// Ruta raíz del panel de administración (p. ej. *"/admin"* o *"/manage"*).
|
||||||
///
|
///
|
||||||
/// Las secciones y páginas del panel se declaran con rutas relativas a ella, y
|
/// Las secciones y páginas del panel se declaran con rutas relativas a ella, y
|
||||||
|
|
|
||||||
|
|
@ -116,10 +116,8 @@ async fn the_admin_template_frames_the_content_of_the_page() {
|
||||||
render(Page::admin(request("/admin/config/export/csv")).with_title(Lc::n("CSV"))).await;
|
render(Page::admin(request("/admin/config/export/csv")).with_title(Lc::n("CSV"))).await;
|
||||||
|
|
||||||
assert!(html.contains(r#"class="wrapper wrapper-admin""#), "{html}");
|
assert!(html.contains(r#"class="wrapper wrapper-admin""#), "{html}");
|
||||||
// Navigation: only the sections with an accessible page.
|
// The template does not paint the navigation of the panel: the application places it.
|
||||||
assert!(html.contains("admin-menu"), "{html}");
|
assert!(!html.contains("nav-admin"), "{html}");
|
||||||
assert!(html.contains(r#"href="/admin/config/export""#), "{html}");
|
|
||||||
assert!(!html.contains(r#"href="/admin/reports/audit""#), "{html}");
|
|
||||||
// Breadcrumbs up to the nearest declared page, then the page title.
|
// Breadcrumbs up to the nearest declared page, then the page title.
|
||||||
assert!(html.contains(r#"href="/admin/config""#), "{html}");
|
assert!(html.contains(r#"href="/admin/config""#), "{html}");
|
||||||
assert!(
|
assert!(
|
||||||
|
|
@ -165,11 +163,156 @@ async fn the_standard_template_has_no_admin_frame() {
|
||||||
let html = render(Page::new(request("/admin/config/export")).with_title(Lc::n("Export"))).await;
|
let html = render(Page::new(request("/admin/config/export")).with_title(Lc::n("Export"))).await;
|
||||||
|
|
||||||
assert!(!html.contains("wrapper-admin"), "{html}");
|
assert!(!html.contains("wrapper-admin"), "{html}");
|
||||||
assert!(!html.contains("admin-menu"), "{html}");
|
assert!(!html.contains("nav-admin"), "{html}");
|
||||||
assert!(!html.contains("admin-content"), "{html}");
|
assert!(!html.contains("admin-content"), "{html}");
|
||||||
assert!(html.contains("Body of the page."), "{html}");
|
assert!(html.contains("Body of the page."), "{html}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Navigation of the panel in its own bar.
|
||||||
|
fn admin_navbar() -> Navbar {
|
||||||
|
Navbar::simple().with_item(navbar::Item::nav(Nav::admin()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn the_admin_menu_goes_where_the_application_places_it() {
|
||||||
|
let _ = Application::prepare(&Ext).await;
|
||||||
|
let page = Page::admin(request("/admin/config/export/csv"))
|
||||||
|
.with_child_in(&CoreRegions::Header, admin_navbar());
|
||||||
|
let html = render(page).await;
|
||||||
|
|
||||||
|
// Only the sections with an accessible page.
|
||||||
|
let header = &html[html.find(r#"id="header""#).unwrap()..html.find("admin-content").unwrap()];
|
||||||
|
assert!(header.contains("nav-admin"), "{header}");
|
||||||
|
assert!(header.contains("navbar-nav"), "{header}");
|
||||||
|
assert!(
|
||||||
|
header.contains(r#"href="/admin/config/export""#),
|
||||||
|
"{header}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!header.contains(r#"href="/admin/reports/audit""#),
|
||||||
|
"{header}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn the_admin_menu_only_shows_in_the_panel() {
|
||||||
|
let _ = Application::prepare(&Ext).await;
|
||||||
|
let page = Page::new(request("/home")).with_child_in(&CoreRegions::Header, admin_navbar());
|
||||||
|
let html = render(page).await;
|
||||||
|
|
||||||
|
assert!(!html.contains("nav-admin"), "{html}");
|
||||||
|
assert!(!html.contains(r#"href="/admin"#), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn the_admin_menu_does_not_repeat_its_links_when_rendered_again() {
|
||||||
|
let _ = Application::prepare(&Ext).await;
|
||||||
|
// The same prototype for every page, as with `InRegion`.
|
||||||
|
let navbar = admin_navbar();
|
||||||
|
for _ in 0..2 {
|
||||||
|
let page = Page::admin(request("/admin/config/export"))
|
||||||
|
.with_child_in(&CoreRegions::Header, navbar.clone());
|
||||||
|
let html = render(page).await;
|
||||||
|
// Links of the menu only (the breadcrumbs also link to the dashboard).
|
||||||
|
let links = r#"class="nav-link" href="/admin""#;
|
||||||
|
assert_eq!(html.matches(links).count(), 1, "{html}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main navbar of an application, with its own menu and the navigation of the panel.
|
||||||
|
fn main_navbar() -> Navbar {
|
||||||
|
Navbar::simple()
|
||||||
|
.with_item(navbar::Item::nav(
|
||||||
|
Nav::new().with_item(nav::Item::link(Lc::n("Home"), "/home")),
|
||||||
|
))
|
||||||
|
.with_item(navbar::Item::nav(Nav::admin()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn the_admin_menu_can_go_in_the_main_navbar() {
|
||||||
|
let _ = Application::prepare(&Ext).await;
|
||||||
|
let page = Page::admin(request("/admin/config/export/csv"))
|
||||||
|
.with_child_in(&CoreRegions::Header, main_navbar());
|
||||||
|
let html = render(page).await;
|
||||||
|
|
||||||
|
// The navigation of the panel goes in the main navbar, with the accessible pages only.
|
||||||
|
let header = &html[html.find(r#"id="header""#).unwrap()..html.find("admin-content").unwrap()];
|
||||||
|
assert!(header.contains(r#"href="/home""#), "{header}");
|
||||||
|
assert!(header.contains(r#"href="/admin""#), "{header}");
|
||||||
|
assert!(
|
||||||
|
header.contains(r#"href="/admin/config/export""#),
|
||||||
|
"{header}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!header.contains(r#"href="/admin/reports/audit""#),
|
||||||
|
"{header}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn the_admin_nav_keeps_its_layout_in_the_main_navbar() {
|
||||||
|
let _ = Application::prepare(&Ext).await;
|
||||||
|
let navbar = Navbar::simple().with_item(navbar::Item::nav(
|
||||||
|
Nav::admin()
|
||||||
|
.with_id("admin-nav")
|
||||||
|
.with_layout(nav::Layout::Center),
|
||||||
|
));
|
||||||
|
let page =
|
||||||
|
Page::admin(request("/admin/config/export")).with_child_in(&CoreRegions::Header, navbar);
|
||||||
|
let html = render(page).await;
|
||||||
|
|
||||||
|
let start = html
|
||||||
|
.find(r#"id="admin-nav""#)
|
||||||
|
.expect("the admin nav is rendered");
|
||||||
|
let nav = &html[html[..start].rfind('<').unwrap()..];
|
||||||
|
let nav = &nav[..nav.find('>').unwrap()];
|
||||||
|
assert!(nav.contains("nav-center"), "{nav}");
|
||||||
|
assert!(nav.contains("nav-admin"), "{nav}");
|
||||||
|
assert!(html.contains(r#"href="/admin/config/export""#), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main navbar whose own menu leaves its place to the navigation of the panel.
|
||||||
|
fn swapping_navbar() -> Navbar {
|
||||||
|
Navbar::simple()
|
||||||
|
.with_item(navbar::Item::nav(
|
||||||
|
Nav::new()
|
||||||
|
.with_item(nav::Item::link(Lc::n("Home"), "/home"))
|
||||||
|
.with_renderable(|cx| !is_admin_panel(cx)),
|
||||||
|
))
|
||||||
|
.with_item(navbar::Item::nav(Nav::admin()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn the_admin_nav_takes_the_place_of_the_main_menu_in_the_panel() {
|
||||||
|
let _ = Application::prepare(&Ext).await;
|
||||||
|
let page = Page::admin(request("/admin/config/export"))
|
||||||
|
.with_child_in(&CoreRegions::Header, swapping_navbar());
|
||||||
|
let html = render(page).await;
|
||||||
|
|
||||||
|
assert!(html.contains(r#"href="/admin/config/export""#), "{html}");
|
||||||
|
assert!(!html.contains(r#"href="/home""#), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn the_main_menu_shows_outside_the_panel() {
|
||||||
|
let _ = Application::prepare(&Ext).await;
|
||||||
|
let page = Page::new(request("/home")).with_child_in(&CoreRegions::Header, swapping_navbar());
|
||||||
|
let html = render(page).await;
|
||||||
|
|
||||||
|
assert!(html.contains(r#"href="/home""#), "{html}");
|
||||||
|
assert!(!html.contains(r#"href="/admin"#), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn the_admin_menu_of_the_main_navbar_only_shows_in_the_panel() {
|
||||||
|
let _ = Application::prepare(&Ext).await;
|
||||||
|
let page = Page::new(request("/home")).with_child_in(&CoreRegions::Header, main_navbar());
|
||||||
|
let html = render(page).await;
|
||||||
|
|
||||||
|
assert!(html.contains(r#"href="/home""#), "{html}");
|
||||||
|
assert!(!html.contains(r#"href="/admin"#), "{html}");
|
||||||
|
}
|
||||||
|
|
||||||
async fn get(uri: &str) -> (u16, String) {
|
async fn get(uri: &str) -> (u16, String) {
|
||||||
let app = Application::prepare(&Ext).await.test();
|
let app = Application::prepare(&Ext).await.test();
|
||||||
let request = web::test::TestRequest::get().uri(uri).to_request();
|
let request = web::test::TestRequest::get().uri(uri).to_request();
|
||||||
|
|
|
||||||
|
|
@ -13,3 +13,24 @@ async fn without_declared_pages_the_panel_is_not_mounted() {
|
||||||
assert_eq!(response.status().as_u16(), 404, "{uri}");
|
assert_eq!(response.status().as_u16(), 404, "{uri}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn without_access_to_the_panel_its_pages_show_the_main_menu() {
|
||||||
|
let _ = Application::prepare(&Ext).await;
|
||||||
|
let navbar = Navbar::simple()
|
||||||
|
.with_item(navbar::Item::nav(
|
||||||
|
Nav::new()
|
||||||
|
.with_item(nav::Item::link(Lc::n("Home"), "/home"))
|
||||||
|
.with_renderable(|cx| !is_admin_panel(cx)),
|
||||||
|
))
|
||||||
|
.with_item(navbar::Item::nav(Nav::admin()));
|
||||||
|
// A page with the admin template that nobody can access, as an error 403 would be.
|
||||||
|
let request = web::test::TestRequest::get()
|
||||||
|
.uri("/admin")
|
||||||
|
.to_http_request();
|
||||||
|
let mut page = Page::admin(request).with_child_in(&CoreRegions::Header, navbar);
|
||||||
|
let html = page.render().await.unwrap().into_string();
|
||||||
|
|
||||||
|
assert!(html.contains(r#"href="/home""#), "{html}");
|
||||||
|
assert!(!html.contains("nav-admin"), "{html}");
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue