✨ (user): Integra pagetop-mail y valida identidades

- Envía por correo la recuperación de contraseña y, con
  `require_email_verification`, la verificación de cuentas nuevas, que
  se confirma con un botón (los escáneres de correo abren los enlaces).
- Nueva política de nombres de usuario (`identity_policy`): sin `@`, sin
  distinguir mayúsculas y sin nombres confusables (UTS #39). Email
  validado con pagetop-mail.
- Tokens de un solo uso atómicos y ligados al usuario. Los correos a
  direcciones sin verificar no incluyen datos elegidos por el usuario.
- Bloqueo por intentos fallidos con su ventana de recuento, y el mismo
  tiempo de respuesta exista o no la cuenta. Argon2 en `spawn_blocking`.
- Límites de longitud del nombre visible y de los roles, y botones sólo
  con el permiso que exigen. Más correcciones en formularios y búsqueda.
This commit is contained in:
Manuel Cillero 2026-10-19 07:57:38 +02:00
parent a9b1b3b2a3
commit bd54980d0f
34 changed files with 2053 additions and 355 deletions

View file

@ -7,6 +7,7 @@ use crate::LOCALES_USER;
use crate::role_path;
use crate::component::error_banner;
use crate::service::role_admin::{ROLE_LABEL_MAX_CHARS, ROLE_MACHINE_NAME_MAX_CHARS};
#[derive(AutoDefault, Clone, Copy, Debug, PartialEq)]
pub(crate) enum RoleFormMode {
@ -48,7 +49,7 @@ impl Component for RoleForm {
.with_label(Lc::t("field-machine-name", &LOCALES_USER))
.with_help_text(Lc::t("help-machine-name-immutable", &LOCALES_USER))
.with_required(true)
.with_maxlength(Some(64)),
.with_maxlength(ROLE_MACHINE_NAME_MAX_CHARS),
RoleFormMode::Edit => form::input::Field::text()
.with_name("machine_name")
.with_value(self.machine_name())
@ -68,7 +69,7 @@ impl Component for RoleForm {
.with_value(self.label())
.with_label(Lc::t("field-label", &LOCALES_USER))
.with_required(true)
.with_maxlength(Some(128)),
.with_maxlength(ROLE_LABEL_MAX_CHARS),
)
.with_child(
form::Textarea::new()

View file

@ -6,6 +6,7 @@ use pagetop_htmx::hx_table::sort_link;
use crate::ADMIN_ROLES_PATH;
use crate::LOCALES_USER;
use crate::permission::UserPermission;
use crate::role_path;
use crate::service::role_admin::{RoleListItem, RoleSortField};
@ -227,8 +228,8 @@ fn label_cell(role: &RoleListItem, waypoint: &Waypoint) -> Html {
})
}
// Construye la celda de acciones: gestionar permisos siempre, y editar/borrar sólo si el rol no
// está bloqueado por el sistema. Devuelve un componente `Html` para que el marcado se genere cuando
// Construye la celda de acciones: gestionar permisos si se tiene `user:admin_permissions`, y
// editar/borrar sólo si el rol no está bloqueado por el sistema. Devuelve un componente `Html` para que el marcado se genere cuando
// `Table` renderice la celda, no al construir la fila.
async fn actions_cell(
role: &RoleListItem,
@ -242,20 +243,29 @@ async fn actions_cell(
let locked = role.locked;
let waypoint = waypoint.clone();
let permissions_href = waypoint.append_to(cx.route(role_path(id, "permissions")));
let can_manage_permissions = cx
.request()
.is_some_and(|request| has_permission(request, &UserPermission::AdminPermissions));
// Los botones se renderizan aquí, no dentro del `Html::with()` de abajo: necesitan pasar por su
// propio ciclo de renderizado (`.render().await`) para que el tema activo los estilice igual
// (ver `pagetop-bootsier::theme::bs::button`), incluida la traducción de `data-dialog-*` que
// usa el botón de borrado.
let permissions_button = Button::anchor(
Lc::t("btn-manage-permissions", &LOCALES_USER),
permissions_href,
)
.with_style(button::Style::Solid(Intent::Neutral))
.with_size(button::Size::Small)
.render(cx)
.await;
let permissions_button = if can_manage_permissions {
let permissions_href = waypoint.append_to(cx.route(role_path(id, "permissions")));
Some(
Button::anchor(
Lc::t("btn-manage-permissions", &LOCALES_USER),
permissions_href,
)
.with_style(button::Style::Solid(Intent::Neutral))
.with_size(button::Size::Small)
.render(cx)
.await,
)
} else {
None
};
let (edit_button, delete_button) = if locked {
(None, None)
@ -290,15 +300,11 @@ async fn actions_cell(
};
Html::with(move |_cx| {
let buttons = [&permissions_button, &edit_button, &delete_button];
html! {
(permissions_button)
@if let Some(edit_button) = &edit_button {
" "
(edit_button)
}
@if let Some(delete_button) = &delete_button {
" "
(delete_button)
@for (i, button) in buttons.into_iter().flatten().enumerate() {
@if i > 0 { " " }
(button)
}
}
})

View file

@ -3,12 +3,13 @@
use pagetop::prelude::*;
use crate::LOCALES_USER;
use crate::config::{user_language_applies, user_timezone_applies};
use crate::config::{SETTINGS, user_language_applies, user_timezone_applies};
use crate::user_path;
use crate::{ADMIN_USERS_PATH, PROFILE_EDIT_PATH};
use crate::component::{PasswordConfirm, error_banner};
use crate::service::user_admin::ABOUT_MAX_CHARS;
use crate::identity::{EMAIL_MAX_CHARS, USERNAME_MIN_CHARS, username_help, username_max_chars};
use crate::service::user_admin::{ABOUT_MAX_CHARS, DISPLAY_NAME_MAX_CHARS};
use super::{USER_ADMIN_FORM_ID, roles_fieldset};
@ -71,22 +72,30 @@ impl Component for UserForm {
.with_name("username")
.with_value(self.username())
.with_label(Lc::t("field-username-admin", &LOCALES_USER))
.with_help_text(if username_readonly {
Lc::none()
} else {
username_help(SETTINGS.identity_policy)
})
.with_required(true)
.with_readonly(username_readonly)
.with_maxlength(Some(64)),
.with_minlength(USERNAME_MIN_CHARS)
.with_maxlength(username_max_chars(SETTINGS.identity_policy)),
)
.with_child(
form::input::Field::email()
.with_name("email")
.with_value(self.email())
.with_label(Lc::t("field-email", &LOCALES_USER))
.with_required(true),
.with_required(true)
.with_maxlength(EMAIL_MAX_CHARS),
)
.with_child(
form::input::Field::text()
.with_name("display_name")
.with_value(self.display_name())
.with_label(Lc::t("field-display-name", &LOCALES_USER)),
.with_label(Lc::t("field-display-name", &LOCALES_USER))
.with_maxlength(DISPLAY_NAME_MAX_CHARS),
);
// Sólo se ofrecen si se aplican (ver `config::user_language_applies()` y

View file

@ -9,6 +9,8 @@ use crate::{LOCALES_USER, LOGIN_PATH, PASSWORD_RESET_PATH, REGISTER_PATH};
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct LoginForm {
error: Option<Lc>,
/// Usuario o email con el que se rellena el campo.
username: String,
/// Página a la que volver tras iniciar sesión.
waypoint: Waypoint,
}
@ -32,6 +34,7 @@ impl Component for LoginForm {
form::input::Field::text().with_autocomplete(Some(form::Autocomplete::username()))
}
.with_name(if strict { "ident" } else { "username" })
.with_value(self.username())
.with_label(Lc::t("field-username", &LOCALES_USER))
.with_autofocus(true)
.with_required(true);
@ -104,6 +107,12 @@ impl LoginForm {
self
}
/// Rellena el usuario o email, p. ej. con el enviado si el inicio de sesión falla.
pub fn with_username(mut self, username: impl Into<String>) -> Self {
self.username = username.into();
self
}
pub fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into();
self

View file

@ -4,11 +4,13 @@
use pagetop::prelude::*;
use crate::LOCALES_USER;
use crate::config::SETTINGS;
/// 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
/// coincidan (eso ocurre en el servidor, tras el envío del formulario), sólo renderiza los dos
/// campos, uno junto al otro, sin ningún contenedor propio.
/// campos, uno junto al otro, sin ningún contenedor propio. El de la contraseña indica la longitud
/// mínima configurada (`user.password.min_length`), como ayuda y con `minlength`.
#[derive(AutoDefault, Clone, Debug, Getters)]
pub(crate) struct PasswordConfirm {
/// Devuelve la etiqueta del campo de contraseña.
@ -21,7 +23,7 @@ pub(crate) struct PasswordConfirm {
impl Component for PasswordConfirm {
// Las etiquetas por defecto cubren los dos casos más habituales (alta de cuenta, alta de
// usuario desde administración); `with_password_label()` cubre los casos distintos
// (restablecimiento por un administrador y cambio de la contraseña propia).
// (restablecimientos y cambio de la contraseña propia).
fn new() -> Self {
Self {
password_label: Lc::t("field-password", &LOCALES_USER),
@ -30,10 +32,19 @@ impl Component for PasswordConfirm {
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
// `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,
// pero nunca al revés.
let min_length = SETTINGS.password.min_length;
let mut password = form::input::Field::password()
.with_name("password")
.with_label(self.password_label().clone())
.with_help_text(
Lc::t("help-password-min-length", &LOCALES_USER)
.with_number("n", u32::try_from(min_length).unwrap_or(u32::MAX)),
)
.with_autocomplete(Some(form::Autocomplete::new_password()))
.with_minlength(u16::try_from(min_length).unwrap_or(u16::MAX))
.with_required(true);
let mut confirm = form::input::Field::password()
.with_name("confirm_password")

View file

@ -3,7 +3,7 @@
use pagetop::prelude::*;
use crate::LOCALES_USER;
use crate::component::error_banner;
use crate::component::{PasswordConfirm, error_banner};
#[derive(AutoDefault, Clone, Debug)]
pub struct PasswordResetConfirmForm {
@ -24,19 +24,8 @@ impl Component for PasswordResetConfirmForm {
.with_method(form::Method::Post)
.with_child(error_banner(self.error.clone()))
.with_child(
form::input::Field::password()
.with_name("password")
.with_label(Lc::t("field-new-password", &LOCALES_USER))
.with_autocomplete(Some(form::Autocomplete::new_password()))
.with_autofocus(true)
.with_required(true),
)
.with_child(
form::input::Field::password()
.with_name("confirm_password")
.with_label(Lc::t("field-confirm-password", &LOCALES_USER))
.with_autocomplete(Some(form::Autocomplete::new_password()))
.with_required(true),
PasswordConfirm::new()
.with_password_label(Lc::t("field-new-password", &LOCALES_USER)),
)
.with_child(Button::submit(Lc::t("btn-set-password", &LOCALES_USER)));

View file

@ -5,10 +5,14 @@ use pagetop::prelude::*;
use crate::LOCALES_USER;
use crate::REGISTER_PATH;
use crate::component::{PasswordConfirm, error_banner};
use crate::config::SETTINGS;
use crate::identity::{EMAIL_MAX_CHARS, USERNAME_MIN_CHARS, username_help, username_max_chars};
#[derive(AutoDefault, Clone, Debug)]
pub struct RegisterForm {
error: Option<Lc>,
username: String,
email: String,
}
#[async_trait]
@ -26,7 +30,11 @@ impl Component for RegisterForm {
.with_child(
form::input::Field::text()
.with_name("username")
.with_label(Lc::t("field-username", &LOCALES_USER))
.with_value(&self.username)
.with_label(Lc::t("field-username-admin", &LOCALES_USER))
.with_help_text(username_help(SETTINGS.identity_policy))
.with_minlength(USERNAME_MIN_CHARS)
.with_maxlength(username_max_chars(SETTINGS.identity_policy))
.with_autocomplete(Some(form::Autocomplete::username()))
.with_autofocus(true)
.with_required(true),
@ -34,7 +42,9 @@ impl Component for RegisterForm {
.with_child(
form::input::Field::email()
.with_name("email")
.with_value(&self.email)
.with_label(Lc::t("field-email", &LOCALES_USER))
.with_maxlength(EMAIL_MAX_CHARS)
.with_autocomplete(Some(form::Autocomplete::email()))
.with_required(true),
)
@ -51,4 +61,16 @@ impl RegisterForm {
self.error = error.into();
self
}
/// Rellena el nombre de usuario, p. ej. con el enviado si el registro falla.
pub fn with_username(mut self, username: impl Into<String>) -> Self {
self.username = username.into();
self
}
/// Rellena el email, p. ej. con el enviado si el registro falla.
pub fn with_email(mut self, email: impl Into<String>) -> Self {
self.email = email.into();
self
}
}