//! # Admin : users management controller //! //! @author Pierre Hubert use crate::api_data::admin::admin_create_password_reset_link_api::AdminCreatedPasswordResetLinkApi; use crate::api_data::admin::admin_search_user_result_api::AdminSearchUserResult; use crate::api_data::admin::admin_user_info_api::AdminUserInfoAPI; use crate::constants::admin::AdminRole; use crate::data::admin_action_log::AdminAction; use crate::data::base_request_handler::BaseRequestHandler; use crate::data::config::conf; use crate::data::http_request_handler::HttpRequestHandler; use crate::helpers::admin_log_helper::log_admin_action; use crate::helpers::{account_helper, user_helper}; use crate::routes::RequestResult; /// Search for user pub async fn search(r: &mut HttpRequestHandler) -> RequestResult { r.check_admin_has_role(AdminRole::MANAGE_USERS)?; let name = r.post_string_opt("name", 0, true)?; let email = r.post_string_opt("email", 0, true)?; let results = user_helper::search_user_admin(&name, &email, 50)?; r.set_response( results .into_iter() .map(AdminSearchUserResult::new) .collect::>(), ) } /// Get information about a single user pub async fn get_single(r: &mut HttpRequestHandler) -> RequestResult { r.check_admin_has_role(AdminRole::MANAGE_USERS)?; let user_id = r.post_user_id("user_id")?; let user = user_helper::find_user_by_id(&user_id)?; log_admin_action( r.admin_id()?, &r.remote_ip(), AdminAction::AccessUserPage { user_id, user_name: user.full_name(), }, )?; r.set_response(AdminUserInfoAPI::new(user)) } /// Change the email address of a Comunic user pub async fn change_email_address(r: &mut HttpRequestHandler) -> RequestResult { r.check_admin_has_role(AdminRole::MANAGE_USERS)?; let user_id = r.post_user_id("user_id")?; let user = user_helper::find_user_by_id(&user_id)?; let new_mail = r.post_email("new_mail")?; // We check if the email address is already used if user_helper::find_user_by_email(&new_mail).is_ok() { r.bad_request(format!( "The email address {} is already attributed!", new_mail ))?; } // Do the update account_helper::set_email(user_id, &new_mail)?; log_admin_action( r.admin_id()?, &r.remote_ip(), AdminAction::ChangedEmailAddress { user_id, user_name: user.full_name(), old_mail: user.email, new_mail, }, )?; r.ok() } /// Create a password reset link for a Comunic user pub async fn create_password_reset_link(r: &mut HttpRequestHandler) -> RequestResult { r.check_admin_has_role(AdminRole::MANAGE_USERS)?; let user_id = r.post_user_id("user_id")?; let user = user_helper::find_user_by_id(&user_id)?; let token = account_helper::generate_password_reset_token(&user_id)?; let reset_link = conf().password_reset_url.replace("{TOKEN}", &token); log_admin_action( r.admin_id()?, &r.remote_ip(), AdminAction::CreatePasswordRecoveryLink { user_id, user_name: user.full_name(), }, )?; r.set_response(AdminCreatedPasswordResetLinkApi::new(reset_link)) }