✨ (user): Recuerda el estado de usuarios y roles
Los listados de usuarios y roles se montan con `remember_query()` y dejan de arrastrar el estado en los enlaces. La renovación de la sesión "Recuérdame" ya no se pierde cuando la respuesta fija otra cookie.
This commit is contained in:
parent
030ac92e2f
commit
84eef9ec4f
24 changed files with 251 additions and 201 deletions
|
|
@ -159,6 +159,25 @@ frenar a quien prueba unas pocas contraseñas habituales en muchas cuentas sin l
|
|||
ninguna. Detrás de un *proxy* inverso, los límites por IP requieren configurar
|
||||
`server.client_ip_header`.
|
||||
|
||||
## Cookies
|
||||
|
||||
Al iniciar sesión se crea la *cookie* de sesión (`cookie_name` de `[user.session]`, `pagetop` por
|
||||
defecto). Es propia, `HttpOnly` y con un identificador aleatorio que la aplicación guarda en la base
|
||||
de datos. Se borra al cerrar sesión.
|
||||
|
||||
Sin marcar "Recuérdame", el navegador la borra al cerrarse, y la sesión deja de valer tras
|
||||
`idle_secs` sin uso. Es una *cookie* de autenticación para un servicio que el propio usuario pide,
|
||||
así que en España y en la Unión Europea no requiere su aceptación: las normas y guías en que se basa
|
||||
están en la sección *Cookies* del módulo `web` de PageTop.
|
||||
|
||||
Con "Recuérdame", la sesión se conserva aunque se cierre el navegador, hasta `remember_idle_secs`
|
||||
sin uso (14 días por defecto). El dictamen 04/2012 del Grupo de Trabajo del Artículo 29 (WP194) no
|
||||
exime estas *cookies* de inicio de sesión persistente, pero considera suficiente que sea el usuario
|
||||
quien la pida marcando expresamente la casilla, siempre que sepa que se usa una *cookie*. Por eso el
|
||||
formulario de acceso lo indica en el texto de ayuda de la casilla, que además desaconseja marcarla
|
||||
en un equipo compartido. La aplicación sólo tiene que declararla también en su política de
|
||||
*cookies*.
|
||||
|
||||
## Créditos
|
||||
|
||||
Este *crate* guarda las contraseñas con el algoritmo Argon2 mediante
|
||||
|
|
|
|||
|
|
@ -22,6 +22,11 @@ max_ip_requests = 3
|
|||
max_ip_failed_logins = 3
|
||||
max_email_changes = 2
|
||||
|
||||
# Sesiones con "Recuérdame" renovadas en cada petición, para probar que la renovación convive con
|
||||
# otras cookies de la respuesta.
|
||||
[user.session]
|
||||
write_interval_secs = 0
|
||||
|
||||
# Costes mínimos de Argon2id: las pruebas cifran muchas contraseñas.
|
||||
[user.password]
|
||||
argon2_m_cost = 64
|
||||
|
|
|
|||
|
|
@ -11,8 +11,6 @@ use crate::component::{PasswordConfirm, error_banner, form_actions};
|
|||
pub(crate) struct AdminPasswordForm {
|
||||
user_id: i32,
|
||||
error: Option<Lc>,
|
||||
/// Listado de origen al que volver tras guardar (orden, búsqueda, página).
|
||||
waypoint: Waypoint,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
|
|
@ -23,7 +21,7 @@ impl Component for AdminPasswordForm {
|
|||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let action = user_path(self.user_id(), "password");
|
||||
let action = self.waypoint().append_to(cx.route(action));
|
||||
let action = cx.route(action);
|
||||
|
||||
let mut form = Form::new()
|
||||
.with_id("user-admin-password-form")
|
||||
|
|
@ -36,8 +34,7 @@ impl Component for AdminPasswordForm {
|
|||
)
|
||||
.with_child(form_actions(
|
||||
Lc::t("btn-save", &LOCALES_USER),
|
||||
self.waypoint()
|
||||
.append_to(cx.route(user_path(self.user_id(), "edit"))),
|
||||
cx.route(user_path(self.user_id(), "edit")),
|
||||
));
|
||||
|
||||
Ok(form.render(cx).await)
|
||||
|
|
@ -57,9 +54,4 @@ impl AdminPasswordForm {
|
|||
self.error = error.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
|
||||
self.waypoint = waypoint.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,8 +21,6 @@ pub(crate) struct RoleForm {
|
|||
mode: RoleFormMode,
|
||||
error: Option<Lc>,
|
||||
role_id: Option<i32>,
|
||||
/// Listado de origen al que volver tras guardar (orden).
|
||||
waypoint: Waypoint,
|
||||
machine_name: String,
|
||||
label: String,
|
||||
description: String,
|
||||
|
|
@ -40,7 +38,7 @@ impl Component for RoleForm {
|
|||
RoleFormMode::New => util::join!(ADMIN_ROLES_PATH.as_str(), "/new"),
|
||||
RoleFormMode::Edit => role_path(self.role_id().copied().unwrap_or_default(), "edit"),
|
||||
};
|
||||
let action = self.waypoint().append_to(cx.route(action));
|
||||
let action = cx.route(action);
|
||||
|
||||
let machine_name_field = match self.mode() {
|
||||
RoleFormMode::New => form::input::Field::text()
|
||||
|
|
@ -88,7 +86,7 @@ impl Component for RoleForm {
|
|||
|
||||
form = form.with_child(form_actions(
|
||||
Lc::t("btn-save", &LOCALES_USER),
|
||||
self.waypoint().or(cx.route(ADMIN_ROLES_PATH.as_str())),
|
||||
cx.route(ADMIN_ROLES_PATH.as_str()),
|
||||
));
|
||||
|
||||
Ok(form.render(cx).await)
|
||||
|
|
@ -114,11 +112,6 @@ impl RoleForm {
|
|||
self
|
||||
}
|
||||
|
||||
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
|
||||
self.waypoint = waypoint.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn with_machine_name(mut self, machine_name: impl Into<String>) -> Self {
|
||||
self.machine_name = machine_name.into();
|
||||
self
|
||||
|
|
|
|||
|
|
@ -17,8 +17,6 @@ pub(crate) struct RolePermissionsForm {
|
|||
role_id: i32,
|
||||
error: Option<Lc>,
|
||||
groups: PermissionGroups,
|
||||
/// Listado de origen al que volver tras guardar (orden).
|
||||
waypoint: Waypoint,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
|
|
@ -29,7 +27,7 @@ impl Component for RolePermissionsForm {
|
|||
|
||||
async fn prepare(&self, cx: &mut Context) -> Result<Markup, ComponentError> {
|
||||
let action = role_path(self.role_id(), "permissions");
|
||||
let action = self.waypoint().append_to(cx.route(action));
|
||||
let action = cx.route(action);
|
||||
|
||||
let mut form = Form::new()
|
||||
.with_id("role-permissions-form")
|
||||
|
|
@ -56,7 +54,7 @@ impl Component for RolePermissionsForm {
|
|||
|
||||
form = form.with_child(form_actions(
|
||||
Lc::t("btn-save", &LOCALES_USER),
|
||||
self.waypoint().or(cx.route(ADMIN_ROLES_PATH.as_str())),
|
||||
cx.route(ADMIN_ROLES_PATH.as_str()),
|
||||
));
|
||||
|
||||
Ok(form.render(cx).await)
|
||||
|
|
@ -81,9 +79,4 @@ impl RolePermissionsForm {
|
|||
self.groups = groups;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
|
||||
self.waypoint = waypoint.into();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,8 +46,6 @@ impl Component for RoleTable {
|
|||
.with_column(Lc::t("col-actions", &LOCALES_USER))
|
||||
.with_empty(Lc::t("empty-roles-list", &LOCALES_USER));
|
||||
|
||||
let waypoint = Waypoint::from(self.list_href(cx));
|
||||
|
||||
for role in self.items() {
|
||||
let system_badge = if role.locked {
|
||||
Some(
|
||||
|
|
@ -71,7 +69,7 @@ impl Component for RoleTable {
|
|||
table.alter_row(
|
||||
table::Row::new()
|
||||
.with_cell(role.machine_name.as_str())
|
||||
.with_cell(label_cell(role, &waypoint))
|
||||
.with_cell(label_cell(role))
|
||||
.with_cell(Html::with(move |_cx| {
|
||||
html! {
|
||||
@if let Some(badge) = &system_badge { (badge) }
|
||||
|
|
@ -80,13 +78,12 @@ impl Component for RoleTable {
|
|||
}))
|
||||
.with_cell(role.user_count.to_string())
|
||||
.with_cell(
|
||||
actions_cell(role, &waypoint, *self.sort(), *self.dir(), self.page(), cx)
|
||||
.await,
|
||||
actions_cell(role, *self.sort(), *self.dir(), self.page(), cx).await,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
let new_href = waypoint.append_to(cx.route(util::join!(ADMIN_ROLES_PATH.as_str(), "/new")));
|
||||
let new_href = cx.route(util::join!(ADMIN_ROLES_PATH.as_str(), "/new"));
|
||||
|
||||
if let Some(message) = self.message() {
|
||||
cx.push_message(MessageLevel::Error, message.clone());
|
||||
|
|
@ -160,17 +157,6 @@ impl RoleTable {
|
|||
self
|
||||
}
|
||||
|
||||
// URL del listado con el estado actual (orden, página): es el valor que viaja como `waypoint`
|
||||
// en los enlaces de ver/editar/permisos, para poder volver exactamente a este mismo estado. Se
|
||||
// construye con `cx.route()` para que preserve el parámetro `lang` cuando corresponda.
|
||||
fn list_href(&self, cx: &Context) -> String {
|
||||
cx.route(ADMIN_ROLES_PATH.as_str())
|
||||
.alter_param("sort", self.sort().as_str())
|
||||
.alter_param("dir", *self.dir())
|
||||
.alter_param("page", self.page().to_string())
|
||||
.to_string()
|
||||
}
|
||||
|
||||
// Construye la cabecera ordenable de una columna: el enlace ya funciona sin HTMX (navega con
|
||||
// una petición normal); `pagetop_htmx::hx_table::sort_link()` añade aparte los atributos `hx-*`
|
||||
// para que la tabla se actualice sin recargar la página cuando la extensión esté disponible.
|
||||
|
|
@ -199,12 +185,11 @@ impl RoleTable {
|
|||
// Construye la celda de etiqueta: enlaza a la pantalla de sólo lectura con todos los permisos del
|
||||
// rol. Devuelve un componente `Html` para que el marcado se genere cuando `Table` renderice la
|
||||
// celda, no al construir la fila.
|
||||
fn label_cell(role: &RoleListItem, waypoint: &Waypoint) -> Html {
|
||||
fn label_cell(role: &RoleListItem) -> Html {
|
||||
let label = crate::role_label(role.id, &role.label);
|
||||
let id = role.id;
|
||||
let waypoint = waypoint.clone();
|
||||
Html::with(move |cx| {
|
||||
let view_href = waypoint.append_to(cx.route(role_path(id, "view")));
|
||||
let view_href = cx.route(role_path(id, "view"));
|
||||
html! {
|
||||
a href=(view_href) { (label.using(cx)) }
|
||||
}
|
||||
|
|
@ -216,7 +201,6 @@ fn label_cell(role: &RoleListItem, waypoint: &Waypoint) -> Html {
|
|||
// que el marcado se genere cuando `Table` renderice la celda, no al construir la fila.
|
||||
async fn actions_cell(
|
||||
role: &RoleListItem,
|
||||
waypoint: &Waypoint,
|
||||
sort: RoleSortField,
|
||||
dir: SortDir,
|
||||
page: u64,
|
||||
|
|
@ -224,7 +208,6 @@ async fn actions_cell(
|
|||
) -> Html {
|
||||
let id = role.id;
|
||||
let locked = role.locked;
|
||||
let waypoint = waypoint.clone();
|
||||
|
||||
let can_manage_permissions = cx
|
||||
.request()
|
||||
|
|
@ -235,7 +218,7 @@ async fn actions_cell(
|
|||
// (ver `pagetop-bootsier::theme::bs::button`), incluida la traducción de `data-dialog-*` que
|
||||
// usa el botón de borrado.
|
||||
let permissions_button = if can_manage_permissions {
|
||||
let permissions_href = waypoint.append_to(cx.route(role_path(id, "permissions")));
|
||||
let permissions_href = cx.route(role_path(id, "permissions"));
|
||||
Some(
|
||||
Button::anchor(
|
||||
Lc::t("btn-manage-permissions", &LOCALES_USER),
|
||||
|
|
@ -253,7 +236,7 @@ async fn actions_cell(
|
|||
let (edit_button, delete_button) = if locked {
|
||||
(None, None)
|
||||
} else {
|
||||
let edit_href = waypoint.append_to(cx.route(role_path(id, "edit")));
|
||||
let edit_href = cx.route(role_path(id, "edit"));
|
||||
let edit_button = Button::anchor(Lc::t("btn-edit", &LOCALES_USER), edit_href)
|
||||
.with_style(button::Style::Solid(Intent::Primary))
|
||||
.with_size(button::Size::Small)
|
||||
|
|
|
|||
|
|
@ -27,8 +27,6 @@ pub(crate) struct UserForm {
|
|||
mode: UserFormMode,
|
||||
error: Option<Lc>,
|
||||
user_id: Option<i32>,
|
||||
/// Listado de origen al que volver tras guardar (orden, búsqueda, página).
|
||||
waypoint: Waypoint,
|
||||
username: String,
|
||||
email: String,
|
||||
display_name: String,
|
||||
|
|
@ -63,7 +61,7 @@ impl Component for UserForm {
|
|||
// 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 action = self.waypoint().append_to(cx.route(action));
|
||||
let action = cx.route(action);
|
||||
|
||||
let mut form = Form::new()
|
||||
.with_id(USER_ADMIN_FORM_ID)
|
||||
|
|
@ -168,7 +166,7 @@ impl Component for UserForm {
|
|||
form = form.with_child(profile_form_actions(save, cx));
|
||||
}
|
||||
UserFormMode::New => {
|
||||
let cancel = self.waypoint().or(cx.route(ADMIN_USERS_PATH.as_str()));
|
||||
let cancel = cx.route(ADMIN_USERS_PATH.as_str());
|
||||
form = form.with_child(form_actions(save, cancel));
|
||||
}
|
||||
}
|
||||
|
|
@ -196,11 +194,6 @@ impl UserForm {
|
|||
self
|
||||
}
|
||||
|
||||
pub(crate) fn with_waypoint(mut self, waypoint: impl Into<Waypoint>) -> Self {
|
||||
self.waypoint = waypoint.into();
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn with_username(mut self, username: impl Into<String>) -> Self {
|
||||
self.username = username.into();
|
||||
self
|
||||
|
|
|
|||
|
|
@ -47,7 +47,6 @@ impl Component for UserTable {
|
|||
.with_column(Lc::t("col-actions", &LOCALES_USER))
|
||||
.with_empty(Lc::t("empty-users-list", &LOCALES_USER));
|
||||
|
||||
let waypoint = Waypoint::from(self.list_href(cx));
|
||||
let viewer_is_admin = cx
|
||||
.request()
|
||||
.and_then(|r| r.extension::<Account>())
|
||||
|
|
@ -58,16 +57,16 @@ impl Component for UserTable {
|
|||
|
||||
table.alter_row(
|
||||
table::Row::new()
|
||||
.with_cell(username_cell(user, &waypoint))
|
||||
.with_cell(username_cell(user))
|
||||
.with_cell(user.email.as_str())
|
||||
.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, viewer_is_admin, cx).await),
|
||||
.with_cell(actions_cell(user, viewer_is_admin, cx).await),
|
||||
);
|
||||
}
|
||||
|
||||
let new_href = waypoint.append_to(cx.route(util::join!(ADMIN_USERS_PATH.as_str(), "/new")));
|
||||
let new_href = cx.route(util::join!(ADMIN_USERS_PATH.as_str(), "/new"));
|
||||
|
||||
let mut list = ListView::new()
|
||||
.with_id("user-table-wrapper")
|
||||
|
|
@ -120,21 +119,6 @@ impl UserTable {
|
|||
self
|
||||
}
|
||||
|
||||
// URL del listado con el estado actual (búsqueda, orden, página): es el valor que viaja como
|
||||
// `waypoint` en los enlaces de ver/editar, para poder volver exactamente a este mismo estado.
|
||||
// Se construye con `cx.route()` para que preserve el parámetro `lang` cuando corresponda.
|
||||
fn list_href(&self, cx: &Context) -> String {
|
||||
let mut route = cx.route(ADMIN_USERS_PATH.as_str());
|
||||
if let Some(q) = self.query().filter(|q| !q.is_empty()) {
|
||||
route.alter_param("q", q);
|
||||
}
|
||||
route
|
||||
.alter_param("sort", self.sort().as_str())
|
||||
.alter_param("dir", *self.dir())
|
||||
.alter_param("page", self.page().to_string())
|
||||
.to_string()
|
||||
}
|
||||
|
||||
// Construye la cabecera ordenable de una columna: el enlace ya funciona sin HTMX (navega con
|
||||
// una petición normal); `pagetop_htmx::hx_table::sort_link()` añade aparte los atributos `hx-*`
|
||||
// para que la tabla se actualice sin recargar la página cuando la extensión esté disponible.
|
||||
|
|
@ -167,12 +151,11 @@ impl UserTable {
|
|||
// Construye la celda de usuario: el nombre enlaza a la pantalla de sólo lectura con todos sus
|
||||
// datos y roles. Devuelve un componente `Html` para que el marcado se genere cuando `Table`
|
||||
// renderice la celda, no al construir la fila.
|
||||
fn username_cell(user: &UserListItem, waypoint: &Waypoint) -> Html {
|
||||
fn username_cell(user: &UserListItem) -> Html {
|
||||
let username = user.username.clone();
|
||||
let id = user.id;
|
||||
let waypoint = waypoint.clone();
|
||||
Html::with(move |cx| {
|
||||
let view_href = waypoint.append_to(cx.route(user_path(id, "view")));
|
||||
let view_href = cx.route(user_path(id, "view"));
|
||||
html! {
|
||||
a href=(view_href) { (username.as_str()) }
|
||||
}
|
||||
|
|
@ -183,16 +166,11 @@ fn username_cell(user: &UserListItem, waypoint: &Waypoint) -> Html {
|
|||
// 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,
|
||||
viewer_is_admin: bool,
|
||||
cx: &mut Context,
|
||||
) -> Html {
|
||||
async fn actions_cell(user: &UserListItem, viewer_is_admin: bool, cx: &mut Context) -> Html {
|
||||
if user.is_admin && !viewer_is_admin {
|
||||
return Html::default();
|
||||
}
|
||||
let edit_href = waypoint.append_to(cx.route(user_path(user.id, "edit")));
|
||||
let edit_href = 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
|
||||
|
|
|
|||
|
|
@ -59,9 +59,13 @@ impl Component for LoginForm {
|
|||
.with_child(
|
||||
form::Checkbox::check()
|
||||
.with_name("remember")
|
||||
.with_label(Lc::t("field-remember-me", &LOCALES_USER)),
|
||||
.with_label(Lc::t("field-remember-me", &LOCALES_USER))
|
||||
.with_help_text(Lc::t("help-remember-me", &LOCALES_USER)),
|
||||
)
|
||||
.with_child(
|
||||
Button::submit(Lc::t("btn-login", &LOCALES_USER))
|
||||
.with_style(button::Style::Solid(Intent::Primary)),
|
||||
)
|
||||
.with_child(Button::submit(Lc::t("btn-login", &LOCALES_USER)))
|
||||
.with_child(links(SETTINGS.allow_registration));
|
||||
|
||||
if strict {
|
||||
|
|
|
|||
|
|
@ -27,7 +27,10 @@ impl Component for PasswordResetConfirmForm {
|
|||
PasswordConfirm::new()
|
||||
.with_password_label(Lc::t("field-new-password", &LOCALES_USER)),
|
||||
)
|
||||
.with_child(Button::submit(Lc::t("btn-set-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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,7 +30,10 @@ impl Component for PasswordResetForm {
|
|||
.with_autofocus(true)
|
||||
.with_required(true),
|
||||
)
|
||||
.with_child(Button::submit(Lc::t("btn-send-reset-link", &LOCALES_USER)))
|
||||
.with_child(
|
||||
Button::submit(Lc::t("btn-send-reset-link", &LOCALES_USER))
|
||||
.with_style(button::Style::Solid(Intent::Primary)),
|
||||
)
|
||||
.with_child(back_to_login());
|
||||
|
||||
Ok(form.render(cx).await)
|
||||
|
|
|
|||
|
|
@ -49,7 +49,10 @@ impl Component for RegisterForm {
|
|||
.with_required(true),
|
||||
)
|
||||
.with_child(PasswordConfirm::new())
|
||||
.with_child(Button::submit(Lc::t("btn-register", &LOCALES_USER)));
|
||||
.with_child(
|
||||
Button::submit(Lc::t("btn-register", &LOCALES_USER))
|
||||
.with_style(button::Style::Solid(Intent::Primary)),
|
||||
);
|
||||
|
||||
Ok(form.render(cx).await)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ pub struct Model {
|
|||
/// Último intento fallido, para saber si el siguiente cae dentro de la misma ventana.
|
||||
pub failed_login_at: Option<DateTimeUtc>,
|
||||
pub locked_until: Option<DateTimeUtc>,
|
||||
/// Acceso irrestricto al sistema, sin pasar por roles ni permisos.
|
||||
/// Acceso total al sistema, sin pasar por roles ni permisos.
|
||||
pub is_admin: bool,
|
||||
pub created_at: DateTimeUtc,
|
||||
pub updated_at: DateTimeUtc,
|
||||
|
|
|
|||
|
|
@ -310,7 +310,7 @@ pub(crate) struct ProfileFormData {
|
|||
|
||||
/// POST /user/edit - Guarda los datos del perfil propio. El nombre de usuario sólo cambia con
|
||||
/// `user:change_own_username`; el email, desde [`email_get()`]; roles, estado y acceso
|
||||
/// irrestricto no se tocan nunca desde aquí.
|
||||
/// total no se tocan nunca desde aquí.
|
||||
pub(crate) async fn profile_edit_post(
|
||||
request: HttpRequest,
|
||||
web::Form(form): web::Form<ProfileFormData>,
|
||||
|
|
|
|||
|
|
@ -72,19 +72,12 @@ pub(crate) async fn list_get(
|
|||
// **< new_get / new_post >*************************************************************************
|
||||
|
||||
/// GET /admin/user/roles/new - Formulario de alta de rol.
|
||||
pub(crate) async fn new_get(
|
||||
request: HttpRequest,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
pub(crate) async fn new_get(request: HttpRequest) -> Result<Response, ErrorPage> {
|
||||
let page = Page::admin(request);
|
||||
let title = Lc::t("title-admin-role-new", &LOCALES_USER);
|
||||
Ok(page
|
||||
.with_title(title)
|
||||
.with_child(
|
||||
RoleForm::new()
|
||||
.with_mode(RoleFormMode::New)
|
||||
.with_waypoint(waypoint),
|
||||
)
|
||||
.with_child(RoleForm::new().with_mode(RoleFormMode::New))
|
||||
.render()
|
||||
.await
|
||||
.into_response())
|
||||
|
|
@ -103,7 +96,6 @@ pub(crate) struct NewRoleFormData {
|
|||
/// POST /admin/user/roles/new - Crea un rol.
|
||||
pub(crate) async fn new_post(
|
||||
request: HttpRequest,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
web::Form(form): web::Form<NewRoleFormData>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
let weight: i32 = form.weight.trim().parse().unwrap_or(0);
|
||||
|
|
@ -119,7 +111,7 @@ pub(crate) async fn new_post(
|
|||
match result {
|
||||
Ok(_) => {
|
||||
let cx = Context::admin(request);
|
||||
let target = waypoint.or(cx.route(ADMIN_ROLES_PATH.as_str()));
|
||||
let target = cx.route(ADMIN_ROLES_PATH.as_str());
|
||||
Ok(Redirect::see_other(target).into_response())
|
||||
}
|
||||
Err(err) => {
|
||||
|
|
@ -130,8 +122,7 @@ pub(crate) async fn new_post(
|
|||
.with_label(form.label)
|
||||
.with_description(form.description)
|
||||
.with_weight(weight)
|
||||
.with_error(map_auth_error(&err))
|
||||
.with_waypoint(waypoint);
|
||||
.with_error(map_auth_error(&err));
|
||||
let title = Lc::t("title-admin-role-new", &LOCALES_USER);
|
||||
Ok(page
|
||||
.with_title(title)
|
||||
|
|
@ -149,7 +140,6 @@ pub(crate) async fn new_post(
|
|||
pub(crate) async fn edit_get(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
let role = match role_admin::find_role(id).await {
|
||||
Ok(role) => role,
|
||||
|
|
@ -171,8 +161,7 @@ pub(crate) async fn edit_get(
|
|||
.with_machine_name(role.machine_name)
|
||||
.with_label(role.label)
|
||||
.with_description(role.description.unwrap_or_default())
|
||||
.with_weight(role.weight)
|
||||
.with_waypoint(waypoint),
|
||||
.with_weight(role.weight),
|
||||
)
|
||||
.render()
|
||||
.await
|
||||
|
|
@ -192,7 +181,6 @@ pub(crate) struct EditRoleFormData {
|
|||
pub(crate) async fn edit_post(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
web::Form(form): web::Form<EditRoleFormData>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
let weight: i32 = form.weight.trim().parse().unwrap_or(0);
|
||||
|
|
@ -210,7 +198,7 @@ pub(crate) async fn edit_post(
|
|||
match result {
|
||||
Ok(()) => {
|
||||
let cx = Context::admin(request);
|
||||
let target = waypoint.or(cx.route(ADMIN_ROLES_PATH.as_str()));
|
||||
let target = cx.route(ADMIN_ROLES_PATH.as_str());
|
||||
Ok(Redirect::see_other(target).into_response())
|
||||
}
|
||||
Err(err) => {
|
||||
|
|
@ -226,8 +214,7 @@ pub(crate) async fn edit_post(
|
|||
.with_label(form.label)
|
||||
.with_description(form.description)
|
||||
.with_weight(weight)
|
||||
.with_error(map_auth_error(&err))
|
||||
.with_waypoint(waypoint);
|
||||
.with_error(map_auth_error(&err));
|
||||
let title = Lc::t("title-admin-role-edit", &LOCALES_USER);
|
||||
Ok(page
|
||||
.with_title(title)
|
||||
|
|
@ -246,7 +233,6 @@ pub(crate) async fn edit_post(
|
|||
pub(crate) async fn view_get(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
let role = match role_admin::find_role(id).await {
|
||||
Ok(role) => role,
|
||||
|
|
@ -259,7 +245,7 @@ pub(crate) async fn view_get(
|
|||
let mut page = Page::admin(request);
|
||||
|
||||
let groups = build_permission_groups(&selected, page.context());
|
||||
let back_href = waypoint.or(page.route(ADMIN_ROLES_PATH.as_str()));
|
||||
let back_href = page.route(ADMIN_ROLES_PATH.as_str());
|
||||
let details_block = role_view_details(&role, page.context_mut()).await;
|
||||
|
||||
let title = Lc::t("title-admin-role-view", &LOCALES_USER);
|
||||
|
|
@ -460,7 +446,6 @@ fn build_permission_groups(selected: &[String], cx: &Context) -> PermissionGroup
|
|||
pub(crate) async fn permissions_get(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
require_permission(&request, &UserPermission::AdminPermissions)?;
|
||||
|
||||
|
|
@ -481,8 +466,7 @@ pub(crate) async fn permissions_get(
|
|||
.with_child(
|
||||
RolePermissionsForm::new()
|
||||
.with_role_id(id)
|
||||
.with_groups(groups)
|
||||
.with_waypoint(waypoint),
|
||||
.with_groups(groups),
|
||||
)
|
||||
.render()
|
||||
.await
|
||||
|
|
@ -502,7 +486,6 @@ pub(crate) struct RolePermissionsFormData {
|
|||
pub(crate) async fn permissions_post(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
raw: web::RawForm,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
require_permission(&request, &UserPermission::AdminPermissions)?;
|
||||
|
|
@ -514,7 +497,7 @@ pub(crate) async fn permissions_post(
|
|||
match role_admin::set_role_permissions(id, &form.permission_keys).await {
|
||||
Ok(()) => {
|
||||
let cx = Context::admin(request);
|
||||
let target = waypoint.or(cx.route(ADMIN_ROLES_PATH.as_str()));
|
||||
let target = cx.route(ADMIN_ROLES_PATH.as_str());
|
||||
Ok(Redirect::see_other(target).into_response())
|
||||
}
|
||||
Err(err) => {
|
||||
|
|
@ -524,8 +507,7 @@ pub(crate) async fn permissions_post(
|
|||
let form_component = RolePermissionsForm::new()
|
||||
.with_role_id(id)
|
||||
.with_groups(groups)
|
||||
.with_error(map_auth_error(&err))
|
||||
.with_waypoint(waypoint);
|
||||
.with_error(map_auth_error(&err));
|
||||
let title = Lc::t("title-admin-role-permissions", &LOCALES_USER);
|
||||
Ok(page
|
||||
.with_title(title)
|
||||
|
|
|
|||
|
|
@ -125,7 +125,7 @@ fn parse_role_ids(role_ids: &[String]) -> Vec<i32> {
|
|||
|
||||
// Carga el usuario y comprueba que quien hace la petición puede gestionarlo. La cuenta de un
|
||||
// administrador sólo la gestiona otro administrador: si no, quien administra usuarios podría
|
||||
// apoderarse de ella (p. ej. restableciendo su contraseña) y obtener acceso irrestricto, que sólo
|
||||
// apoderarse de ella (p. ej. restableciendo su contraseña) y obtener acceso total, que sólo
|
||||
// un administrador puede conceder.
|
||||
async fn require_manageable(request: &HttpRequest, id: i32) -> Result<user::Model, ErrorPage> {
|
||||
let Ok(user) = user_admin::find_user(id).await else {
|
||||
|
|
@ -140,10 +140,7 @@ async fn require_manageable(request: &HttpRequest, id: i32) -> Result<user::Mode
|
|||
// **< new_get / new_post >*************************************************************************
|
||||
|
||||
/// GET /admin/user/users/new - Formulario de alta de usuario.
|
||||
pub(crate) async fn new_get(
|
||||
request: HttpRequest,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
pub(crate) async fn new_get(request: HttpRequest) -> Result<Response, ErrorPage> {
|
||||
let roles = match available_roles(&[]).await {
|
||||
Ok(roles) => roles,
|
||||
Err(_) => return Err(ErrorPage::InternalError(request)),
|
||||
|
|
@ -159,8 +156,7 @@ pub(crate) async fn new_get(
|
|||
UserForm::new()
|
||||
.with_mode(UserFormMode::New)
|
||||
.with_roles(roles)
|
||||
.with_allow_admin_field(allow_admin_field)
|
||||
.with_waypoint(waypoint),
|
||||
.with_allow_admin_field(allow_admin_field),
|
||||
)
|
||||
.render()
|
||||
.await
|
||||
|
|
@ -193,7 +189,6 @@ pub(crate) struct NewUserFormData {
|
|||
/// deserializa claves repetidas como `role_ids=2&role_ids=3` en un `Vec<T>`).
|
||||
pub(crate) async fn new_post(
|
||||
request: HttpRequest,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
raw: web::RawForm,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
let Ok(form) = serde_qs::from_bytes::<NewUserFormData>(&raw.0) else {
|
||||
|
|
@ -222,7 +217,7 @@ pub(crate) async fn new_post(
|
|||
match result {
|
||||
Ok(_) => {
|
||||
let cx = Context::admin(request);
|
||||
let target = waypoint.or(cx.route(ADMIN_USERS_PATH.as_str()));
|
||||
let target = cx.route(ADMIN_USERS_PATH.as_str());
|
||||
Ok(Redirect::see_other(target).into_response())
|
||||
}
|
||||
Err(err) => {
|
||||
|
|
@ -239,8 +234,7 @@ pub(crate) async fn new_post(
|
|||
.with_roles(roles)
|
||||
.with_allow_admin_field(allow_admin_field)
|
||||
.with_is_admin(is_admin)
|
||||
.with_error(map_auth_error(&err))
|
||||
.with_waypoint(waypoint);
|
||||
.with_error(map_auth_error(&err));
|
||||
let title = Lc::t("title-admin-user-new", &LOCALES_USER);
|
||||
Ok(page
|
||||
.with_title(title)
|
||||
|
|
@ -255,12 +249,7 @@ pub(crate) async fn new_post(
|
|||
// **< edit_get / edit_post >***********************************************************************
|
||||
|
||||
// Pantalla de edición con el formulario relleno con los datos guardados del usuario.
|
||||
async fn render_user_edit(
|
||||
request: HttpRequest,
|
||||
id: i32,
|
||||
error: Option<Lc>,
|
||||
waypoint: Waypoint,
|
||||
) -> Response {
|
||||
async fn render_user_edit(request: HttpRequest, id: i32, error: Option<Lc>) -> Response {
|
||||
let user = match user_admin::find_user(id).await {
|
||||
Ok(user) => user,
|
||||
Err(_) => return ErrorPage::NotFound(request).into_response(),
|
||||
|
|
@ -285,7 +274,7 @@ async fn render_user_edit(
|
|||
.with_theme(user.theme.unwrap_or_default())
|
||||
.with_roles(roles)
|
||||
.with_error(error);
|
||||
render_edit_page(request, id, status, is_admin, form, waypoint).await
|
||||
render_edit_page(request, id, status, is_admin, form).await
|
||||
}
|
||||
|
||||
// Pantalla de edición del usuario `id` con `form` ya relleno, sea con los datos guardados o con los
|
||||
|
|
@ -297,7 +286,6 @@ async fn render_edit_page(
|
|||
status: UserStatus,
|
||||
is_admin: bool,
|
||||
form: UserForm,
|
||||
waypoint: Waypoint,
|
||||
) -> Response {
|
||||
// El botón de conceder/revocar sólo se muestra si quien lo ve ya es administrador y no está
|
||||
// viendo su propio perfil: no es un permiso del catálogo, y nadie puede automodificarse el flag
|
||||
|
|
@ -315,16 +303,11 @@ async fn render_edit_page(
|
|||
is_admin,
|
||||
can_toggle_admin,
|
||||
can_change_status,
|
||||
&waypoint,
|
||||
page.context_mut(),
|
||||
);
|
||||
|
||||
page.with_title(title)
|
||||
.with_child(
|
||||
form.with_mode(UserFormMode::Edit)
|
||||
.with_user_id(Some(id))
|
||||
.with_waypoint(waypoint.clone()),
|
||||
)
|
||||
.with_child(form.with_mode(UserFormMode::Edit).with_user_id(Some(id)))
|
||||
.with_child(actions)
|
||||
.render()
|
||||
.await
|
||||
|
|
@ -333,9 +316,7 @@ async fn render_edit_page(
|
|||
|
||||
// Botonera de la edición: "Guardar", "Cancelar", el enlace a la pantalla de restablecer contraseña
|
||||
// y los botones de bloqueo/activación (sólo si `can_change_status`) y de concesión/revocación de
|
||||
// acceso irrestricto (sólo si `can_toggle_admin`). El listado de origen (`waypoint`) se arrastra a
|
||||
// todas ellas para que, al volver aquí, esta misma pantalla siga sabiendo devolver al listado en el
|
||||
// estado en que se dejó.
|
||||
// acceso total (sólo si `can_toggle_admin`).
|
||||
//
|
||||
// "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
|
||||
|
|
@ -348,7 +329,6 @@ fn edit_actions(
|
|||
target_is_admin: bool,
|
||||
can_toggle_admin: bool,
|
||||
can_change_status: bool,
|
||||
waypoint: &Waypoint,
|
||||
cx: &mut Context,
|
||||
) -> Flex {
|
||||
// Una cuenta pendiente de verificar su email también se puede activar directamente, p. ej. si
|
||||
|
|
@ -363,9 +343,9 @@ fn edit_actions(
|
|||
("true", "btn-grant-admin", "confirm-grant-admin")
|
||||
};
|
||||
|
||||
let password_href = waypoint.append_to(cx.route(user_path(user_id, "password")));
|
||||
let status_action = waypoint.append_to(cx.route(user_path(user_id, "status")));
|
||||
let admin_action = waypoint.append_to(cx.route(user_path(user_id, "admin")));
|
||||
let password_href = cx.route(user_path(user_id, "password"));
|
||||
let status_action = cx.route(user_path(user_id, "status"));
|
||||
let admin_action = cx.route(user_path(user_id, "admin"));
|
||||
|
||||
let mut status_form = Form::new()
|
||||
.with_action(status_action.clone())
|
||||
|
|
@ -389,9 +369,7 @@ fn edit_actions(
|
|||
.with_style(button::Style::Solid(Intent::Primary))
|
||||
.with_prop(PropsOp::set("form", USER_ADMIN_FORM_ID)),
|
||||
)
|
||||
.with_child(cancel_link(
|
||||
waypoint.or(cx.route(ADMIN_USERS_PATH.as_str())),
|
||||
))
|
||||
.with_child(cancel_link(cx.route(ADMIN_USERS_PATH.as_str())))
|
||||
.with_child(
|
||||
Button::anchor(Lc::t("btn-reset-password", &LOCALES_USER), password_href)
|
||||
.with_style(button::Style::Solid(Intent::Neutral)),
|
||||
|
|
@ -422,10 +400,9 @@ fn edit_actions(
|
|||
pub(crate) async fn edit_get(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
require_manageable(&request, id).await?;
|
||||
Ok(render_user_edit(request, id, None, waypoint).await)
|
||||
Ok(render_user_edit(request, id, None).await)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
|
|
@ -452,7 +429,6 @@ pub(crate) struct EditUserFormData {
|
|||
pub(crate) async fn edit_post(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
raw: web::RawForm,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
let user = require_manageable(&request, id).await?;
|
||||
|
|
@ -481,7 +457,7 @@ pub(crate) async fn edit_post(
|
|||
match result {
|
||||
Ok(()) => {
|
||||
let cx = Context::admin(request);
|
||||
let target = waypoint.or(cx.route(ADMIN_USERS_PATH.as_str()));
|
||||
let target = cx.route(ADMIN_USERS_PATH.as_str());
|
||||
Ok(Redirect::see_other(target).into_response())
|
||||
}
|
||||
Err(err) => {
|
||||
|
|
@ -497,7 +473,7 @@ pub(crate) async fn edit_post(
|
|||
.with_theme(form.theme)
|
||||
.with_roles(roles)
|
||||
.with_error(map_auth_error(&err));
|
||||
Ok(render_edit_page(request, id, status, user.is_admin, form, waypoint).await)
|
||||
Ok(render_edit_page(request, id, status, user.is_admin, form).await)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -509,7 +485,6 @@ pub(crate) async fn edit_post(
|
|||
pub(crate) async fn view_get(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
let user = match user_admin::find_user(id).await {
|
||||
Ok(user) => user,
|
||||
|
|
@ -521,7 +496,7 @@ pub(crate) async fn view_get(
|
|||
};
|
||||
|
||||
let mut page = Page::admin(request);
|
||||
let back_href = waypoint.or(page.route(ADMIN_USERS_PATH.as_str()));
|
||||
let back_href = page.route(ADMIN_USERS_PATH.as_str());
|
||||
let details_block = user_details(&user, page.context_mut()).await;
|
||||
let roles_block = user_view_roles(&roles, user.is_admin, page.context_mut()).await;
|
||||
|
||||
|
|
@ -608,7 +583,6 @@ pub(crate) struct StatusFormData {
|
|||
pub(crate) async fn status_post(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
web::Form(form): web::Form<StatusFormData>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
require_permission(&request, &UserPermission::BlockAccounts)?;
|
||||
|
|
@ -629,14 +603,14 @@ pub(crate) async fn status_post(
|
|||
match user_admin::set_user_status(id, new_status, account.id()).await {
|
||||
Ok(()) => {
|
||||
let cx = Context::admin(request);
|
||||
let edit_href = waypoint.append_to(cx.route(user_path(id, "edit")));
|
||||
let edit_href = cx.route(user_path(id, "edit"));
|
||||
if is_htmx {
|
||||
Ok(HtmxResponse::empty().redirect(edit_href).into_response())
|
||||
} else {
|
||||
Ok(Redirect::see_other(edit_href).into_response())
|
||||
}
|
||||
}
|
||||
Err(err) => Ok(render_user_edit(request, id, Some(map_auth_error(&err)), waypoint).await),
|
||||
Err(err) => Ok(render_user_edit(request, id, Some(map_auth_error(&err))).await),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -647,7 +621,7 @@ pub(crate) struct AdminFormData {
|
|||
is_admin: String,
|
||||
}
|
||||
|
||||
/// POST /admin/user/users/{id}/admin - Concede o revoca el acceso irrestricto (`is_admin`).
|
||||
/// POST /admin/user/users/{id}/admin - Concede o revoca el acceso total (`is_admin`).
|
||||
///
|
||||
/// No pasa por `require_permission`: conceder o revocar este flag no es un permiso del catálogo,
|
||||
/// se comprueba directamente contra `account.is_admin()` para que sólo un administrador pueda
|
||||
|
|
@ -655,7 +629,6 @@ pub(crate) struct AdminFormData {
|
|||
pub(crate) async fn admin_post(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
web::Form(form): web::Form<AdminFormData>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
let Some(account) = request.extension::<Account>().cloned() else {
|
||||
|
|
@ -676,14 +649,14 @@ pub(crate) async fn admin_post(
|
|||
match user_admin::set_user_admin(id, new_is_admin, account.id()).await {
|
||||
Ok(()) => {
|
||||
let cx = Context::admin(request);
|
||||
let edit_href = waypoint.append_to(cx.route(user_path(id, "edit")));
|
||||
let edit_href = cx.route(user_path(id, "edit"));
|
||||
if is_htmx {
|
||||
Ok(HtmxResponse::empty().redirect(edit_href).into_response())
|
||||
} else {
|
||||
Ok(Redirect::see_other(edit_href).into_response())
|
||||
}
|
||||
}
|
||||
Err(err) => Ok(render_user_edit(request, id, Some(map_auth_error(&err)), waypoint).await),
|
||||
Err(err) => Ok(render_user_edit(request, id, Some(map_auth_error(&err))).await),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -694,7 +667,6 @@ pub(crate) async fn admin_post(
|
|||
pub(crate) async fn password_get(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
let user = require_manageable(&request, id).await?;
|
||||
let page = Page::admin(request);
|
||||
|
|
@ -702,11 +674,7 @@ pub(crate) async fn password_get(
|
|||
Ok(page
|
||||
.with_title(title)
|
||||
.with_child(user_summary(&user))
|
||||
.with_child(
|
||||
AdminPasswordForm::new()
|
||||
.with_user_id(id)
|
||||
.with_waypoint(waypoint),
|
||||
)
|
||||
.with_child(AdminPasswordForm::new().with_user_id(id))
|
||||
.render()
|
||||
.await
|
||||
.into_response())
|
||||
|
|
@ -723,7 +691,6 @@ pub(crate) struct AdminPasswordFormData {
|
|||
pub(crate) async fn password_post(
|
||||
request: HttpRequest,
|
||||
web::Path(id): web::Path<i32>,
|
||||
web::Query(waypoint): web::Query<Waypoint>,
|
||||
web::Form(form): web::Form<AdminPasswordFormData>,
|
||||
) -> Result<Response, ErrorPage> {
|
||||
let user = require_manageable(&request, id).await?;
|
||||
|
|
@ -737,7 +704,7 @@ pub(crate) async fn password_post(
|
|||
Ok(user) => {
|
||||
send_notice(&request, Notice::PasswordChangedByAdmin, &user);
|
||||
let cx = Context::admin(request);
|
||||
let edit_href = waypoint.append_to(cx.route(user_path(id, "edit")));
|
||||
let edit_href = cx.route(user_path(id, "edit"));
|
||||
Ok(Redirect::see_other(edit_href).into_response())
|
||||
}
|
||||
Err(err) => {
|
||||
|
|
@ -749,8 +716,7 @@ pub(crate) async fn password_post(
|
|||
.with_child(
|
||||
AdminPasswordForm::new()
|
||||
.with_user_id(id)
|
||||
.with_error(map_auth_error(&err))
|
||||
.with_waypoint(waypoint),
|
||||
.with_error(map_auth_error(&err)),
|
||||
)
|
||||
.render()
|
||||
.await
|
||||
|
|
|
|||
|
|
@ -159,6 +159,25 @@ Los inicios de sesión fallidos se limitan también por dirección IP (`max_ip_f
|
|||
frenar a quien prueba unas pocas contraseñas habituales en muchas cuentas sin llegar a bloquear
|
||||
ninguna. Detrás de un *proxy* inverso, los límites por IP requieren configurar
|
||||
`server.client_ip_header`.
|
||||
|
||||
## Cookies
|
||||
|
||||
Al iniciar sesión se crea la *cookie* de sesión (`cookie_name` de `[user.session]`, `pagetop` por
|
||||
defecto). Es propia, `HttpOnly` y con un identificador aleatorio que la aplicación guarda en la base
|
||||
de datos. Se borra al cerrar sesión.
|
||||
|
||||
Sin marcar "Recuérdame", el navegador la borra al cerrarse, y la sesión deja de valer tras
|
||||
`idle_secs` sin uso. Es una *cookie* de autenticación para un servicio que el propio usuario pide,
|
||||
así que en España y en la Unión Europea no requiere su aceptación: las normas y guías en que se basa
|
||||
están en [*Cookies*](pagetop::web#cookies), en el módulo `web` de PageTop.
|
||||
|
||||
Con "Recuérdame", la sesión se conserva aunque se cierre el navegador, hasta `remember_idle_secs`
|
||||
sin uso (14 días por defecto). El dictamen 04/2012 del Grupo de Trabajo del Artículo 29 (WP194) no
|
||||
exime estas *cookies* de inicio de sesión persistente, pero considera suficiente que sea el usuario
|
||||
quien la pida marcando expresamente la casilla, siempre que sepa que se usa una *cookie*. Por eso el
|
||||
formulario de acceso lo indica en el texto de ayuda de la casilla, que además desaconseja marcarla
|
||||
en un equipo compartido. La aplicación sólo tiene que declararla también en su política de
|
||||
*cookies*.
|
||||
*/
|
||||
|
||||
use pagetop::prelude::*;
|
||||
|
|
@ -450,7 +469,10 @@ impl Extension for User {
|
|||
&format!("{}/{{uid}}/{{token}}", VERIFY_PATH),
|
||||
web::get(handlers::auth::verify_email_get).post(handlers::auth::verify_email_post),
|
||||
)
|
||||
.admin_route(ADMIN_USERS, web::get(handlers::admin::users::list_get))
|
||||
.admin_route(
|
||||
ADMIN_USERS,
|
||||
web::remember_query(web::get(handlers::admin::users::list_get)),
|
||||
)
|
||||
.admin_route(
|
||||
&format!("{ADMIN_USERS}/new"),
|
||||
web::get(handlers::admin::users::new_get).post(handlers::admin::users::new_post),
|
||||
|
|
@ -476,7 +498,10 @@ impl Extension for User {
|
|||
web::get(handlers::admin::users::password_get)
|
||||
.post(handlers::admin::users::password_post),
|
||||
)
|
||||
.admin_route(ADMIN_ROLES, web::get(handlers::admin::roles::list_get))
|
||||
.admin_route(
|
||||
ADMIN_ROLES,
|
||||
web::remember_query(web::get(handlers::admin::roles::list_get)),
|
||||
)
|
||||
.admin_route(
|
||||
&format!("{ADMIN_ROLES}/new"),
|
||||
web::get(handlers::admin::roles::new_get).post(handlers::admin::roles::new_post),
|
||||
|
|
|
|||
|
|
@ -226,6 +226,8 @@ help-password-min-length = At least { $n } characters.
|
|||
|
||||
help-email-readonly = To change it, use "Change email" in your profile.
|
||||
|
||||
help-remember-me = Keeps you signed in using a cookie. Do not check on a shared device.
|
||||
|
||||
help-machine-name-immutable =
|
||||
Lowercase letters, digits and underscores only. Cannot be changed after creation.
|
||||
|
||||
|
|
|
|||
|
|
@ -206,7 +206,7 @@ field-label = Etiqueta
|
|||
field-description = Descripción
|
||||
field-weight = Peso
|
||||
field-roles = Roles
|
||||
field-is-admin = Administrador (acceso irrestricto)
|
||||
field-is-admin = Administrador (acceso total)
|
||||
field-search-users = Buscar por usuario, email o nombre...
|
||||
|
||||
help-username-strict =
|
||||
|
|
@ -227,6 +227,8 @@ help-password-min-length = Al menos { $n } caracteres.
|
|||
|
||||
help-email-readonly = Para cambiarla, usa «Cambiar email» en tu perfil.
|
||||
|
||||
help-remember-me = Mantiene la sesión abierta usando una cookie. No marcar en un equipo compartido.
|
||||
|
||||
help-machine-name-immutable =
|
||||
Sólo minúsculas, dígitos y guiones bajos. No se puede cambiar tras crearlo.
|
||||
|
||||
|
|
@ -254,8 +256,8 @@ link-back = Volver
|
|||
|
||||
confirm-delete-role = ¿Eliminar este rol? Esta acción no se puede deshacer.
|
||||
confirm-change-status = ¿Cambiar el estado de esta cuenta?
|
||||
confirm-grant-admin = ¿Conceder acceso irrestricto a esta cuenta?
|
||||
confirm-revoke-admin = ¿Revocar el acceso irrestricto de esta cuenta?
|
||||
confirm-grant-admin = ¿Conceder acceso total a esta cuenta?
|
||||
confirm-revoke-admin = ¿Revocar el acceso total de esta cuenta?
|
||||
badge-system-role = Sistema
|
||||
badge-admin = Administrador
|
||||
badge-no-permissions = Sin permisos
|
||||
|
|
@ -273,6 +275,6 @@ error-role-locked = Este rol es de sistema y no se puede modifi
|
|||
error-role-in-use = Este rol tiene usuarios asignados y no se puede eliminar.
|
||||
error-last-administrator = No se puede quitar al último administrador.
|
||||
error-cannot-block-self = No puedes bloquear tu propia cuenta.
|
||||
error-cannot-modify-own-admin-flag = No puedes conceder ni revocar tu propio acceso irrestricto.
|
||||
error-cannot-modify-own-admin-flag = No puedes conceder ni revocar tu propio acceso total.
|
||||
error-user-not-found = Usuario no encontrado.
|
||||
error-unknown-permission = Clave de permiso desconocida.
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ use std::sync::Arc;
|
|||
use pagetop::prelude::*;
|
||||
|
||||
use crate::account::{Account, PermissionSet};
|
||||
use crate::config::SETTINGS;
|
||||
use crate::session;
|
||||
|
||||
// Permisos del rol "anonymous", insertados en las peticiones sin sesión. Un tipo propio para que no
|
||||
|
|
@ -47,17 +48,17 @@ pub(crate) async fn session_middleware(
|
|||
|
||||
let mut response = next.run(req).await;
|
||||
|
||||
// No se pisa una cookie que ya fije el handler (p. ej. la de expiración al cerrar sesión).
|
||||
// No se pisa la cookie de sesión que ya fije el handler (p. ej. la de expiración al cerrar
|
||||
// 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.
|
||||
if let Some(cookie) = renewed_cookie
|
||||
&& !response
|
||||
.headers()
|
||||
.contains_key(web::http::header::SET_COOKIE)
|
||||
&& !sets_cookie(response.headers(), &SETTINGS.session.cookie_name)
|
||||
{
|
||||
match web::http::HeaderValue::try_from(cookie) {
|
||||
Ok(value) => {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(web::http::header::SET_COOKIE, value);
|
||||
.append(web::http::header::SET_COOKIE, value);
|
||||
}
|
||||
Err(_) => trace::warn!("session: invalid renewed cookie, header discarded"),
|
||||
}
|
||||
|
|
@ -65,6 +66,19 @@ pub(crate) async fn session_middleware(
|
|||
response
|
||||
}
|
||||
|
||||
// Si la respuesta ya fija (o borra) la cookie `name`.
|
||||
fn sets_cookie(headers: &web::http::HeaderMap, name: &str) -> bool {
|
||||
headers
|
||||
.get_all(web::http::header::SET_COOKIE)
|
||||
.iter()
|
||||
.any(|value| {
|
||||
value
|
||||
.as_bytes()
|
||||
.strip_prefix(name.as_bytes())
|
||||
.is_some_and(|rest| rest.starts_with(b"="))
|
||||
})
|
||||
}
|
||||
|
||||
// **< check_rbac_permission >**********************************************************************
|
||||
|
||||
/// Handler de la acción [`CheckPermission`](pagetop::base::action::auth::CheckPermission) para el
|
||||
|
|
@ -88,3 +102,33 @@ pub(crate) fn check_rbac_permission(
|
|||
*granted = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn headers(cookies: &[&'static str]) -> web::http::HeaderMap {
|
||||
let mut headers = web::http::HeaderMap::new();
|
||||
for cookie in cookies {
|
||||
headers.append(
|
||||
web::http::header::SET_COOKIE,
|
||||
web::http::HeaderValue::from_static(cookie),
|
||||
);
|
||||
}
|
||||
headers
|
||||
}
|
||||
|
||||
#[pagetop::test]
|
||||
async fn only_the_session_cookie_itself_blocks_its_renewal() {
|
||||
// Other cookies (flash messages, the state of a list) must not stop the renewal.
|
||||
let others = headers(&[
|
||||
"pagetop_flash=iSaved; Path=/",
|
||||
"pagetop_list_0=q=a; Path=/x",
|
||||
]);
|
||||
assert!(!sets_cookie(&others, "session"));
|
||||
let logout = headers(&["pagetop_flash=iBye; Path=/", "session=; Path=/; Max-Age=0"]);
|
||||
assert!(sets_cookie(&logout, "session"));
|
||||
// A cookie whose name only starts like the session one is a different cookie.
|
||||
assert!(!sets_cookie(&headers(&["session_old=x"]), "session"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ impl MigrationTrait for Migration {
|
|||
.col(integer(Users::FailedLoginCount).default(0))
|
||||
.col(timestamp_null(Users::FailedLoginAt))
|
||||
.col(timestamp_null(Users::LockedUntil))
|
||||
// Acceso irrestricto al sistema, sin pasar por roles ni permisos.
|
||||
// Acceso total al sistema, sin pasar por roles ni permisos.
|
||||
.col(boolean(Users::IsAdmin).default(false))
|
||||
.to_owned(),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ pub enum UserPermission {
|
|||
/// "Sobre mí" y fecha de alta.
|
||||
ViewProfiles,
|
||||
/// Editar los datos del perfil propio: email, nombre visible, "Sobre mí", idioma, zona horaria
|
||||
/// y tema. Nunca los roles, el estado de la cuenta ni el acceso irrestricto.
|
||||
/// y tema. Nunca los roles, el estado de la cuenta ni el acceso total.
|
||||
EditOwnProfile,
|
||||
/// Cambiar el nombre de usuario propio. Complementa a `EditOwnProfile`: el campo está en el
|
||||
/// mismo formulario, así que sin aquel no tiene efecto.
|
||||
|
|
|
|||
|
|
@ -473,7 +473,7 @@ pub(crate) async fn set_user_status(
|
|||
|
||||
// **< set_user_admin >*****************************************************************************
|
||||
|
||||
/// Concede o revoca el acceso irrestricto (`is_admin`). No es un permiso del catálogo: sólo un
|
||||
/// Concede o revoca el acceso total (`is_admin`). No es un permiso del catálogo: sólo un
|
||||
/// administrador puede concederlo o revocarlo (el handler comprueba `account.is_admin()`
|
||||
/// directamente, sin pasar por `require_permission`).
|
||||
///
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
// End-to-end account flows against a real database. `config/common.toml` gives these tests an
|
||||
// in-memory SQLite database with a single connection, the memory mail transport, email
|
||||
// verification on sign-up, `max_failed_logins = 3`, `max_ip_requests = 3`,
|
||||
// `max_ip_failed_logins = 3` and `max_email_changes = 2` (`max_password_resets` keeps its
|
||||
// default, 3).
|
||||
// `max_ip_failed_logins = 3`, `max_email_changes = 2` (`max_password_resets` keeps its default,
|
||||
// 3) and `write_interval_secs = 0`, so "remember me" sessions renew their cookie on every request.
|
||||
//
|
||||
// Every scenario shares the same database, so they run one after another in a single test (and a
|
||||
// single runtime, which also keeps the database connection alive). Each one uses its own accounts
|
||||
|
|
@ -198,6 +198,8 @@ async fn account_flows() {
|
|||
requests_are_limited_by_address(&client).await;
|
||||
failed_logins_are_limited_by_address(&client).await;
|
||||
anonymous_visitors_are_offered_to_sign_in(&client).await;
|
||||
user_and_role_lists_remember_their_state(&client).await;
|
||||
remembered_sessions_are_renewed_alongside_other_cookies(&client).await;
|
||||
}
|
||||
|
||||
async fn registration_requires_confirming_the_address(client: &Client) {
|
||||
|
|
@ -876,3 +878,61 @@ async fn anonymous_visitors_are_offered_to_sign_in(client: &Client) {
|
|||
);
|
||||
assert!(reply.header("set-cookie").starts_with("pagetop_flash="));
|
||||
}
|
||||
|
||||
// The lists of users and roles remember their search, order and page: coming back to them without
|
||||
// parameters, as the back links and the redirections after saving do, restores the state, and
|
||||
// "Clear" forgets it.
|
||||
async fn user_and_role_lists_remember_their_state(client: &Client) {
|
||||
let admin = client.login("admin", "admin-password").await.unwrap();
|
||||
for (list, state) in [
|
||||
("/admin/user/users", "q=gil&sort=email&dir=desc&page=1"),
|
||||
("/admin/user/roles", "sort=label&dir=desc&page=1"),
|
||||
] {
|
||||
let filtered = client.get(&format!("{list}?{state}"), Some(&admin)).await;
|
||||
assert_eq!(filtered.status, Status::OK, "{list}");
|
||||
let saved = filtered.header("set-cookie").split(';').next().unwrap();
|
||||
assert!(saved.starts_with("pagetop_list_"), "{list}: {saved}");
|
||||
let cookies = format!("{admin}; {saved}");
|
||||
|
||||
let back = client.get(list, Some(&cookies)).await;
|
||||
assert_eq!(back.status, Status::SEE_OTHER, "{list}");
|
||||
assert_eq!(back.location(), format!("{list}?{state}"));
|
||||
|
||||
let reset = client.get(&format!("{list}?reset"), Some(&cookies)).await;
|
||||
assert_eq!(reset.location(), list);
|
||||
}
|
||||
}
|
||||
|
||||
// A "remember me" session renews its cookie even when the response sets another one, such as the
|
||||
// state of a list: otherwise the cookie would expire in the browser before the session does.
|
||||
async fn remembered_sessions_are_renewed_alongside_other_cookies(client: &Client) {
|
||||
let fields = form(&[
|
||||
("username", "admin"),
|
||||
("password", "admin-password"),
|
||||
("remember", "true"),
|
||||
]);
|
||||
let login = client.post("/user/login", &fields, None).await;
|
||||
assert_eq!(login.status, Status::SEE_OTHER);
|
||||
let session = login.session_cookie().expect("login sets the cookie");
|
||||
|
||||
let reply = client
|
||||
.get("/admin/user/users?q=renewal", Some(&session))
|
||||
.await;
|
||||
assert_eq!(reply.status, Status::OK);
|
||||
let cookies: Vec<&str> = reply
|
||||
.headers
|
||||
.get_all("set-cookie")
|
||||
.iter()
|
||||
.filter_map(|value| value.to_str().ok())
|
||||
.collect();
|
||||
assert!(
|
||||
cookies.iter().any(|c| c.starts_with("pagetop_list_")),
|
||||
"{cookies:?}"
|
||||
);
|
||||
assert!(
|
||||
cookies
|
||||
.iter()
|
||||
.any(|c| c.starts_with(&format!("{session};")) && c.contains("Max-Age=")),
|
||||
"{cookies:?}"
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue