update user channels, fix #721

This commit is contained in:
jb-alvarado 2024-08-21 12:18:15 +02:00
parent b63cdb9888
commit a1cc272697
3 changed files with 28 additions and 20 deletions

View File

@ -309,6 +309,7 @@ async fn update_user(
role: AuthDetails<Role>,
user: web::ReqData<UserMeta>,
) -> Result<impl Responder, ServiceError> {
let channel_ids = data.channel_ids.clone().unwrap_or_default();
let mut fields = String::new();
if let Some(mail) = data.mail.clone() {
@ -319,21 +320,6 @@ async fn update_user(
fields.push_str(&format!("mail = '{mail}'"));
}
if let Some(channel_ids) = &data.channel_ids {
if !fields.is_empty() {
fields.push_str(", ");
}
fields.push_str(&format!(
"channel_ids = '{}'",
channel_ids
.iter()
.map(|i| i.to_string())
.collect::<Vec<String>>()
.join(",")
));
}
if !data.password.is_empty() {
if !fields.is_empty() {
fields.push_str(", ");
@ -354,11 +340,19 @@ async fn update_user(
fields.push_str(&format!("password = '{password_hash}'"));
}
if handles::update_user(&pool, *id, fields).await.is_ok() {
return Ok("Update Success");
};
handles::update_user(&pool, *id, fields).await?;
Err(ServiceError::InternalServerError)
let related_channels = handles::select_related_channels(&pool, Some(*id)).await?;
for channel in related_channels {
if !channel_ids.contains(&channel.id) {
handles::delete_user_channel(&pool, *id, channel.id).await?;
}
}
handles::insert_user_channel(&pool, *id, channel_ids).await?;
Ok("Update Success")
}
/// **Add User**

View File

@ -94,6 +94,20 @@ pub async fn select_related_channels(
Ok(results)
}
pub async fn delete_user_channel(
conn: &Pool<Sqlite>,
user_id: i32,
channel_id: i32,
) -> Result<SqliteQueryResult, sqlx::Error> {
let query = "DELETE FROM user_channels WHERE user_id = $1 AND channel_id = $2";
sqlx::query(query)
.bind(user_id)
.bind(channel_id)
.execute(conn)
.await
}
pub async fn update_channel(
conn: &Pool<Sqlite>,
id: i32,

@ -1 +1 @@
Subproject commit 2045e47ab5e9f42ff73e03a7c4c604821a73f7ca
Subproject commit e9eff70158431a69080bb192a5bb793b0475938a