🐛 (user): Crea usuario + roles de forma atómica
Inserta los roles en una sola sentencia y retira assign_role(), que sólo usaba la demo.
This commit is contained in:
parent
1577891fe3
commit
d7efb80856
3 changed files with 61 additions and 58 deletions
|
|
@ -8,7 +8,7 @@ use pagetop_seaorm::db::{
|
||||||
|
|
||||||
use crate::account::UserStatus;
|
use crate::account::UserStatus;
|
||||||
use crate::config::SETTINGS;
|
use crate::config::SETTINGS;
|
||||||
use crate::entity::{role_permission, user, user_role};
|
use crate::entity::{role_permission, user};
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
use crate::password;
|
use crate::password;
|
||||||
use crate::permission::UserPermission;
|
use crate::permission::UserPermission;
|
||||||
|
|
@ -153,32 +153,6 @@ pub async fn register(
|
||||||
Ok(user_id)
|
Ok(user_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< assign_role >********************************************************************************
|
|
||||||
|
|
||||||
/// Asigna un rol a un usuario (sin error si ya está asignado).
|
|
||||||
///
|
|
||||||
/// Los roles de sistema ("anonymous" y "authenticated") no se asignan nunca: se ignoran.
|
|
||||||
pub async fn assign_role(user_id: i32, role_id: i32) -> Result<(), AuthError> {
|
|
||||||
if crate::is_system_role(role_id) {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let already = user_role::Entity::find()
|
|
||||||
.filter(user_role::Column::UserId.eq(user_id))
|
|
||||||
.filter(user_role::Column::RoleId.eq(role_id))
|
|
||||||
.one(dbconn())
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
if already.is_none() {
|
|
||||||
user_role::Entity::insert(user_role::ActiveModel {
|
|
||||||
user_id: Set(user_id),
|
|
||||||
role_id: Set(role_id),
|
|
||||||
})
|
|
||||||
.exec(dbconn())
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
// **< change_own_password >************************************************************************
|
// **< change_own_password >************************************************************************
|
||||||
|
|
||||||
/// Cambia la contraseña del propio usuario tras comprobar la actual, y cierra el resto de sus
|
/// Cambia la contraseña del propio usuario tras comprobar la actual, y cierra el resto de sus
|
||||||
|
|
|
||||||
|
|
@ -8,8 +8,7 @@ use pagetop::prelude::*;
|
||||||
use pagetop_seaorm::db::{ActiveValue, ColumnTrait, EntityTrait, QueryFilter, Set, dbconn};
|
use pagetop_seaorm::db::{ActiveValue, ColumnTrait, EntityTrait, QueryFilter, Set, dbconn};
|
||||||
|
|
||||||
use crate::account::UserStatus;
|
use crate::account::UserStatus;
|
||||||
use crate::auth;
|
use crate::entity::{role, user, user_role};
|
||||||
use crate::entity::{role, user};
|
|
||||||
use crate::error::AuthError;
|
use crate::error::AuthError;
|
||||||
use crate::password;
|
use crate::password;
|
||||||
|
|
||||||
|
|
@ -105,8 +104,12 @@ async fn create_demo_users(role_ids: &[i32]) -> Result<(), AuthError> {
|
||||||
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.
|
||||||
let role_id = role_ids[(n - 1) % role_ids.len()];
|
user_role::Entity::insert(user_role::ActiveModel {
|
||||||
auth::assign_role(user_id, role_id).await?;
|
user_id: Set(user_id),
|
||||||
|
role_id: Set(role_ids[(n - 1) % role_ids.len()]),
|
||||||
|
})
|
||||||
|
.exec_without_returning(dbconn())
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -4,9 +4,9 @@ use std::collections::HashMap;
|
||||||
|
|
||||||
use pagetop::prelude::*;
|
use pagetop::prelude::*;
|
||||||
use pagetop_seaorm::db::{
|
use pagetop_seaorm::db::{
|
||||||
ActiveModelTrait, ActiveValue, ColumnTrait, Condition, EntityTrait, Order, Paginated,
|
ActiveModelTrait, ActiveValue, ColumnTrait, Condition, DatabaseTransaction, DbErr, EntityTrait,
|
||||||
PaginatorTrait, QueryFilter, QueryOrder, Set, TransactionTrait, dbconn, flatten_txn_err,
|
Order, Paginated, PaginatorTrait, QueryFilter, QueryOrder, Set, TransactionTrait, dbconn,
|
||||||
paginate,
|
flatten_txn_err, paginate,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::account::UserStatus;
|
use crate::account::UserStatus;
|
||||||
|
|
@ -171,7 +171,10 @@ pub(crate) struct NewUserData<'a> {
|
||||||
|
|
||||||
/// Da de alta un usuario administrativamente. A diferencia de `auth::register`, el usuario queda
|
/// Da de alta un usuario administrativamente. A diferencia de `auth::register`, el usuario queda
|
||||||
/// activo y con el email verificado de inmediato (lo crea un administrador de confianza), y admite
|
/// activo y con el email verificado de inmediato (lo crea un administrador de confianza), y admite
|
||||||
/// asignar roles iniciales.
|
/// asignar roles iniciales (los de sistema se descartan, ver [`set_user_roles`]).
|
||||||
|
///
|
||||||
|
/// El usuario y sus roles se crean en una sola transacción: si falla cualquier inserción (p. ej.
|
||||||
|
/// porque se ha eliminado uno de los roles mientras tanto), no se crea nada.
|
||||||
pub(crate) async fn create_user(data: NewUserData<'_>) -> Result<i32, AuthError> {
|
pub(crate) async fn create_user(data: NewUserData<'_>) -> Result<i32, AuthError> {
|
||||||
password::validate_strength(data.password)?;
|
password::validate_strength(data.password)?;
|
||||||
password::passwords_match(data.password, data.confirm_password)?;
|
password::passwords_match(data.password, data.confirm_password)?;
|
||||||
|
|
@ -214,14 +217,21 @@ pub(crate) async fn create_user(data: NewUserData<'_>) -> Result<i32, AuthError>
|
||||||
created_at: Set(now),
|
created_at: Set(now),
|
||||||
updated_at: Set(now),
|
updated_at: Set(now),
|
||||||
};
|
};
|
||||||
let result = user::Entity::insert(new_user).exec(dbconn()).await?;
|
let role_ids = assignable_roles(data.initial_role_ids);
|
||||||
let user_id = result.last_insert_id;
|
|
||||||
|
|
||||||
for role_id in data.initial_role_ids {
|
dbconn()
|
||||||
crate::auth::assign_role(user_id, *role_id).await?;
|
.transaction::<_, _, AuthError>(|txn| {
|
||||||
}
|
Box::pin(async move {
|
||||||
|
let user_id = user::Entity::insert(new_user)
|
||||||
Ok(user_id)
|
.exec(txn)
|
||||||
|
.await?
|
||||||
|
.last_insert_id;
|
||||||
|
insert_user_roles(txn, user_id, role_ids).await?;
|
||||||
|
Ok(user_id)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(flatten_txn_err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// **< update_user >********************************************************************************
|
// **< update_user >********************************************************************************
|
||||||
|
|
@ -301,14 +311,7 @@ pub(crate) async fn update_user(user_id: i32, data: UserUpdateData<'_>) -> Resul
|
||||||
/// peticiones sin sesión.
|
/// peticiones sin sesión.
|
||||||
pub(crate) async fn set_user_roles(user_id: i32, role_ids: &[i32]) -> Result<(), AuthError> {
|
pub(crate) async fn set_user_roles(user_id: i32, role_ids: &[i32]) -> Result<(), AuthError> {
|
||||||
find_user(user_id).await?;
|
find_user(user_id).await?;
|
||||||
|
let role_ids = assignable_roles(role_ids);
|
||||||
let mut role_ids: Vec<i32> = role_ids
|
|
||||||
.iter()
|
|
||||||
.copied()
|
|
||||||
.filter(|id| !crate::is_system_role(*id))
|
|
||||||
.collect();
|
|
||||||
role_ids.sort_unstable();
|
|
||||||
role_ids.dedup();
|
|
||||||
|
|
||||||
dbconn()
|
dbconn()
|
||||||
.transaction::<_, _, AuthError>(|txn| {
|
.transaction::<_, _, AuthError>(|txn| {
|
||||||
|
|
@ -317,14 +320,7 @@ pub(crate) async fn set_user_roles(user_id: i32, role_ids: &[i32]) -> Result<(),
|
||||||
.filter(user_role::Column::UserId.eq(user_id))
|
.filter(user_role::Column::UserId.eq(user_id))
|
||||||
.exec(txn)
|
.exec(txn)
|
||||||
.await?;
|
.await?;
|
||||||
for role_id in role_ids {
|
insert_user_roles(txn, user_id, role_ids).await?;
|
||||||
user_role::Entity::insert(user_role::ActiveModel {
|
|
||||||
user_id: Set(user_id),
|
|
||||||
role_id: Set(role_id),
|
|
||||||
})
|
|
||||||
.exec(txn)
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
@ -332,6 +328,36 @@ pub(crate) async fn set_user_roles(user_id: i32, role_ids: &[i32]) -> Result<(),
|
||||||
.map_err(flatten_txn_err)
|
.map_err(flatten_txn_err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Roles de `role_ids` que pueden asignarse a un usuario: sin los de sistema y sin repetidos.
|
||||||
|
fn assignable_roles(role_ids: &[i32]) -> Vec<i32> {
|
||||||
|
let mut role_ids: Vec<i32> = role_ids
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.filter(|id| !crate::is_system_role(*id))
|
||||||
|
.collect();
|
||||||
|
role_ids.sort_unstable();
|
||||||
|
role_ids.dedup();
|
||||||
|
role_ids
|
||||||
|
}
|
||||||
|
|
||||||
|
// Asigna los roles al usuario en una sola sentencia, dentro de la transacción indicada.
|
||||||
|
async fn insert_user_roles(
|
||||||
|
txn: &DatabaseTransaction,
|
||||||
|
user_id: i32,
|
||||||
|
role_ids: Vec<i32>,
|
||||||
|
) -> Result<(), DbErr> {
|
||||||
|
if role_ids.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
user_role::Entity::insert_many(role_ids.into_iter().map(|role_id| user_role::ActiveModel {
|
||||||
|
user_id: Set(user_id),
|
||||||
|
role_id: Set(role_id),
|
||||||
|
}))
|
||||||
|
.exec_without_returning(txn)
|
||||||
|
.await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
// **< set_user_status >****************************************************************************
|
// **< set_user_status >****************************************************************************
|
||||||
|
|
||||||
/// Cambia el estado de la cuenta. Rechaza que un usuario se bloquee a sí mismo o bloquee al último
|
/// Cambia el estado de la cuenta. Rechaza que un usuario se bloquee a sí mismo o bloquee al último
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue