diff --git a/src/controllers/routes.rs b/src/controllers/routes.rs index 51fe7e7..a05bd6f 100644 --- a/src/controllers/routes.rs +++ b/src/controllers/routes.rs @@ -103,6 +103,7 @@ pub fn get_routes() -> Vec { Route::post("/settings/check_password", Box::new(settings_controller::check_password)), Route::post("/settings/update_password", Box::new(settings_controller::update_password)), Route::post("/settings/get_account_image", Box::new(settings_controller::get_account_image_settings)), + Route::post("/settings/upload_account_image", Box::new(settings_controller::upload_account_image)), // Friends controller diff --git a/src/controllers/settings_controller.rs b/src/controllers/settings_controller.rs index 1fdda4b..682f769 100644 --- a/src/controllers/settings_controller.rs +++ b/src/controllers/settings_controller.rs @@ -142,4 +142,17 @@ pub fn get_account_image_settings(r: &mut HttpRequestHandler) -> RequestResult { let user = user_helper::find_user_by_id(r.user_id_ref()?)?; r.set_response(AccountImageSettingsAPI::new(&user)) +} + +/// Upload a new account image +pub fn upload_account_image(r: &mut HttpRequestHandler) -> RequestResult { + if !r.has_file("picture") { + return r.bad_request("An error occurred while receiving the image !".to_string()) + } + + let uri = r.save_post_image("picture", "avatars", 800, 800)?; + + account_helper::set_account_image(r.user_id_ref()?, &uri)?; + + r.success("Account image updated!") } \ No newline at end of file diff --git a/src/helpers/account_helper.rs b/src/helpers/account_helper.rs index 32b78b6..2e1cbae 100644 --- a/src/helpers/account_helper.rs +++ b/src/helpers/account_helper.rs @@ -13,6 +13,7 @@ use crate::helpers::database::{DeleteQuery, InsertQuery, QueryInfo}; use crate::utils::crypt_utils::{crypt_pass, rand_str}; use crate::utils::date_utils::{mysql_date, time}; use crate::data::security_settings::SecuritySettings; +use crate::utils::user_data_utils::user_data_path; /// Account helper /// @@ -232,6 +233,39 @@ pub fn set_security_settings(settings: &SecuritySettings) -> ResultBoxError { .exec() } +/// Delete user account image +pub fn delete_account_image(user_id: &UserID) -> ResultBoxError { + let user = user_helper::find_user_by_id(user_id)?; + + if !user.has_account_image() { + return Ok(()); + } + + let path = user_data_path(user.account_image_path.unwrap().as_ref()); + + if path.exists() + { + std::fs::remove_file(path)?; + } + + database::UpdateInfo::new(USERS_TABLE) + .cond_user_id("ID", user_id) + .set_str("account_image_path", "") + .exec() +} + +/// Set a new account image +pub fn set_account_image(user_id: &UserID, uri: &String) -> ResultBoxError { + // First, delete the previous account image + delete_account_image(user_id)?; + + // Update database + database::UpdateInfo::new(USERS_TABLE) + .cond_user_id("ID", user_id) + .set_str("account_image_path", uri) + .exec() +} + /// Export an account's data pub fn export(user_id: &UserID) -> ResultBoxError { let mut data = AccountExport {