1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use std::fmt::Debug;

use http::{HeaderMap, HeaderValue};
use thiserror::Error;

/// Authentication error
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum AuthError {
    /// Invalid header value
    #[error("Invalid header value: {0}")]
    HeaderValue(#[from] http::header::InvalidHeaderValue),
}

#[derive(Clone)]
pub(crate) struct Auth {
    pub(crate) token: Option<String>,
}

impl Auth {
    pub fn set_auth_header<'a>(
        &self,
        headers: &'a mut HeaderMap<HeaderValue>,
    ) -> Result<&'a mut HeaderMap<HeaderValue>, AuthError> {
        if let Some(ref api_key) = self.token {
            let mut val = HeaderValue::from_str(api_key)?;
            val.set_sensitive(true);
            headers.insert("X-API-Key", val);
        }

        Ok(headers)
    }
}

impl Debug for Auth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.token.is_some() {
            write!(f, "Yes")
        } else {
            write!(f, "No")
        }
    }
}