rsub 0.1.0

A high-performance message broker with QUIC transport and pub/sub messaging patterns
Documentation
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_yaml;

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(tag = "type", content = "config")]
pub enum AuthType {
    #[default]
    None,
    Basic(BasicAuth),
    Bearer(BearerAuth),
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BasicAuth {
    pub username: String,
    pub password: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BearerAuth {
    pub token: String,
}

impl AuthType {
    pub fn validate(&self, provided_auth: &str) -> bool {
        match self {
            AuthType::None => true,
            AuthType::Basic(auth) => {
                format!("{}:{}", auth.username, auth.password) == provided_auth
            }
            AuthType::Bearer(auth) => provided_auth == auth.token,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct AuthConfig {
    #[serde(flatten)]
    pub auth_type: AuthType,
}

impl AuthConfig {
    pub fn new(auth_type: AuthType) -> Self {
        AuthConfig { auth_type }
    }

    pub fn validate(&self, provided_auth: &str) -> bool {
        self.auth_type.validate(provided_auth)
    }

    pub fn to_yaml(&self) -> Result<String> {
        Ok(serde_yaml::to_string(self)?)
    }

    pub fn from_yaml(yaml: &str) -> Result<Self> {
        Ok(serde_yaml::from_str(yaml)?)
    }
}