//! # Administration accounts helper //! //! @author Pierre Hubert use crate::constants::{ADMIN_RESET_TOKEN_LENGTH, ADMIN_RESET_TOKEN_LIFETIME}; use crate::constants::database_tables_names::ADMIN_LIST_TABLE; use crate::data::admin::{Admin, AdminID, AdminResetToken, NewAdmin, NewAdminGeneralSettings}; use crate::data::error::{ExecError, Res}; use crate::helpers::database; use crate::utils::crypt_utils::rand_str; use crate::utils::date_utils::time; /// Create a new admin account pub fn create(new_admin: &NewAdmin) -> Res { if find_admin_by_email(&new_admin.email).is_ok() { return Err(ExecError::boxed_new("An other admin account already holds the same email address!")); } database::InsertQuery::new(ADMIN_LIST_TABLE) .add_u64("time_create", time()) .add_str("name", &new_admin.name) .add_str("email", &new_admin.email) .insert_expect_result() .map(|i| AdminID::new(i)) } /// Check out whether an admin exists or not pub fn exists(id: AdminID) -> Res { database::QueryInfo::new(ADMIN_LIST_TABLE) .cond_admin_id("id", id) .exec_count() .map(|r| r > 0) } /// Get admin information by ID pub fn find_admin_by_id(id: AdminID) -> Res { database::QueryInfo::new(ADMIN_LIST_TABLE) .cond_admin_id("id", id) .query_row(db_to_admin) } /// Get admin information by admin email address pub fn find_admin_by_email(email: &str) -> Res { database::QueryInfo::new(ADMIN_LIST_TABLE) .cond("email", email) .query_row(db_to_admin) } /// Create a new reset token for an admin pub fn create_new_reset_token(id: AdminID) -> Res { let token = AdminResetToken { token: rand_str(ADMIN_RESET_TOKEN_LENGTH), expire: time() + ADMIN_RESET_TOKEN_LIFETIME, }; database::UpdateInfo::new(ADMIN_LIST_TABLE) .cond_admin_id("id", id) .set_str("reset_token", &token.token) .set_u64("reset_token_expire", token.expire) .exec()?; Ok(token) } /// Update admin general settings pub fn set_general_settings(settings: NewAdminGeneralSettings) -> Res { database::UpdateInfo::new(ADMIN_LIST_TABLE) .cond_admin_id("id", settings.id) .set_str("name", &settings.name) .set_str("email", &settings.email) .exec() } /// Turn a database entry into an admin structure fn db_to_admin(row: &database::RowResult) -> Res { let reset_token_expire = row.get_optional_u64("reset_token_expire")? .unwrap_or(0); let reset_token = if reset_token_expire < time() { None } else { Some(AdminResetToken { token: row.get_str("reset_token")?, expire: row.get_u64("reset_token_expire")?, }) }; Ok(Admin { id: row.get_admin_id("id")?, time_create: row.get_u64("time_create")?, name: row.get_str("name")?, email: row.get_str("email")?, reset_token, }) }