zammad-api 0.4.0

Async, idiomatic Rust client for the Zammad Service Platform
Documentation
use reqwest::RequestBuilder;

/// Authentication strategy for the Zammad API.
///
/// Zammad accepts personal access tokens (`Token token=...`), OAuth bearer
/// tokens (`Bearer ...`) and HTTP Basic auth on every endpoint.
#[derive(Clone)]
pub enum Auth {
    /// Personal access token issued from a user's profile.
    Token(String),
    /// OAuth2 bearer token.
    Bearer(String),
    /// HTTP Basic auth.
    Basic {
        /// Username or login email.
        username: String,
        /// Password - `None` is valid (e.g. for token-as-username schemes).
        password: Option<String>,
    },
}

impl Auth {
    /// Build a personal-access-token credential.
    pub fn token(t: impl Into<String>) -> Self {
        Self::Token(t.into())
    }

    /// Build an OAuth2 bearer credential.
    pub fn bearer(t: impl Into<String>) -> Self {
        Self::Bearer(t.into())
    }

    /// Build an HTTP Basic credential with a password.
    pub fn basic(username: impl Into<String>, password: impl Into<String>) -> Self {
        Self::Basic {
            username: username.into(),
            password: Some(password.into()),
        }
    }

    /// Build an HTTP Basic credential without a password (some Zammad
    /// proxies accept a bare token as the username).
    pub fn basic_no_password(username: impl Into<String>) -> Self {
        Self::Basic {
            username: username.into(),
            password: None,
        }
    }

    pub(crate) fn apply(&self, req: RequestBuilder) -> RequestBuilder {
        match self {
            Self::Token(t) => req.header("Authorization", format!("Token token={t}")),
            Self::Bearer(t) => req.bearer_auth(t),
            Self::Basic { username, password } => req.basic_auth(username, password.as_deref()),
        }
    }
}

impl std::fmt::Debug for Auth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Token(_) => f.debug_tuple("Token").field(&"<redacted>").finish(),
            Self::Bearer(_) => f.debug_tuple("Bearer").field(&"<redacted>").finish(),
            Self::Basic { username, .. } => f
                .debug_struct("Basic")
                .field("username", username)
                .field("password", &"<redacted>")
                .finish(),
        }
    }
}