use ibridge_core::AppleId;
use secrecy::{ExposeSecret, SecretString};
#[derive(Debug)]
pub struct Credentials {
pub apple_id: AppleId,
secret: SecretString,
}
impl Credentials {
#[must_use]
pub fn new(apple_id: AppleId, secret: impl Into<SecretString>) -> Self {
Self {
apple_id,
secret: secret.into(),
}
}
#[must_use]
pub fn duplicate(&self) -> Self {
self.with_secret(|secret| Self::new(self.apple_id.clone(), secret.to_owned()))
}
pub fn with_secret<T>(&self, read: impl FnOnce(&str) -> T) -> T {
read(self.secret.expose_secret())
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum AuthMethod {
AppPassword(Credentials),
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum AuthError {
#[error("validation failed")]
Validation,
#[error("credentials are unavailable")]
Unavailable,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ServiceCheck {
Ok,
Failed {
reason: String,
},
Unreachable {
reason: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationReport {
pub mail: ServiceCheck,
pub calendar: ServiceCheck,
pub contacts: ServiceCheck,
}
impl ValidationReport {
#[must_use]
pub fn any_service_ok(&self) -> bool {
matches!(self.mail, ServiceCheck::Ok)
|| matches!(self.calendar, ServiceCheck::Ok)
|| matches!(self.contacts, ServiceCheck::Ok)
}
}
#[trait_variant::make(Send)]
pub trait Validator {
async fn validate(&self) -> Result<ValidationReport, AuthError>;
}
#[cfg(test)]
mod tests {
use ibridge_core::AppleId;
use super::Credentials;
#[test]
fn duplicate_carries_the_apple_id_and_password() {
let original = Credentials::new(
AppleId::try_from("ada@icloud.com").expect("primary address"),
"abcd-efgh-ijkl-mnop",
);
let copy = original.duplicate();
assert_eq!(copy.apple_id, original.apple_id);
assert_eq!(
copy.with_secret(str::to_owned),
"abcd-efgh-ijkl-mnop",
"the copy signs in as the original does"
);
}
}