From 98e748ca7b50ff0dec6b475911adf133a2cc3721 Mon Sep 17 00:00:00 2001 From: Sphereso Date: Fri, 12 Jul 2024 01:29:57 +0200 Subject: [PATCH] backend: update user endpoint --- crates/backend/src/controller/user.rs | 52 +++++++++++++++++++++++++++ crates/backend/src/routes.rs | 6 +++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/crates/backend/src/controller/user.rs b/crates/backend/src/controller/user.rs index ebea0cd..a278511 100644 --- a/crates/backend/src/controller/user.rs +++ b/crates/backend/src/controller/user.rs @@ -29,6 +29,13 @@ pub struct CreateUserDto { password: String, admin: bool, } +#[derive(Deserialize)] +pub struct UpdateUserDto { + name: String, + email: String, + password: Option, + admin: Option, +} impl From for UserWithoutPassword { fn from(value: entity::user::Model) -> Self { @@ -119,4 +126,49 @@ impl UserController { .map_err(ErrorInternalServerError)?; Ok(HttpResponse::Ok().finish()) } + + pub async fn update_user( + state: web::Data, + path: web::Path, + executor: AuthedUser, + user: web::Json, + ) -> actix_web::Result { + let id = path.into_inner(); + let db = &state.db; + let user = user.into_inner(); + let is_current_user = executor.0.id == id; + if executor.0.admin || is_current_user { + let hash: ActiveValue = if let Some(new_password) = user.password { + let salt = SaltString::generate(&mut OsRng); + let argon2 = Argon2::default(); + + let password_hash = argon2 + .hash_password(new_password.as_bytes(), &salt) + .map_err(ErrorInternalServerError)?; + + ActiveValue::Set(password_hash.to_string()) + } else { + ActiveValue::NotSet + }; + let user = entity::user::ActiveModel { + id: ActiveValue::Unchanged(id), + email: ActiveValue::Set(user.email), + name: ActiveValue::Set(user.name), + admin: if executor.0.admin { + if let Some(a) = user.admin { + ActiveValue::Set(a) + } else { + ActiveValue::NotSet + } + } else { + ActiveValue::NotSet + }, + hash, + }; + let res = user.update(db).await.map_err(ErrorInternalServerError)?; + Ok(web::Json(res)) + } else { + Err(ErrorUnauthorized("Unauthorized")) + } + } } diff --git a/crates/backend/src/routes.rs b/crates/backend/src/routes.rs index 35f8700..4eaf1a1 100644 --- a/crates/backend/src/routes.rs +++ b/crates/backend/src/routes.rs @@ -10,7 +10,11 @@ pub fn config(cfg: &mut web::ServiceConfig) { .post(UserController::create_user), ) .route("/users/me", web::get().to(UserController::get_current_user)) - .service(web::resource("/users/{user_id}").delete(UserController::delete_user)) + .service( + web::resource("/users/{user_id}") + .delete(UserController::delete_user) + .put(UserController::update_user), + ) .service( web::resource("/licenses") .get(LicenseController::list_groups)