use crate::account::credential::{CredentialModel, CredentialRepository};
use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::Mutex;
#[derive(Default)]
pub struct MockCredentialRepository {
store: Mutex<HashMap<String, CredentialModel>>,
}
#[async_trait]
impl CredentialRepository for MockCredentialRepository {
async fn create(&self, credential: CredentialModel) -> GarrisonResult<()> {
let mut store = self.store.lock().unwrap();
if store.contains_key(&credential.id) {
return Err(GarrisonError::InvalidParam(format!(
"credential-already-exists::{}",
credential.id
)));
}
store.insert(credential.id.clone(), credential);
Ok(())
}
async fn find_by_user(
&self,
caller_login_id: &str,
user_id: &str,
) -> GarrisonResult<Vec<CredentialModel>> {
if caller_login_id != user_id {
return Err(GarrisonError::NotPermission(format!(
"credential-query-forbidden::{}::{}",
caller_login_id, user_id
)));
}
let store = self.store.lock().unwrap();
let mut creds: Vec<CredentialModel> = store
.values()
.filter(|c| c.user_id == user_id)
.cloned()
.collect();
creds.sort_by_key(|c| c.priority);
Ok(creds)
}
async fn find_by_user_and_type(
&self,
user_id: &str,
cred_type: &str,
) -> GarrisonResult<Vec<CredentialModel>> {
let all = self.find_by_user(user_id, user_id).await?;
Ok(all
.into_iter()
.filter(|c| c.credential_type == cred_type)
.collect())
}
async fn update(
&self,
caller_login_id: &str,
credential: CredentialModel,
) -> GarrisonResult<()> {
let mut store = self.store.lock().unwrap();
let existing = match store.get(&credential.id) {
Some(m) => m.clone(),
None => {
return Err(GarrisonError::InvalidParam(format!(
"credential-not-found::{}",
credential.id
)));
},
};
if existing.user_id != caller_login_id {
return Err(GarrisonError::NotPermission(format!(
"credential-update-forbidden::{}::{} (owner {})",
caller_login_id, credential.id, existing.user_id
)));
}
if credential.user_id != existing.user_id {
return Err(GarrisonError::NotPermission(format!(
"credential-transfer-forbidden::{}::{} -> {}",
credential.id, existing.user_id, credential.user_id
)));
}
store.insert(credential.id.clone(), credential);
Ok(())
}
async fn delete(&self, caller_login_id: &str, credential_id: &str) -> GarrisonResult<()> {
let mut store = self.store.lock().unwrap();
let existing = match store.get(credential_id) {
Some(m) => m.clone(),
None => {
return Err(GarrisonError::InvalidParam(format!(
"credential-not-found::{}",
credential_id
)));
},
};
if existing.user_id != caller_login_id {
return Err(GarrisonError::NotPermission(format!(
"credential-delete-forbidden::{}::{} (owner {})",
caller_login_id, credential_id, existing.user_id
)));
}
store.remove(credential_id);
Ok(())
}
}