Skip to content
This repository was archived by the owner on Sep 5, 2024. It is now read-only.

Commit

Permalink
feat(db/user): Delete user
Browse files Browse the repository at this point in the history
  • Loading branch information
pan93412 committed Aug 25, 2024
1 parent ae733b1 commit c007d4e
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/db/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,34 @@ pub async fn get_or_initialize_user(conn: impl Acquire<'_>, user_id: &str) -> Re
Ok(created_user_info)
}

/// Mark the user as deleted.
///
/// You should also remove this user from the authentication service.
pub async fn delete_user(conn: impl Executor<'_>, user_id: &str) -> Result<(), Error> {
tracing::debug!("Deleting user");

let affected_rows = sqlx::query!(
r#"
UPDATE dp_users
SET deleted_at = now()
WHERE user_id = $1 AND deleted_at IS NULL
"#,
user_id,
)
.execute(conn)
.await?
.rows_affected();

if affected_rows == 0 {
return Err(Error::NotFound {
entity: "user",
id: eco_format!("{user_id}"),
});
}

Ok(())
}

pub struct GroupCreateParameter<'a> {
pub name: &'a str,
pub description: Option<&'a str>,
Expand Down
39 changes: 39 additions & 0 deletions tests/db_user_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,45 @@ mod test_get_or_initialize_user {
}
}

mod test_delete_user {
use std::assert_matches::assert_matches;

use sqlx::PgPool;

#[sqlx::test(fixtures("group", "user"))]
async fn test_delete_user(pool: PgPool) {
backend::db::delete_user(&pool, "usergroup1")
.await
.expect("failed to delete user");

let user = sqlx::query!(r#"SELECT deleted_at FROM dp_users WHERE user_id = 'usergroup1';"#)
.fetch_one(&pool)
.await
.expect("failed to fetch user");
assert!(user.deleted_at.is_some());
}

#[sqlx::test]
async fn test_delete_user_not_found(pool: PgPool) {
let user = backend::db::delete_user(&pool, "usernotfound0").await;

assert_matches!(
user,
Err(backend::db::Error::NotFound {
entity: "user",
id,
}) if id == "usernotfound0"
);
}

#[sqlx::test(fixtures("group", "user"))]
async fn test_delete_user_deleted(pool: PgPool) {
let user = backend::db::delete_user(&pool, "userdeleted0").await;

assert_matches!(user, Err(backend::db::Error::NotFound { entity: "user", id }) if id == "userdeleted0");
}
}

mod test_create_group {
use backend::db::GroupCreateParameter;
use sqlx::PgPool;
Expand Down

0 comments on commit c007d4e

Please sign in to comment.