🐛 (user): Corrige altas simultáneas y roles sistema
This commit is contained in:
parent
574010374d
commit
9afbafdefb
12 changed files with 134 additions and 63 deletions
|
|
@ -31,7 +31,13 @@
|
||||||
//! modelo leído: `model.into_active_model()`).
|
//! modelo leído: `model.into_active_model()`).
|
||||||
//! - **Macros de derivación**: [`DeriveEntityModel`], [`DeriveColumn`], [`DerivePrimaryKey`],
|
//! - **Macros de derivación**: [`DeriveEntityModel`], [`DeriveColumn`], [`DerivePrimaryKey`],
|
||||||
//! [`DeriveRelation`], [`EnumIter`].
|
//! [`DeriveRelation`], [`EnumIter`].
|
||||||
//! - **Errores**: [`DbErr`], [`TransactionError`].
|
//! - **Errores**: [`DbErr`], [`TransactionError`], [`SqlErr`] (para reconocer con
|
||||||
|
//! [`DbErr::sql_err()`] la violación de una restricción única o de clave ajena).
|
||||||
|
//! - **Fechas**: [`DateTime`] es el de PageTop ([`pagetop::datetime::DateTime`]), no el alias de
|
||||||
|
//! `NaiveDateTime` que exporta SeaORM con ese nombre, para que `db::*` y el preludio de PageTop
|
||||||
|
//! puedan importarse juntos. Para las columnas de fecha y hora de una entidad se usa
|
||||||
|
//! [`DateTimeUtc`] o [`DateTimeWithTimeZone`] (con zona horaria) o
|
||||||
|
//! [`pagetop::datetime::NaiveDateTime`] (sin ella).
|
||||||
//! - **Resultados**: [`QueryResult`] (filas sin tipar), [`ExecResult`] (INSERT/UPDATE/DELETE),
|
//! - **Resultados**: [`QueryResult`] (filas sin tipar), [`ExecResult`] (INSERT/UPDATE/DELETE),
|
||||||
//! [`Paginated`] (página de resultados).
|
//! [`Paginated`] (página de resultados).
|
||||||
//!
|
//!
|
||||||
|
|
@ -153,6 +159,11 @@
|
||||||
|
|
||||||
pub use sea_orm::prelude::*;
|
pub use sea_orm::prelude::*;
|
||||||
|
|
||||||
|
// Sustituye al `DateTime` del prelude de SeaORM (alias de `NaiveDateTime`): al ser el mismo
|
||||||
|
// elemento que el del preludio de PageTop, el nombre no es ambiguo al importar ambos con `*`.
|
||||||
|
#[doc(no_inline)]
|
||||||
|
pub use pagetop::datetime::DateTime;
|
||||||
|
|
||||||
// Re-exporta el crate `sea_orm` íntegro como puerta de acceso a su API completa.
|
// Re-exporta el crate `sea_orm` íntegro como puerta de acceso a su API completa.
|
||||||
//
|
//
|
||||||
// Útil para tipos o utilidades que no están expuestos directamente en `db::*`; la inmensa mayoría
|
// Útil para tipos o utilidades que no están expuestos directamente en `db::*`; la inmensa mayoría
|
||||||
|
|
@ -169,7 +180,7 @@ pub use sea_orm;
|
||||||
|
|
||||||
pub use sea_orm::{
|
pub use sea_orm::{
|
||||||
ActiveValue, Condition, DatabaseTransaction, DbBackend, ExecResult, IntoActiveModel, NotSet,
|
ActiveValue, Condition, DatabaseTransaction, DbBackend, ExecResult, IntoActiveModel, NotSet,
|
||||||
Order, QueryOrder, QuerySelect, Set, TransactionError, TransactionTrait, Unchanged,
|
Order, QueryOrder, QuerySelect, Set, SqlErr, TransactionError, TransactionTrait, Unchanged,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Re-exporta `sea_query` para construir sentencias SQL en tiempo de ejecución.
|
/// Re-exporta `sea_query` para construir sentencias SQL en tiempo de ejecución.
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,7 @@
|
||||||
//! inicial.
|
//! inicial.
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
use pagetop_seaorm::db::{
|
use pagetop_seaorm::db::*;
|
||||||
ActiveModelTrait, ActiveValue, ColumnTrait, EntityTrait, IntoActiveModel, PaginatorTrait,
|
|
||||||
QueryFilter, Set, dbconn,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::account::UserStatus;
|
use crate::account::UserStatus;
|
||||||
use crate::config::SETTINGS;
|
use crate::config::SETTINGS;
|
||||||
|
|
@ -14,7 +11,9 @@ use crate::error::AuthError;
|
||||||
use crate::identity::{self, Email, Username};
|
use crate::identity::{self, Email, Username};
|
||||||
use crate::password;
|
use crate::password;
|
||||||
use crate::permission::UserPermission;
|
use crate::permission::UserPermission;
|
||||||
use crate::service::user_admin::{ensure_email_available, ensure_username_available};
|
use crate::service::user_admin::{
|
||||||
|
ensure_email_available, ensure_username_available, taken_on_conflict,
|
||||||
|
};
|
||||||
use crate::session;
|
use crate::session;
|
||||||
use crate::token::{self, TokenKind};
|
use crate::token::{self, TokenKind};
|
||||||
|
|
||||||
|
|
@ -147,10 +146,10 @@ pub async fn register(
|
||||||
};
|
};
|
||||||
username.set_on(&mut new_user);
|
username.set_on(&mut new_user);
|
||||||
email.set_on(&mut new_user);
|
email.set_on(&mut new_user);
|
||||||
let result = user::Entity::insert(new_user).exec(dbconn()).await?;
|
match user::Entity::insert(new_user).exec(dbconn()).await {
|
||||||
let user_id = result.last_insert_id;
|
Ok(result) => Ok(result.last_insert_id),
|
||||||
|
Err(err) => Err(taken_on_conflict(err.into(), Some(&username), &email, None).await),
|
||||||
Ok(user_id)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< change_own_password >************************************************************************
|
// **< change_own_password >************************************************************************
|
||||||
|
|
@ -291,7 +290,9 @@ pub(crate) async fn confirm_email_change(user_id: i32, plain_token: &str) -> Res
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
email.set_on(&mut model);
|
email.set_on(&mut model);
|
||||||
model.update(dbconn()).await?;
|
if let Err(err) = model.update(dbconn()).await {
|
||||||
|
return Err(taken_on_conflict(err.into(), None, &email, Some(user_id)).await);
|
||||||
|
}
|
||||||
revoke_address_tokens(user_id).await
|
revoke_address_tokens(user_id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -217,13 +217,13 @@ impl RoleTable {
|
||||||
// rol. Devuelve un componente `Html` para que el marcado se genere cuando `Table` renderice la
|
// rol. Devuelve un componente `Html` para que el marcado se genere cuando `Table` renderice la
|
||||||
// celda, no al construir la fila.
|
// celda, no al construir la fila.
|
||||||
fn label_cell(role: &RoleListItem, waypoint: &Waypoint) -> Html {
|
fn label_cell(role: &RoleListItem, waypoint: &Waypoint) -> Html {
|
||||||
let label = role.label.clone();
|
let label = crate::role_label(role.id, &role.label);
|
||||||
let id = role.id;
|
let id = role.id;
|
||||||
let waypoint = waypoint.clone();
|
let waypoint = waypoint.clone();
|
||||||
Html::with(move |cx| {
|
Html::with(move |cx| {
|
||||||
let view_href = waypoint.append_to(cx.route(role_path(id, "view")));
|
let view_href = waypoint.append_to(cx.route(role_path(id, "view")));
|
||||||
html! {
|
html! {
|
||||||
a href=(view_href) { (label.as_str()) }
|
a href=(view_href) { (label.using(cx)) }
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,10 +2,12 @@
|
||||||
//!
|
//!
|
||||||
//! Sólo se compila con la feature `demo-data`. Se ejecuta una vez desde
|
//! Sólo se compila con la feature `demo-data`. Se ejecuta una vez desde
|
||||||
//! `Extension::initialize()`, después de `auth::seed_initial_data()`. Si el rol
|
//! `Extension::initialize()`, después de `auth::seed_initial_data()`. Si el rol
|
||||||
//! `demo_role_01` ya existe, la siembra se omite para no duplicar datos en reinicios.
|
//! `demo_role_01` ya existe, la siembra se omite para no duplicar datos en reinicios. Roles y
|
||||||
|
//! usuarios se crean en una sola transacción: si algo falla, no queda nada sembrado y se vuelve a
|
||||||
|
//! intentar en el siguiente arranque.
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
use pagetop_seaorm::db::{ActiveValue, ColumnTrait, EntityTrait, QueryFilter, Set, dbconn};
|
use pagetop_seaorm::db::*;
|
||||||
|
|
||||||
use crate::account::UserStatus;
|
use crate::account::UserStatus;
|
||||||
use crate::config::SETTINGS;
|
use crate::config::SETTINGS;
|
||||||
|
|
@ -31,30 +33,34 @@ pub(crate) async fn seed_demo_data() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let role_ids = match create_demo_roles().await {
|
let hash = match password::hash_password(DEMO_PASSWORD) {
|
||||||
Ok(ids) => ids,
|
Ok(hash) => hash,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!(
|
eprintln!("pagetop-user demo-data error: failed to hash password: {e}");
|
||||||
"pagetop-user demo-data error: failed to create roles: {}",
|
|
||||||
e
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
match create_demo_users(&role_ids).await {
|
let result = dbconn()
|
||||||
|
.transaction::<_, _, AuthError>(|txn| {
|
||||||
|
Box::pin(async move {
|
||||||
|
let role_ids = create_demo_roles(txn).await?;
|
||||||
|
create_demo_users(txn, &role_ids, &hash).await
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(flatten_txn_err);
|
||||||
|
|
||||||
|
match result {
|
||||||
Ok(()) => println!(
|
Ok(()) => println!(
|
||||||
"\npagetop-user: demo data created ({ROLE_COUNT} roles, {USER_COUNT} users).\n \
|
"\npagetop-user: demo data created ({ROLE_COUNT} roles, {USER_COUNT} users).\n \
|
||||||
password: {DEMO_PASSWORD}\n"
|
password: {DEMO_PASSWORD}\n"
|
||||||
),
|
),
|
||||||
Err(e) => eprintln!(
|
Err(e) => eprintln!("pagetop-user demo-data error: failed to create demo data: {e}"),
|
||||||
"pagetop-user demo-data error: failed to create users: {}",
|
|
||||||
e
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_demo_roles() -> Result<Vec<i32>, AuthError> {
|
async fn create_demo_roles(txn: &DatabaseTransaction) -> Result<Vec<i32>, AuthError> {
|
||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
let mut role_ids = Vec::with_capacity(ROLE_COUNT);
|
let mut role_ids = Vec::with_capacity(ROLE_COUNT);
|
||||||
for n in 1..=ROLE_COUNT {
|
for n in 1..=ROLE_COUNT {
|
||||||
|
|
@ -71,14 +77,17 @@ async fn create_demo_roles() -> Result<Vec<i32>, AuthError> {
|
||||||
created_at: Set(now),
|
created_at: Set(now),
|
||||||
updated_at: Set(now),
|
updated_at: Set(now),
|
||||||
};
|
};
|
||||||
let result = role::Entity::insert(new_role).exec(dbconn()).await?;
|
let result = role::Entity::insert(new_role).exec(txn).await?;
|
||||||
role_ids.push(result.last_insert_id);
|
role_ids.push(result.last_insert_id);
|
||||||
}
|
}
|
||||||
Ok(role_ids)
|
Ok(role_ids)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn create_demo_users(role_ids: &[i32]) -> Result<(), AuthError> {
|
async fn create_demo_users(
|
||||||
let hash = password::hash_password(DEMO_PASSWORD)?;
|
txn: &DatabaseTransaction,
|
||||||
|
role_ids: &[i32],
|
||||||
|
hash: &str,
|
||||||
|
) -> Result<(), AuthError> {
|
||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
|
|
||||||
for n in 1..=USER_COUNT {
|
for n in 1..=USER_COUNT {
|
||||||
|
|
@ -88,7 +97,7 @@ async fn create_demo_users(role_ids: &[i32]) -> Result<(), AuthError> {
|
||||||
let mut new_user = user::ActiveModel {
|
let mut new_user = user::ActiveModel {
|
||||||
id: ActiveValue::NotSet,
|
id: ActiveValue::NotSet,
|
||||||
email_verified_at: Set(Some(now)),
|
email_verified_at: Set(Some(now)),
|
||||||
password_hash: Set(hash.clone()),
|
password_hash: Set(hash.to_owned()),
|
||||||
status: Set(UserStatus::Active.as_i16()),
|
status: Set(UserStatus::Active.as_i16()),
|
||||||
language: Set(None),
|
language: Set(None),
|
||||||
timezone: Set(None),
|
timezone: Set(None),
|
||||||
|
|
@ -106,7 +115,7 @@ async fn create_demo_users(role_ids: &[i32]) -> Result<(), AuthError> {
|
||||||
};
|
};
|
||||||
username.set_on(&mut new_user);
|
username.set_on(&mut new_user);
|
||||||
email.set_on(&mut new_user);
|
email.set_on(&mut new_user);
|
||||||
let result = user::Entity::insert(new_user).exec(dbconn()).await?;
|
let result = user::Entity::insert(new_user).exec(txn).await?;
|
||||||
let user_id = result.last_insert_id;
|
let user_id = result.last_insert_id;
|
||||||
|
|
||||||
// Reparte los usuarios de forma cíclica entre los roles de demostración.
|
// Reparte los usuarios de forma cíclica entre los roles de demostración.
|
||||||
|
|
@ -114,7 +123,7 @@ async fn create_demo_users(role_ids: &[i32]) -> Result<(), AuthError> {
|
||||||
user_id: Set(user_id),
|
user_id: Set(user_id),
|
||||||
role_id: Set(role_ids[(n - 1) % role_ids.len()]),
|
role_id: Set(role_ids[(n - 1) % role_ids.len()]),
|
||||||
})
|
})
|
||||||
.exec_without_returning(dbconn())
|
.exec_without_returning(txn)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
||||||
|
|
@ -117,7 +117,7 @@ async fn profile_roles(roles: &[role::Model], cx: &mut Context) -> Block {
|
||||||
return Block::new();
|
return Block::new();
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut items: Vec<(String, Option<Markup>)> = Vec::with_capacity(roles.len());
|
let mut items: Vec<(Lc, Option<Markup>)> = Vec::with_capacity(roles.len());
|
||||||
for r in roles {
|
for r in roles {
|
||||||
let system_badge = if r.locked {
|
let system_badge = if r.locked {
|
||||||
Some(
|
Some(
|
||||||
|
|
@ -128,17 +128,17 @@ async fn profile_roles(roles: &[role::Model], cx: &mut Context) -> Block {
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
items.push((r.label.clone(), system_badge));
|
items.push((crate::role_label(r.id, &r.label), system_badge));
|
||||||
}
|
}
|
||||||
|
|
||||||
Block::new()
|
Block::new()
|
||||||
.with_title(Lc::t("field-roles", &LOCALES_USER))
|
.with_title(Lc::t("field-roles", &LOCALES_USER))
|
||||||
.with_child(Html::with(move |_cx| {
|
.with_child(Html::with(move |cx| {
|
||||||
html! {
|
html! {
|
||||||
ul class="user-profile-roles" {
|
ul class="user-profile-roles" {
|
||||||
@for (label, system_badge) in &items {
|
@for (label, system_badge) in &items {
|
||||||
li {
|
li {
|
||||||
(label.as_str())
|
(label.using(cx))
|
||||||
@if let Some(badge) = system_badge {
|
@if let Some(badge) = system_badge {
|
||||||
" "
|
" "
|
||||||
(badge)
|
(badge)
|
||||||
|
|
|
||||||
|
|
@ -319,7 +319,7 @@ async fn role_view_details(role: &role::Model, cx: &mut Context) -> Block {
|
||||||
.with_row(
|
.with_row(
|
||||||
table::Row::new()
|
table::Row::new()
|
||||||
.with_cell(Lc::t("field-label", &LOCALES_USER))
|
.with_cell(Lc::t("field-label", &LOCALES_USER))
|
||||||
.with_cell(role.label.as_str()),
|
.with_cell(crate::role_label(role.id, &role.label)),
|
||||||
)
|
)
|
||||||
.with_row(
|
.with_row(
|
||||||
table::Row::new()
|
table::Row::new()
|
||||||
|
|
|
||||||
|
|
@ -590,11 +590,11 @@ async fn user_view_roles(roles: &[role::Model], is_admin: bool, cx: &mut Context
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
let (id, label) = (r.id, r.label.clone());
|
let (id, label) = (r.id, crate::role_label(r.id, &r.label));
|
||||||
table = table.with_row(
|
table = table.with_row(
|
||||||
table::Row::new()
|
table::Row::new()
|
||||||
.with_cell(Html::with(move |cx| {
|
.with_cell(Html::with(move |cx| {
|
||||||
html! { a href=(cx.route(role_path(id, "view"))) { (label.as_str()) } }
|
html! { a href=(cx.route(role_path(id, "view"))) { (label.using(cx)) } }
|
||||||
}))
|
}))
|
||||||
.with_cell(r.machine_name.as_str())
|
.with_cell(r.machine_name.as_str())
|
||||||
.with_cell(Html::with(move |_| {
|
.with_cell(Html::with(move |_| {
|
||||||
|
|
|
||||||
|
|
@ -55,10 +55,10 @@ pub(crate) struct Username {
|
||||||
|
|
||||||
impl Username {
|
impl Username {
|
||||||
// Guarda el nombre de usuario en el modelo.
|
// Guarda el nombre de usuario en el modelo.
|
||||||
pub(crate) fn set_on(self, model: &mut user::ActiveModel) {
|
pub(crate) fn set_on(&self, model: &mut user::ActiveModel) {
|
||||||
model.username = Set(self.value);
|
model.username = Set(self.value.clone());
|
||||||
model.username_key = Set(self.key);
|
model.username_key = Set(self.key.clone());
|
||||||
model.username_skeleton = Set(self.skeleton);
|
model.username_skeleton = Set(self.skeleton.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -154,9 +154,9 @@ pub(crate) struct Email {
|
||||||
|
|
||||||
impl Email {
|
impl Email {
|
||||||
// Guarda el email en el modelo.
|
// Guarda el email en el modelo.
|
||||||
pub(crate) fn set_on(self, model: &mut user::ActiveModel) {
|
pub(crate) fn set_on(&self, model: &mut user::ActiveModel) {
|
||||||
model.email = Set(self.value);
|
model.email = Set(self.value.clone());
|
||||||
model.email_key = Set(self.key);
|
model.email_key = Set(self.key.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -313,6 +313,16 @@ fn is_system_role(role_id: i32) -> bool {
|
||||||
role_id == ANONYMOUS_ROLE_ID || role_id == AUTHENTICATED_ROLE_ID
|
role_id == ANONYMOUS_ROLE_ID || role_id == AUTHENTICATED_ROLE_ID
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Etiqueta visible de un rol. Las de los roles de sistema se traducen: la migración las guarda en
|
||||||
|
// inglés y, al estar bloqueados, no se pueden editar.
|
||||||
|
fn role_label(role_id: i32, label: &str) -> Lc {
|
||||||
|
match role_id {
|
||||||
|
ANONYMOUS_ROLE_ID => Lc::t("role-anonymous", &LOCALES_USER),
|
||||||
|
AUTHENTICATED_ROLE_ID => Lc::t("role-authenticated", &LOCALES_USER),
|
||||||
|
_ => Lc::n(label.to_owned()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// **< Extension >**********************************************************************************
|
// **< Extension >**********************************************************************************
|
||||||
|
|
||||||
/// Implementa la extensión `pagetop-user`.
|
/// Implementa la extensión `pagetop-user`.
|
||||||
|
|
|
||||||
|
|
@ -150,6 +150,11 @@ status-active = Active
|
||||||
status-blocked = Blocked
|
status-blocked = Blocked
|
||||||
status-pending = Pending email verification
|
status-pending = Pending email verification
|
||||||
|
|
||||||
|
# **< System roles >**
|
||||||
|
|
||||||
|
role-anonymous = Anonymous
|
||||||
|
role-authenticated = Authenticated
|
||||||
|
|
||||||
# **< Admin: page titles >**
|
# **< Admin: page titles >**
|
||||||
|
|
||||||
title-admin-users = Users
|
title-admin-users = Users
|
||||||
|
|
|
||||||
|
|
@ -150,6 +150,11 @@ status-active = Activo
|
||||||
status-blocked = Bloqueado
|
status-blocked = Bloqueado
|
||||||
status-pending = Pendiente de verificación de email
|
status-pending = Pendiente de verificación de email
|
||||||
|
|
||||||
|
# **< Roles de sistema >**
|
||||||
|
|
||||||
|
role-anonymous = Anónimo
|
||||||
|
role-authenticated = Autenticado
|
||||||
|
|
||||||
# **< Administración: títulos de página >**
|
# **< Administración: títulos de página >**
|
||||||
|
|
||||||
title-admin-users = Usuarios
|
title-admin-users = Usuarios
|
||||||
|
|
|
||||||
|
|
@ -3,12 +3,7 @@
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
use pagetop_seaorm::db::query::{Expr, Func, LikeExpr};
|
use pagetop_seaorm::db::*;
|
||||||
use pagetop_seaorm::db::{
|
|
||||||
ActiveModelTrait, ActiveValue, ColumnTrait, Condition, DatabaseTransaction, DbErr, EntityTrait,
|
|
||||||
Order, Paginated, PaginatorTrait, QueryFilter, QueryOrder, Set, TransactionTrait, dbconn,
|
|
||||||
flatten_txn_err, paginate,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::account::UserStatus;
|
use crate::account::UserStatus;
|
||||||
use crate::config::{SETTINGS, user_language_applies, user_timezone_applies};
|
use crate::config::{SETTINGS, user_language_applies, user_timezone_applies};
|
||||||
|
|
@ -78,15 +73,17 @@ pub(crate) async fn list_users(
|
||||||
select = select.filter(
|
select = select.filter(
|
||||||
Condition::any()
|
Condition::any()
|
||||||
.add(
|
.add(
|
||||||
Expr::col(user::Column::UsernameKey)
|
query::Expr::col(user::Column::UsernameKey)
|
||||||
.like(contains_pattern(&identity::username_key(q))),
|
.like(contains_pattern(&identity::username_key(q))),
|
||||||
)
|
)
|
||||||
.add(
|
.add(
|
||||||
Expr::col(user::Column::EmailKey)
|
query::Expr::col(user::Column::EmailKey)
|
||||||
.like(contains_pattern(&identity::email_key(q))),
|
.like(contains_pattern(&identity::email_key(q))),
|
||||||
)
|
)
|
||||||
.add(
|
.add(
|
||||||
Expr::expr(Func::lower(Expr::col(user::Column::DisplayName)))
|
query::Expr::expr(query::Func::lower(query::Expr::col(
|
||||||
|
user::Column::DisplayName,
|
||||||
|
)))
|
||||||
.like(contains_pattern(&q.to_lowercase())),
|
.like(contains_pattern(&q.to_lowercase())),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
@ -112,7 +109,7 @@ pub(crate) async fn list_users(
|
||||||
// Patrón `LIKE` que busca `text` en cualquier posición, con los comodines `%` y `_` escapados para
|
// Patrón `LIKE` que busca `text` en cualquier posición, con los comodines `%` y `_` escapados para
|
||||||
// que se busquen tal cual (p. ej. el `_` de `demo_user`). Se escapan con `!`, no con `\`, que
|
// que se busquen tal cual (p. ej. el `_` de `demo_user`). Se escapan con `!`, no con `\`, que
|
||||||
// MySQL interpreta también dentro de las cadenas.
|
// MySQL interpreta también dentro de las cadenas.
|
||||||
fn contains_pattern(text: &str) -> LikeExpr {
|
fn contains_pattern(text: &str) -> query::LikeExpr {
|
||||||
let mut pattern = String::with_capacity(text.len() + 2);
|
let mut pattern = String::with_capacity(text.len() + 2);
|
||||||
pattern.push('%');
|
pattern.push('%');
|
||||||
for c in text.chars() {
|
for c in text.chars() {
|
||||||
|
|
@ -122,7 +119,7 @@ fn contains_pattern(text: &str) -> LikeExpr {
|
||||||
pattern.push(c);
|
pattern.push(c);
|
||||||
}
|
}
|
||||||
pattern.push('%');
|
pattern.push('%');
|
||||||
LikeExpr::new(pattern).escape('!')
|
query::LikeExpr::new(pattern).escape('!')
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn user_items(users: Vec<user::Model>) -> Result<Vec<UserListItem>, AuthError> {
|
async fn user_items(users: Vec<user::Model>) -> Result<Vec<UserListItem>, AuthError> {
|
||||||
|
|
@ -253,7 +250,7 @@ pub(crate) async fn create_user(data: NewUserData<'_>) -> Result<i32, AuthError>
|
||||||
email.set_on(&mut new_user);
|
email.set_on(&mut new_user);
|
||||||
let role_ids = assignable_roles(data.initial_role_ids);
|
let role_ids = assignable_roles(data.initial_role_ids);
|
||||||
|
|
||||||
dbconn()
|
let result = dbconn()
|
||||||
.transaction::<_, _, AuthError>(|txn| {
|
.transaction::<_, _, AuthError>(|txn| {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let user_id = user::Entity::insert(new_user)
|
let user_id = user::Entity::insert(new_user)
|
||||||
|
|
@ -265,7 +262,11 @@ pub(crate) async fn create_user(data: NewUserData<'_>) -> Result<i32, AuthError>
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(flatten_txn_err)
|
.map_err(flatten_txn_err);
|
||||||
|
match result {
|
||||||
|
Err(err) => Err(taken_on_conflict(err, Some(&username), &email, None).await),
|
||||||
|
ok => ok,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< update_user >********************************************************************************
|
// **< update_user >********************************************************************************
|
||||||
|
|
@ -365,7 +366,9 @@ pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Resul
|
||||||
}
|
}
|
||||||
username.set_on(&mut model);
|
username.set_on(&mut model);
|
||||||
email.set_on(&mut model);
|
email.set_on(&mut model);
|
||||||
model.update(dbconn()).await?;
|
if let Err(err) = model.update(dbconn()).await {
|
||||||
|
return Err(taken_on_conflict(err.into(), Some(&username), &email, Some(user_id)).await);
|
||||||
|
}
|
||||||
if email_changed {
|
if email_changed {
|
||||||
crate::auth::cancel_email_change(user_id).await?;
|
crate::auth::cancel_email_change(user_id).await?;
|
||||||
crate::auth::revoke_address_tokens(user_id).await?;
|
crate::auth::revoke_address_tokens(user_id).await?;
|
||||||
|
|
@ -628,6 +631,33 @@ pub(crate) async fn ensure_email_available(
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Traduce el error al guardar una cuenta si otra petición ha ocupado el nombre de usuario o el email
|
||||||
|
// entre la comprobación (`ensure_username_available()`, `ensure_email_available()`) y la escritura.
|
||||||
|
// Ante la violación de un índice único repite la comprobación, para devolver `UsernameTaken` o
|
||||||
|
// `EmailTaken` en lugar de un error interno; cualquier otro error se devuelve tal cual.
|
||||||
|
pub(crate) async fn taken_on_conflict(
|
||||||
|
err: AuthError,
|
||||||
|
username: Option<&Username>,
|
||||||
|
email: &Email,
|
||||||
|
exclude_id: Option<i32>,
|
||||||
|
) -> AuthError {
|
||||||
|
let AuthError::Database(db_err) = &err else {
|
||||||
|
return err;
|
||||||
|
};
|
||||||
|
if !matches!(db_err.sql_err(), Some(SqlErr::UniqueConstraintViolation(_))) {
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
if let Some(username) = username
|
||||||
|
&& let Err(taken) = ensure_username_available(username, exclude_id).await
|
||||||
|
{
|
||||||
|
return taken;
|
||||||
|
}
|
||||||
|
match ensure_email_available(email, exclude_id).await {
|
||||||
|
Err(taken) => taken,
|
||||||
|
Ok(()) => err,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Comprueba si `user_id` es actualmente el único usuario con `is_admin = true`.
|
// Comprueba si `user_id` es actualmente el único usuario con `is_admin = true`.
|
||||||
async fn is_last_administrator(user_id: i32) -> Result<bool, AuthError> {
|
async fn is_last_administrator(user_id: i32) -> Result<bool, AuthError> {
|
||||||
let user = find_user(user_id).await?;
|
let user = find_user(user_id).await?;
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue