✨ (user): Añade proveedores de autenticación

Otras extensiones pueden comprobar las credenciales del inicio de sesión
con un servicio externo (un directorio LDAP...): módulo público provider
(AuthProvider, ProviderHandle, AccountPolicy, DeclareAuthProviders),
tabla `user_identities`, sección `[user.login]` (sources, local_fallback
y strict, que sustituye a login_strict), estado AwaitingApproval y
acciones AfterSessionResolved, AfterUserStatusChanged y
AdminUserFormExtras.

Las reglas que protegen las cuentas son siempre de pagetop-user: sólo se
vincula una cuenta que un administrador ha permitido para esa persona,
nunca la de un administrador, y una caída del proveedor no bloquea a
nadie.

Añade el límite de fallos por identificador tecleado, guarda las
contraseñas en util::SecretStr, crea en una sola transacción las cuentas
de proveedor y documenta todos los elementos públicos del crate.
This commit is contained in:
Manuel Cillero 2026-11-12 23:13:58 +01:00
parent 9a78b79939
commit 5172da65d6
39 changed files with 4711 additions and 310 deletions

View file

@ -43,12 +43,28 @@ pub(crate) type PermissionGroups = Vec<(Lc, Vec<PermissionItem>)>;
// rol "authenticated" no se lista como casilla ni se envía: todo usuario autenticado lo tiene
// concedido por definición (ver `session::load_user_from_session`), sin necesidad de una fila en
// `user_role`.
pub(crate) fn roles_fieldset(roles: &[(i32, String, bool)]) -> form::Fieldset {
//
// Los roles de `managed` los asigna el proveedor `provider` que gestiona la cuenta: se muestran
// deshabilitados, con una nota, y quien recibe el formulario los conserva como estén.
pub(crate) fn roles_fieldset(
roles: &[(i32, String, bool)],
managed: &[i32],
provider: &str,
) -> form::Fieldset {
let mut field = form::check::Field::new().with_name("role_ids");
for (role_id, label, checked) in roles {
let is_managed = managed.contains(role_id);
let label = if is_managed {
Lc::t("value-role-managed", &LOCALES_USER)
.with_arg("role", label.clone())
.with_arg("provider", provider.to_owned())
} else {
Lc::n(label.clone())
};
field = field.with_item(
form::check::Item::new(role_id.to_string(), Lc::n(label.clone()))
.with_checked(*checked),
form::check::Item::new(role_id.to_string(), label)
.with_checked(*checked)
.with_disabled(is_managed),
);
}
form::Fieldset::new()

View file

@ -9,6 +9,7 @@ use crate::{ADMIN_USERS_PATH, PROFILE_EDIT_PATH};
use crate::component::{PasswordConfirm, error_banner, form_actions, profile_form_actions};
use crate::identity::{EMAIL_MAX_CHARS, USERNAME_MIN_CHARS, username_help, username_max_chars};
use crate::provider::{AccountPolicy, UserField};
use crate::service::user_admin::{ABOUT_MAX_CHARS, DISPLAY_NAME_MAX_CHARS};
use super::{USER_ADMIN_FORM_ID, roles_fieldset};
@ -42,6 +43,11 @@ pub(crate) struct UserForm {
/// En modo `Profile`, si el nombre de usuario es editable; si no, se muestra de sólo lectura.
allow_username_field: bool,
is_admin: bool,
/// Política del proveedor que gestiona la cuenta, si lo hay: los datos que gestiona se muestran
/// de sólo lectura (y quien recibe el formulario los ignora).
policy: Option<AccountPolicy>,
/// En modo `New`, el proveedor con el que entrará la cuenta (`(id, nombre)`): sin contraseña.
provider: Option<(String, String)>,
}
#[async_trait]
@ -56,11 +62,29 @@ impl Component for UserForm {
UserFormMode::Edit => user_path(self.user_id().copied().unwrap_or_default(), "edit"),
UserFormMode::Profile => PROFILE_EDIT_PATH.into(),
};
let username_readonly =
*self.mode() == UserFormMode::Profile && !*self.allow_username_field();
let policy = self.policy();
let managed = |field: UserField| policy.is_some_and(|p| p.manages(field));
let managed_help = match policy {
Some(p) => Lc::t("help-managed-by", &LOCALES_USER).with_arg(
"provider",
p.provider_label().lookup(cx).unwrap_or_default(),
),
None => Lc::none(),
};
let help = |readonly: bool| {
if readonly {
managed_help.clone()
} else {
Lc::none()
}
};
let username_managed = policy.is_some_and(|p| !p.username().is_editable());
let username_readonly = username_managed
|| (*self.mode() == UserFormMode::Profile && !*self.allow_username_field());
// El propio usuario cambia su email en otra pantalla, que pide su contraseña y confirma la
// nueva dirección antes de aplicarla.
let email_readonly = *self.mode() == UserFormMode::Profile;
let email_managed = policy.is_some_and(|p| !p.email().is_editable());
let email_readonly = email_managed || *self.mode() == UserFormMode::Profile;
let action = cx.route(action);
let mut form = Form::new()
@ -73,7 +97,9 @@ 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 {
.with_help_text(if username_managed {
managed_help.clone()
} else if username_readonly {
Lc::none()
} else {
username_help(SETTINGS.identity_policy)
@ -88,7 +114,9 @@ impl Component for UserForm {
.with_name("email")
.with_value(self.email())
.with_label(Lc::t("field-email", &LOCALES_USER))
.with_help_text(if email_readonly {
.with_help_text(if email_managed {
managed_help.clone()
} else if email_readonly {
Lc::t("help-email-readonly", &LOCALES_USER)
} else {
Lc::none()
@ -102,6 +130,8 @@ impl Component for UserForm {
.with_name("display_name")
.with_value(self.display_name())
.with_label(Lc::t("field-display-name", &LOCALES_USER))
.with_help_text(help(managed(UserField::DisplayName)))
.with_readonly(managed(UserField::DisplayName))
.with_maxlength(DISPLAY_NAME_MAX_CHARS),
);
@ -112,6 +142,7 @@ impl Component for UserForm {
form::SelectLanguage::new()
.with_name("language")
.with_label(Lc::t("field-language", &LOCALES_USER))
.with_disabled(managed(UserField::Language))
.with_selected(self.language()),
);
}
@ -121,6 +152,7 @@ impl Component for UserForm {
.with_name("timezone")
.with_label(Lc::t("field-timezone", &LOCALES_USER))
.with_utc_offset(true)
.with_disabled(managed(UserField::Timezone))
.with_selected(self.timezone()),
);
}
@ -128,24 +160,47 @@ impl Component for UserForm {
form::SelectTheme::new()
.with_name("theme")
.with_label(Lc::t("field-theme", &LOCALES_USER))
.with_disabled(managed(UserField::Theme))
.with_selected(self.theme()),
);
if *self.mode() == UserFormMode::New {
form = form.with_child(PasswordConfirm::new());
} else {
form = form.with_child(
form::Textarea::new()
.with_name("about")
.with_value(self.about())
.with_label(Lc::t("field-about", &LOCALES_USER))
.with_rows(Some(5))
.with_maxlength(Some(ABOUT_MAX_CHARS)),
);
match (self.mode(), self.provider()) {
// Una cuenta que entrará con un proveedor no tiene contraseña local.
(UserFormMode::New, Some((id, name))) => {
form = form
.with_child(form::Hidden::field("provider", id.as_str()))
.with_child(Html::with({
let note = Lc::t("help-external-user", &LOCALES_USER)
.with_arg("provider", name.clone());
move |cx| html! { p { (note.using(cx)) } }
}));
}
(UserFormMode::New, None) => {
form = form.with_child(PasswordConfirm::new());
}
_ => {
form = form.with_child(
form::Textarea::new()
.with_name("about")
.with_value(self.about())
.with_label(Lc::t("field-about", &LOCALES_USER))
.with_help_text(help(managed(UserField::About)))
.with_readonly(managed(UserField::About))
.with_rows(Some(5))
.with_maxlength(Some(ABOUT_MAX_CHARS)),
);
}
}
if *self.mode() != UserFormMode::Profile && !self.roles().is_empty() {
form = form.with_child(roles_fieldset(self.roles()));
let (managed_roles, provider) = match policy {
Some(p) => (
p.managed_roles(),
p.provider_label().lookup(cx).unwrap_or_default(),
),
None => (&[][..], String::new()),
};
form = form.with_child(roles_fieldset(self.roles(), managed_roles, &provider));
}
if *self.mode() == UserFormMode::New && *self.allow_admin_field() {
@ -248,4 +303,14 @@ impl UserForm {
self.is_admin = is_admin;
self
}
pub(crate) fn with_policy(mut self, policy: Option<AccountPolicy>) -> Self {
self.policy = policy;
self
}
pub(crate) fn with_provider(mut self, provider: Option<(String, String)>) -> Self {
self.provider = provider;
self
}
}

View file

@ -7,6 +7,7 @@ use pagetop_htmx::hx_table::sort_link;
use crate::ADMIN_USERS_PATH;
use crate::LOCALES_USER;
use crate::account::{Account, UserStatus};
use crate::provider;
use crate::service::user_admin::{UserListItem, UserSortField};
use crate::user_path;
@ -68,12 +69,23 @@ impl Component for UserTable {
let new_href = cx.route(util::join!(ADMIN_USERS_PATH.as_str(), "/new"));
let mut list = ListView::new()
.with_id("user-table-wrapper")
.with_action(
Button::anchor(Lc::t("btn-create-user", &LOCALES_USER), new_href)
.with_style(button::Style::Solid(Intent::Primary)),
)
let mut list = ListView::new().with_id("user-table-wrapper").with_action(
Button::anchor(Lc::t("btn-create-user", &LOCALES_USER), new_href.clone())
.with_style(button::Style::Solid(Intent::Primary)),
);
// Alta de una cuenta que entrará con un proveedor de autenticación (ver `new_get()`).
for provider in provider::active_providers() {
let name = provider.label().lookup(cx).unwrap_or_default();
let href = new_href.clone().with_param("provider", provider.id());
list = list.with_action(
Button::anchor(
Lc::t("btn-create-external-user", &LOCALES_USER).with_arg("provider", name),
href,
)
.with_style(button::Style::Solid(Intent::Neutral)),
);
}
let mut list = list
.with_table(table)
.with_pager(hx_pager::boost(pager, "#user-table-wrapper"));
Ok(list.render(cx).await)
@ -221,5 +233,6 @@ pub(crate) fn status_key(status: UserStatus) -> &'static str {
UserStatus::Active => "status-active",
UserStatus::Blocked => "status-blocked",
UserStatus::Pending => "status-pending",
UserStatus::AwaitingApproval => "status-awaiting-approval",
}
}

View file

@ -4,11 +4,23 @@ use pagetop::prelude::*;
use crate::component::error_banner;
use crate::config::SETTINGS;
use crate::provider::{self, HelpLink, ResetLink};
use crate::{LOCALES_USER, LOGIN_PATH, PASSWORD_RESET_PATH, REGISTER_PATH};
/// Formulario de inicio de sesión.
///
/// Además de los campos de usuario y contraseña, muestra lo que piden los proveedores de
/// autenticación activos (ver
/// [`AuthProvider::login_hints()`](crate::provider::AuthProvider::login_hints)): su nota bajo el
/// formulario y, si `"local"` no está en `[user.login] sources`, su enlace para recuperar la
/// contraseña en lugar del de `pagetop-user`. La casilla «Recuérdame» sólo aparece si alguna fuente
/// la admite.
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct LoginForm {
/// Mensaje de error sobre el formulario.
error: Option<Lc>,
/// Enlace de ayuda junto al error (p. ej. dónde cambiar una contraseña caducada).
help: Option<HelpLink>,
/// Usuario o email con el que se rellena el campo.
username: String,
/// Página a la que volver tras iniciar sesión.
@ -23,7 +35,8 @@ impl Component for LoginForm {
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let action = self.waypoint().append_to(cx.route(LOGIN_PATH));
let strict = SETTINGS.login_strict;
let strict = SETTINGS.login.strict;
let (notes, reset) = provider::login_hints();
// En modo estricto se dificulta que el navegador recuerde o autorrellene las
// credenciales: nombres de campo neutros y campos `Field::strict_text()`/
@ -54,19 +67,23 @@ impl Component for LoginForm {
.with_action(action)
.with_method(form::Method::Post)
.with_child(error_banner(self.error().cloned()))
.with_child(help_link(self.help().cloned()))
.with_child(username)
.with_child(password)
.with_child(
.with_child(password);
if provider::any_allows_remember() {
form = form.with_child(
form::Checkbox::check()
.with_name("remember")
.with_label(Lc::t("field-remember-me", &LOCALES_USER))
.with_help_text(Lc::t("help-remember-me", &LOCALES_USER)),
)
);
}
form = form
.with_child(
Button::submit(Lc::t("btn-login", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
)
.with_child(links(SETTINGS.allow_registration));
.with_child(links(SETTINGS.allow_registration, notes, reset));
if strict {
form = form
@ -85,9 +102,12 @@ impl Component for LoginForm {
}
}
fn links(allow_registration: bool) -> Html {
fn links(allow_registration: bool, notes: Vec<Lc>, reset: ResetLink) -> Html {
Html::with(move |cx| {
html! {
@for note in &notes {
p class="user-login-note" { (note.using(cx)) }
}
@if allow_registration {
p class="user-register-link" {
a href=(cx.route(REGISTER_PATH)) {
@ -95,22 +115,61 @@ fn links(allow_registration: bool) -> Html {
}
}
}
p class="user-reset-link" {
a href=(cx.route(PASSWORD_RESET_PATH)) {
(Lc::t("link-forgot-password", &LOCALES_USER).using(cx))
@match &reset {
ResetLink::Local => {
p class="user-reset-link" {
a href=(cx.route(PASSWORD_RESET_PATH)) {
(Lc::t("link-forgot-password", &LOCALES_USER).using(cx))
}
}
}
ResetLink::External(help) => {
p class="user-reset-link" {
a href=(help.url()) {
@match help.text().lookup(cx) {
Some(text) => (text),
None => (Lc::t("link-forgot-password", &LOCALES_USER).using(cx)),
}
}
}
}
ResetLink::Hidden => {}
}
}
})
}
// Enlace de ayuda que acompaña a un error, si lo hay.
fn help_link(help: Option<HelpLink>) -> Html {
Html::with(move |cx| match &help {
Some(help) => html! {
p class="user-login-help" {
a href=(help.url()) {
@match help.text().lookup(cx) {
Some(text) => (text),
None => (help.url()),
}
}
}
},
None => html! {},
})
}
#[builder_impl]
impl LoginForm {
/// Mensaje de error sobre el formulario, p. ej. el del envío que ha fallado.
pub fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into();
self
}
/// Enlace de ayuda junto al error.
pub fn with_help(mut self, help: impl Into<Option<HelpLink>>) -> Self {
self.help = help.into();
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();

View file

@ -5,6 +5,10 @@ use pagetop::prelude::*;
use crate::LOCALES_USER;
use crate::component::{PasswordConfirm, error_banner};
/// Formulario para elegir la nueva contraseña desde el enlace de recuperación.
///
/// Pide la contraseña y su confirmación, y se envía a la propia página del enlace, cuya dirección
/// lleva la cuenta y el *token*: sólo funciona dentro de ella.
#[derive(AutoDefault, Clone, Debug)]
pub struct PasswordResetConfirmForm {
error: Option<Lc>,
@ -38,6 +42,7 @@ impl Component for PasswordResetConfirmForm {
#[builder_impl]
impl PasswordResetConfirmForm {
/// Mensaje de error sobre el formulario, p. ej. el del envío que ha fallado.
pub fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into();
self

View file

@ -5,6 +5,11 @@ use pagetop::prelude::*;
use crate::component::error_banner;
use crate::{LOCALES_USER, LOGIN_PATH, PASSWORD_RESET_PATH};
/// Formulario para pedir la recuperación de la contraseña.
///
/// Pide el email de la cuenta y lo envía a `/user/password/reset`, que, si es de una cuenta activa,
/// manda por correo el enlace para elegir una nueva (o un aviso, si la contraseña la gestiona un
/// proveedor de autenticación). La respuesta es la misma exista o no la cuenta.
#[derive(AutoDefault, Clone, Debug)]
pub struct PasswordResetForm {
error: Option<Lc>,
@ -54,6 +59,7 @@ fn back_to_login() -> Html {
#[builder_impl]
impl PasswordResetForm {
/// Mensaje de error sobre el formulario, p. ej. el del envío que ha fallado.
pub fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into();
self

View file

@ -8,6 +8,11 @@ use crate::component::{PasswordConfirm, error_banner};
use crate::config::SETTINGS;
use crate::identity::{EMAIL_MAX_CHARS, USERNAME_MIN_CHARS, username_help, username_max_chars};
/// Formulario de registro de una cuenta nueva.
///
/// Pide el nombre de usuario (con las reglas de la política de identidad configurada), el email y
/// la contraseña con su confirmación, y se envía a `/user/register`, que sólo admite registros con
/// [`allow_registration`](crate::config::UserSettings::allow_registration).
#[derive(AutoDefault, Clone, Debug)]
pub struct RegisterForm {
error: Option<Lc>,
@ -60,6 +65,7 @@ impl Component for RegisterForm {
#[builder_impl]
impl RegisterForm {
/// Mensaje de error sobre el formulario, p. ej. el del envío que ha fallado.
pub fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into();
self

View file

@ -6,12 +6,12 @@ use crate::Account;
use crate::permission::UserPermission;
use crate::profile_path;
/// Componente para mostrar el **nombre de un usuario**, enlazado a su perfil público cuando quien
/// mira puede verlo.
/// Componente para mostrar el **nombre de un usuario**.
///
/// Se renderiza como enlace a `/user/{id}` si quien hace la petición tiene `user:view_profiles` o
/// es el propio usuario; si no, como texto. Las propiedades del componente (identificador, clases,
/// atributos) se aplican en ambos casos.
/// Enlaza con su perfil público, siempre que quien mira pueda verlo. Se renderiza como enlace a
/// `/user/{id}` si quien hace la petición tiene `user:view_profiles` o es el propio usuario; si no,
/// como texto. Las propiedades del componente (identificador, clases, atributos) se aplican en
/// ambos casos.
///
/// Recibe el identificador y el nombre que el llamador ya tiene de su propia consulta, así que no
/// consulta la base de datos al renderizarse. El nombre suele ser el nombre visible del usuario o,