✨ (user): Asigna roles desde la edición de usuario

This commit is contained in:
Manuel Cillero 2026-10-05 00:36:47 +02:00
parent 806ed9e0dc
commit f819181872
26 changed files with 1219 additions and 544 deletions

View file

@ -7,7 +7,6 @@ mod role_form;
mod role_permissions_form;
mod role_table;
mod user_form;
mod user_roles_form;
mod user_table;
pub(crate) use admin_password_form::AdminPasswordForm;
@ -15,7 +14,6 @@ pub(crate) use role_form::{RoleForm, RoleFormMode};
pub(crate) use role_permissions_form::RolePermissionsForm;
pub(crate) use role_table::RoleTable;
pub(crate) use user_form::{UserForm, UserFormMode};
pub(crate) use user_roles_form::UserRolesForm;
pub(crate) use user_table::{UserTable, status_key};
use pagetop::prelude::*;
@ -41,10 +39,10 @@ pub(crate) type PermissionGroups = Vec<(Lc, Vec<PermissionItem>)>;
// **< HELPERS >************************************************************************************
// `Fieldset` con las casillas para asignar roles (usado en el alta de usuario y en la pantalla de
// asignación de roles). El 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`.
// `Fieldset` con las casillas para asignar roles (usado en el alta y en la edición de usuario). El
// 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 {
let mut field = form::check::Field::new().with_name("role_ids");
for (role_id, label, checked) in roles {

View file

@ -1,49 +1,23 @@
//! Formulario de alta/edición de usuario.
use std::collections::BTreeMap;
use std::sync::LazyLock;
//! Formulario de alta/edición de usuario, también usado para que cada usuario edite su perfil.
use pagetop::prelude::*;
use crate::ADMIN_USERS_PATH;
use crate::LOCALES_USER;
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 super::{USER_ADMIN_FORM_ID, roles_fieldset};
// Regiones de la base IANA que sólo contienen alias heredados (fichero `backward`), todos con una
// zona canónica equivalente en otra región (p. ej. `US/Eastern` es `America/New_York`).
const LEGACY_REGIONS: [&str; 5] = ["Brazil", "Canada", "Chile", "Mexico", "US"];
// Zonas horarias IANA canónicas agrupadas por región (lo anterior a la primera `/`), ordenadas por
// región y nombre. Se descartan los alias heredados: los nombres sin región (`GB`, `Japan`,
// `EST5EDT`...), los de `LEGACY_REGIONS` y los de `Etc` salvo `Etc/UTC`, cuyo grupo va al final.
static TZ_BY_REGION: LazyLock<Vec<(&'static str, Vec<&'static str>)>> = LazyLock::new(|| {
let mut regions: BTreeMap<&'static str, Vec<&'static str>> = BTreeMap::new();
for tz in TZ_VARIANTS.iter() {
let name = tz.name();
let Some((region, _)) = name.split_once('/') else {
continue;
};
if LEGACY_REGIONS.contains(&region) || (region == "Etc" && name != "Etc/UTC") {
continue;
}
regions.entry(region).or_default().push(name);
}
for names in regions.values_mut() {
names.sort_unstable();
}
let etc = regions.remove_entry("Etc");
regions.into_iter().chain(etc).collect()
});
#[derive(AutoDefault, Clone, Copy, Debug, PartialEq)]
pub(crate) enum UserFormMode {
#[default]
New,
Edit,
/// Edición del perfil propio: sin roles ni casilla de administrador.
Profile,
}
#[derive(AutoDefault, Clone, Debug, Getters)]
@ -56,12 +30,17 @@ pub(crate) struct UserForm {
username: String,
email: String,
display_name: String,
/// Texto "Sobre mí"; sólo se edita en los modos `Edit` y `Profile`, no en el alta.
about: String,
language: String,
timezone: String,
/// Roles asignables (excluye "anonymous" y "authenticated"); sólo se renderiza en modo `New`.
theme: String,
/// Roles asignables (excluye "anonymous" y "authenticated"); si no hay ninguno, no se muestra.
roles: Vec<(i32, String, bool)>,
/// Si se ofrece la casilla "administrador"; sólo cuando quien da de alta ya es administrador.
allow_admin_field: bool,
/// 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,
}
@ -75,7 +54,10 @@ impl Component for UserForm {
let action = match self.mode() {
UserFormMode::New => util::join!(ADMIN_USERS_PATH, "/new"),
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 action = self.waypoint().append_to(cx.route(action));
let mut form = Form::new()
@ -89,6 +71,7 @@ impl Component for UserForm {
.with_value(self.username())
.with_label(Lc::t("field-username-admin", &LOCALES_USER))
.with_required(true)
.with_readonly(username_readonly)
.with_maxlength(Some(64)),
)
.with_child(
@ -105,33 +88,54 @@ impl Component for UserForm {
.with_label(Lc::t("field-display-name", &LOCALES_USER)),
)
.with_child(
form::input::Field::text()
form::SelectLanguage::new()
.with_name("language")
.with_value(self.language())
.with_label(Lc::t("field-language", &LOCALES_USER)),
.with_label(Lc::t("field-language", &LOCALES_USER))
.with_selected(self.language()),
)
.with_child(timezone_field(self.timezone()));
.with_child(
form::SelectTimezone::new()
.with_name("timezone")
.with_label(Lc::t("field-timezone", &LOCALES_USER))
.with_selected(self.timezone()),
)
.with_child(
form::SelectTheme::new()
.with_name("theme")
.with_label(Lc::t("field-theme", &LOCALES_USER))
.with_selected(self.theme()),
);
if *self.mode() == UserFormMode::New {
form = form.with_child(PasswordConfirm::new());
if !self.roles().is_empty() {
form = form.with_child(roles_fieldset(self.roles()));
}
} 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)),
);
}
if *self.allow_admin_field() {
form = form.with_child(
form::Checkbox::check()
.with_name("is_admin")
.with_label(Lc::t("field-is-admin", &LOCALES_USER))
.with_checked(*self.is_admin()),
);
}
if *self.mode() != UserFormMode::Profile && !self.roles().is_empty() {
form = form.with_child(roles_fieldset(self.roles()));
}
if *self.mode() == UserFormMode::New && *self.allow_admin_field() {
form = form.with_child(
form::Checkbox::check()
.with_name("is_admin")
.with_label(Lc::t("field-is-admin", &LOCALES_USER))
.with_checked(*self.is_admin()),
);
}
// En modo `Edit`, "Guardar" se renderiza fuera del formulario, junto al resto de acciones
// de la pantalla (ver `USER_ADMIN_FORM_ID`); en modo `New` no hay ninguna botonera con la
// que agruparlo, así que se queda aquí, dentro del propio `<form>`.
if *self.mode() == UserFormMode::New {
// de la pantalla (ver `USER_ADMIN_FORM_ID`); en los demás modos no hay ninguna botonera con
// la que agruparlo, así que se queda aquí, dentro del propio `<form>`.
if *self.mode() != UserFormMode::Edit {
form = form.with_child(
Button::submit(Lc::t("btn-save", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
@ -181,6 +185,11 @@ impl UserForm {
self
}
pub(crate) fn with_about(mut self, about: impl Into<String>) -> Self {
self.about = about.into();
self
}
pub(crate) fn with_language(mut self, language: impl Into<String>) -> Self {
self.language = language.into();
self
@ -191,6 +200,11 @@ impl UserForm {
self
}
pub(crate) fn with_theme(mut self, theme: impl Into<String>) -> Self {
self.theme = theme.into();
self
}
pub(crate) fn with_roles(mut self, roles: Vec<(i32, String, bool)>) -> Self {
self.roles = roles;
self
@ -201,34 +215,13 @@ impl UserForm {
self
}
pub(crate) fn with_allow_username_field(mut self, allow_username_field: bool) -> Self {
self.allow_username_field = allow_username_field;
self
}
pub(crate) fn with_is_admin(mut self, is_admin: bool) -> Self {
self.is_admin = is_admin;
self
}
}
// `<select>` de zona horaria: primero la opción de usar la predeterminada de la aplicación y luego
// un `<optgroup>` por región. La etiqueta de cada opción es el nombre IANA completo.
fn timezone_field(selected: &str) -> form::select::Field {
let mut field = form::select::Field::new()
.with_name("timezone")
.with_label(Lc::t("field-timezone", &LOCALES_USER))
.with_item(
form::select::Item::new(
"",
Lc::t("field-timezone-site-default", &LOCALES_USER)
.with_arg("tz", Timezone::default_tz().name()),
)
.with_selected(selected.is_empty()),
);
for (region, names) in TZ_BY_REGION.iter() {
let mut group = form::select::Group::new(Lc::n(*region));
for name in names {
group = group.with_item(
form::select::Item::new(*name, Lc::n(*name)).with_selected(*name == selected),
);
}
field = field.with_group(group);
}
field
}

View file

@ -1,69 +0,0 @@
//! Formulario de asignación de roles a un usuario. Reemplaza siempre el conjunto completo.
use pagetop::prelude::*;
use crate::LOCALES_USER;
use crate::user_path;
use crate::component::error_banner;
use super::roles_fieldset;
#[derive(AutoDefault, Clone, Debug, Getters)]
pub(crate) struct UserRolesForm {
user_id: i32,
error: Option<Lc>,
roles: Vec<(i32, String, bool)>,
/// Listado de origen al que volver tras guardar (orden, búsqueda, página).
waypoint: Waypoint,
}
#[async_trait]
impl Component for UserRolesForm {
fn new() -> Self {
Self::default()
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let action = user_path(self.user_id(), "roles");
let action = self.waypoint().append_to(cx.route(action));
let mut form = Form::new()
.with_id("user-roles-form")
.with_action(action)
.with_method(form::Method::Post)
.with_child(error_banner(self.error().cloned()))
.with_child(roles_fieldset(self.roles()))
.with_child(
Button::submit(Lc::t("btn-save", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
);
Ok(form.render(cx).await)
}
}
#[builder_impl]
impl UserRolesForm {
// **< UserRolesForm BUILDER >******************************************************************
pub(crate) fn with_user_id(mut self, user_id: i32) -> Self {
self.user_id = user_id;
self
}
pub(crate) fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into();
self
}
pub(crate) fn with_roles(mut self, roles: Vec<(i32, String, bool)>) -> Self {
self.roles = roles;
self
}
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
self.waypoint = waypoint.into();
self
}
}

View file

@ -6,9 +6,7 @@ use pagetop_htmx::hx_table::sort_link;
use crate::ADMIN_USERS_PATH;
use crate::LOCALES_USER;
use crate::account::UserStatus;
use crate::handlers::admin::users::available_roles;
use crate::permission::UserPermission;
use crate::account::{Account, UserStatus};
use crate::service::user_admin::{UserListItem, UserSortField};
use crate::user_path;
@ -66,14 +64,10 @@ impl Component for UserTable {
.with_empty(Lc::t("empty-users-list", &LOCALES_USER));
let waypoint = Waypoint::from(self.list_href(cx));
let can_assign_roles = cx
let viewer_is_admin = cx
.request()
.is_some_and(|r| has_permission(r, &UserPermission::AssignRoles));
// Sólo hace falta consultar si hay algún rol asignable cuando el botón vaya a mostrarse.
let has_assignable_roles = can_assign_roles
&& available_roles(&[])
.await
.is_ok_and(|roles| !roles.is_empty());
.and_then(|r| r.extension::<Account>())
.is_some_and(|a| a.is_admin());
for user in self.items() {
let status = user.status;
@ -85,10 +79,7 @@ impl Component for UserTable {
.with_cell(user.display_name.as_deref().unwrap_or("-"))
.with_cell(roles_cell(user, cx).await)
.with_cell(Lc::t(status_key(status), &LOCALES_USER))
.with_cell(
actions_cell(user, &waypoint, can_assign_roles, has_assignable_roles, cx)
.await,
),
.with_cell(actions_cell(user, &waypoint, viewer_is_admin, cx).await),
);
}
@ -207,19 +198,20 @@ fn username_cell(user: &UserListItem, waypoint: &Waypoint) -> Html {
})
}
// Construye la celda de acciones: editar siempre, y gestionar roles sólo si el usuario autenticado
// tiene permiso para asignarlos; en ese caso, deshabilitado si no hay ningún rol asignable en todo
// el sistema. Devuelve un componente `Html` para que el marcado se genere cuando `Table` renderice
// la celda, no al construir la fila.
// Construye la celda de acciones con el botón de edición, salvo en la cuenta de un administrador
// si quien mira no lo es (no puede gestionarla, ver `handlers::admin::users::require_manageable`).
// Devuelve un componente `Html` para que el marcado se genere cuando `Table` renderice la celda, no
// al construir la fila.
async fn actions_cell(
user: &UserListItem,
waypoint: &Waypoint,
can_assign_roles: bool,
has_assignable_roles: bool,
viewer_is_admin: bool,
cx: &mut Context,
) -> Html {
let id = user.id;
let edit_href = waypoint.append_to(cx.route(user_path(id, "edit")));
if user.is_admin && !viewer_is_admin {
return Html::default();
}
let edit_href = waypoint.append_to(cx.route(user_path(user.id, "edit")));
// El botón se renderiza aquí, no dentro del `Html::with()` de abajo: necesita pasar por su
// propio ciclo de renderizado (`.render().await`) para que el tema activo lo estilice igual
@ -230,62 +222,33 @@ async fn actions_cell(
.render(cx)
.await;
let roles_button = if can_assign_roles {
let roles_href = waypoint.append_to(cx.route(user_path(id, "roles")));
Some(
Button::anchor(Lc::t("btn-manage-roles", &LOCALES_USER), roles_href)
.with_style(button::Style::Solid(Intent::Neutral))
.with_size(button::Size::Small)
.with_disabled(!has_assignable_roles)
.render(cx)
.await,
)
} else {
None
};
Html::with(move |_cx| {
html! {
(edit_button)
@if let Some(roles_button) = &roles_button {
" "
(roles_button)
}
}
})
Html::with(move |_cx| edit_button.clone())
}
// Construye la celda de roles: la insignia de administrador y las insignias de cada rol asignado,
// o "-" si el usuario no tiene ningún rol ni es administrador. Los badges se renderizan aquí mismo
// (con el `cx` del ciclo de renderizado de `Table`); el resto del marcado se difiere al `Html` que
// se devuelve, igual que el resto de celdas.
// Construye la celda de roles: sólo la insignia de administrador si lo es (tiene acceso sin
// restricciones, así que sus roles no añaden nada), o las insignias de cada rol asignado, o "-" si
// no tiene ninguno. Los badges se renderizan aquí mismo (con el `cx` del ciclo de renderizado de
// `Table`); el resto del marcado se difiere al `Html` que se devuelve, igual que el resto de celdas.
async fn roles_cell(user: &UserListItem, cx: &mut Context) -> Html {
let admin_badge = if user.is_admin {
Some(
let mut badges = Vec::with_capacity(user.roles.len().max(1));
if user.is_admin {
badges.push(
Badge::severe(Lc::t("badge-admin", &LOCALES_USER))
.render(cx)
.await,
)
);
} else {
None
};
let mut role_badges = Vec::with_capacity(user.roles.len());
for role in &user.roles {
role_badges.push(Badge::neutral(Lc::n(role.clone())).render(cx).await);
for role in &user.roles {
badges.push(Badge::neutral(Lc::n(role.clone())).render(cx).await);
}
}
let is_admin = user.is_admin;
Html::with(move |_cx| {
html! {
@if let Some(badge) = &admin_badge {
(badge)
" "
}
@if role_badges.is_empty() {
@if !is_admin { "-" }
@if badges.is_empty() {
"-"
} @else {
@for badge in &role_badges {
@for badge in &badges {
(badge)
" "
}

View file

@ -0,0 +1,56 @@
//! Formulario para que el usuario autenticado cambie su propia contraseña.
use pagetop::prelude::*;
use crate::{LOCALES_USER, PROFILE_PASSWORD_PATH};
use crate::component::{PasswordConfirm, error_banner};
/// Pide la contraseña actual además de la nueva y su confirmación, a diferencia del
/// restablecimiento por un administrador.
#[derive(AutoDefault, Clone, Debug, Getters)]
pub(crate) struct ChangePasswordForm {
error: Option<Lc>,
}
#[async_trait]
impl Component for ChangePasswordForm {
fn new() -> Self {
Self::default()
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let mut form = Form::new()
.with_id("user-change-password-form")
.with_action(cx.route(PROFILE_PASSWORD_PATH))
.with_method(form::Method::Post)
.with_child(error_banner(self.error().cloned()))
.with_child(
form::input::Field::password()
.with_name("current_password")
.with_label(Lc::t("field-current-password", &LOCALES_USER))
.with_autocomplete(Some(form::Autocomplete::current_password()))
.with_required(true),
)
.with_child(
PasswordConfirm::new()
.with_password_label(Lc::t("field-new-password", &LOCALES_USER)),
)
.with_child(
Button::submit(Lc::t("btn-set-password", &LOCALES_USER))
.with_style(button::Style::Solid(Intent::Primary)),
);
Ok(form.render(cx).await)
}
}
#[builder_impl]
impl ChangePasswordForm {
// **< ChangePasswordForm BUILDER >*************************************************************
pub(crate) fn with_error(mut self, error: impl Into<Option<Lc>>) -> Self {
self.error = error.into();
self
}
}

View file

@ -1,5 +1,5 @@
//! Par de campos "contraseña" + "confirmar contraseña", reutilizado en los formularios de
//! registro, alta y restablecimiento de contraseña.
//! registro, alta, restablecimiento y cambio de contraseña.
use pagetop::prelude::*;
@ -20,8 +20,8 @@ pub(crate) struct PasswordConfirm {
#[async_trait]
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 el caso distinto
// (restablecimiento de contraseña por un administrador).
// usuario desde administración); `with_password_label()` cubre los casos distintos
// (restablecimiento por un administrador y cambio de la contraseña propia).
fn new() -> Self {
Self {
password_label: Lc::t("field-password", &LOCALES_USER),

View file

@ -0,0 +1,109 @@
//! Nombre de un usuario enlazado a su perfil público.
use pagetop::prelude::*;
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.
///
/// 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,
/// si no tiene, su nombre de usuario.
///
/// # Ejemplo
///
/// ```rust,no_run
/// # use pagetop::prelude::*;
/// use pagetop_user::prelude::*;
///
/// // En una celda de tabla, p. ej. el autor de un cambio en un historial.
/// let row = table::Row::new()
/// .with_cell(UserName::of(42, "Ana Pérez"))
/// .with_cell("Cambio de ubicación");
/// ```
#[derive(AutoDefault, Clone, Debug, Getters)]
pub struct UserName {
/// Devuelve identificador, clases CSS, atributos HTML y valores extra del componente.
props: Props,
/// Devuelve el identificador del usuario.
user_id: i32,
/// Devuelve el nombre que se muestra.
name: String,
}
#[async_trait]
impl Component for UserName {
fn new() -> Self {
Self::default()
}
fn id(&self) -> Option<String> {
self.props.get_id()
}
fn setup(&mut self, _cx: &mut Context) {
self.alter_prop(PropsOp::prepend_classes("user-name"));
}
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
let user_id = self.user_id();
let can_view = cx.request().is_some_and(|request| {
request
.extension::<Account>()
.is_some_and(|a| a.id() == user_id)
|| has_permission(request, &UserPermission::ViewProfiles)
});
Ok(if can_view {
let href = cx.route(profile_path(user_id));
html! { a (self.props().unpack(cx)) href=(href) { (self.name()) } }
} else {
html! { span (self.props().unpack(cx)) { (self.name()) } }
})
}
}
#[builder_impl]
impl UserName {
/// Crea el nombre del usuario `user_id` con el texto indicado.
pub fn of(user_id: i32, name: impl Into<String>) -> Self {
Self {
user_id,
name: name.into(),
..Default::default()
}
}
// **< UserName BUILDER >***********************************************************************
/// Establece el identificador único del componente; igual a `with_prop(PropsOp::set_id(id))`.
pub fn with_id(mut self, id: impl Into<CowStr>) -> Self {
self.props.alter_id(id);
self
}
/// Modifica identificador, clases CSS, atributos HTML o valores extra del componente.
pub fn with_prop(mut self, op: impl Into<PropsOp>) -> Self {
self.props.alter_prop(op);
self
}
/// Establece el identificador del usuario.
pub fn with_user_id(mut self, user_id: i32) -> Self {
self.user_id = user_id;
self
}
/// Establece el nombre que se muestra.
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
}