backend: update user endpoint
This commit is contained in:
parent
c6074c26e0
commit
98e748ca7b
2 changed files with 57 additions and 1 deletions
|
@ -29,6 +29,13 @@ pub struct CreateUserDto {
|
|||
password: String,
|
||||
admin: bool,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
pub struct UpdateUserDto {
|
||||
name: String,
|
||||
email: String,
|
||||
password: Option<String>,
|
||||
admin: Option<bool>,
|
||||
}
|
||||
|
||||
impl From<entity::user::Model> 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<AppState>,
|
||||
path: web::Path<Uuid>,
|
||||
executor: AuthedUser,
|
||||
user: web::Json<UpdateUserDto>,
|
||||
) -> actix_web::Result<impl Responder> {
|
||||
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<String> = 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"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
|
|
Loading…
Reference in a new issue