Skip to main content

alpaca_http/
auth.rs

1use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
2
3use crate::Error;
4
5pub trait Authenticator: Send + Sync {
6    fn apply(&self, headers: &mut HeaderMap) -> Result<(), Error>;
7}
8
9#[derive(Debug, Clone, Default)]
10pub struct StaticHeaderAuthenticator {
11    headers: HeaderMap,
12}
13
14impl StaticHeaderAuthenticator {
15    pub fn from_pairs<I, K, V>(pairs: I) -> Result<Self, Error>
16    where
17        I: IntoIterator<Item = (K, V)>,
18        K: AsRef<str>,
19        V: AsRef<str>,
20    {
21        let mut headers = HeaderMap::new();
22
23        for (name, value) in pairs {
24            let name = HeaderName::from_bytes(name.as_ref().as_bytes())
25                .map_err(|error| Error::Authentication(format!("invalid header name: {error}")))?;
26            let value = HeaderValue::from_str(value.as_ref())
27                .map_err(|error| Error::Authentication(format!("invalid header value: {error}")))?;
28            headers.insert(name, value);
29        }
30
31        Ok(Self { headers })
32    }
33
34    pub fn apply(&self, headers: &mut HeaderMap) -> Result<(), Error> {
35        <Self as Authenticator>::apply(self, headers)
36    }
37}
38
39impl Authenticator for StaticHeaderAuthenticator {
40    fn apply(&self, headers: &mut HeaderMap) -> Result<(), Error> {
41        headers.extend(self.headers.clone());
42        Ok(())
43    }
44}