/ backend / src / services / whitelist_service.rs
whitelist_service.rs
 1  use rocket::State;
 2  use sqlx::Pool;
 3  
 4  use crate::{
 5      db::{new_transaction, whitelist_repository, DB},
 6      models::whitelist::Whitelist,
 7      util::accounts_error::AccountsError,
 8  };
 9  
10  #[derive(Debug, thiserror::Error)]
11  pub enum WhitelistError {
12      #[error("An internal error occured")]
13      Internal,
14  }
15  
16  impl From<sqlx::Error> for WhitelistError {
17      fn from(_: sqlx::Error) -> Self {
18          WhitelistError::Internal
19      }
20  }
21  
22  impl From<AccountsError> for WhitelistError {
23      fn from(_: AccountsError) -> Self {
24          WhitelistError::Internal
25      }
26  }
27  
28  pub async fn get_whitelisted_emails(
29      db_pool: &State<Pool<DB>>,
30  ) -> Result<Vec<Whitelist>, WhitelistError> {
31      let mut transaction = new_transaction(db_pool).await?;
32  
33      let emails = whitelist_repository::get_all_whitelisted_emails(&mut transaction)
34          .await
35          .map_err(|err| {
36              error!("Failed to get whitelisted emails, err: {}", err);
37              err
38          })?;
39  
40      Ok(emails)
41  }
42  
43  pub async fn add_to_whitelist(
44      db_pool: &State<Pool<DB>>,
45      email: String,
46  ) -> Result<Whitelist, WhitelistError> {
47      let mut transaction = new_transaction(db_pool).await?;
48  
49      let email = whitelist_repository::add_email_to_local_whitelist(&mut transaction, email)
50          .await
51          .map_err(|err| {
52              error!("Failed to insert email into local whitelist, err {}", err);
53              err
54          })?;
55  
56      transaction.commit().await?;
57  
58      Ok(email)
59  }
60  
61  pub async fn delete_from_whitelist(
62      db_pool: &State<Pool<DB>>,
63      email: String,
64  ) -> Result<(), WhitelistError> {
65      let mut transaction = new_transaction(db_pool).await?;
66  
67      whitelist_repository::remove_email(&mut transaction, email)
68          .await
69          .map_err(|err| {
70              error!("Failed to delete email from whitelist, err {}", err);
71              err
72          })?;
73  
74      transaction.commit().await?;
75  
76      Ok(())
77  }