use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use id_effect::{Effect, fail, succeed, suspend};
use super::AccountError;
use crate::apikey::random_hex;
use crate::password::PasswordHash;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Account {
pub id: String,
pub email: String,
pub email_verified: bool,
}
pub trait AccountStore: Send + Sync + 'static {
fn find_by_email(&self, email: &str) -> Effect<Option<Account>, AccountError>;
fn create(&self, email: &str, password: &PasswordHash) -> Effect<Account, AccountError>;
fn set_password(
&self,
id: &str,
password: &PasswordHash,
) -> Effect<Option<Account>, AccountError>;
fn mark_verified(&self, id: &str) -> Effect<Option<Account>, AccountError>;
}
#[derive(Default)]
struct MemoryAccountsState {
accounts: HashMap<String, (Account, PasswordHash)>,
fail: Option<String>,
}
#[derive(Clone, Default)]
pub struct MemoryAccountStore {
inner: Arc<Mutex<MemoryAccountsState>>,
}
impl fmt::Debug for MemoryAccountStore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MemoryAccountStore")
.field("len", &self.len())
.finish()
}
}
impl MemoryAccountStore {
#[inline]
pub fn new() -> Self {
Self::default()
}
fn state(&self) -> MutexGuard<'_, MemoryAccountsState> {
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn len(&self) -> usize {
self.state().accounts.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn get(&self, id: &str) -> Option<Account> {
self.state().accounts.get(id).map(|(a, _)| a.clone())
}
pub fn password_hash(&self, id: &str) -> Option<PasswordHash> {
self.state().accounts.get(id).map(|(_, h)| h.clone())
}
pub fn fail_with(&self, message: Option<&str>) {
self.state().fail = message.map(str::to_owned);
}
fn with<A: Send + 'static>(
&self,
f: impl FnOnce(&mut HashMap<String, (Account, PasswordHash)>) -> Result<A, AccountError>
+ Send
+ 'static,
) -> Effect<A, AccountError> {
let this = self.clone();
suspend(move || {
let mut st = this.state();
let result = match st.fail.clone() {
Some(m) => Err(AccountError::Storage(m)),
None => f(&mut st.accounts),
};
match result {
Ok(a) => succeed(a),
Err(e) => fail(e),
}
})
}
}
impl AccountStore for MemoryAccountStore {
fn find_by_email(&self, email: &str) -> Effect<Option<Account>, AccountError> {
let email = email.to_owned();
self.with(move |accounts| {
Ok(
accounts
.values()
.find(|(a, _)| a.email == email)
.map(|(a, _)| a.clone()),
)
})
}
fn create(&self, email: &str, password: &PasswordHash) -> Effect<Account, AccountError> {
let (email, password) = (email.to_owned(), password.clone());
self.with(move |accounts| {
if accounts.values().any(|(a, _)| a.email == email) {
return Err(AccountError::EmailTaken);
}
let id = random_hex(8).map_err(|e| AccountError::Random(e.to_string()))?;
let account = Account {
id: id.clone(),
email,
email_verified: false,
};
accounts.insert(id, (account.clone(), password));
Ok(account)
})
}
fn set_password(
&self,
id: &str,
password: &PasswordHash,
) -> Effect<Option<Account>, AccountError> {
let (id, password) = (id.to_owned(), password.clone());
self.with(move |accounts| {
Ok(accounts.get_mut(&id).map(|(a, h)| {
*h = password;
a.clone()
}))
})
}
fn mark_verified(&self, id: &str) -> Effect<Option<Account>, AccountError> {
let id = id.to_owned();
self.with(move |accounts| {
Ok(accounts.get_mut(&id).map(|(a, _)| {
a.email_verified = true;
a.clone()
}))
})
}
}