use crate::runtime::error::Error;
/// Trait for authenticating requests.
pub trait Authenticator<R: aioduct::Runtime>: Send + Sync + std::fmt::Debug {
/// Apply authentication to the request builder.
fn authenticate<'a>(
&self,
req: aioduct::RequestBuilder<'a, R>,
) -> Result<aioduct::RequestBuilder<'a, R>, Error>;
}
/// Bearer token authentication.
#[derive(Debug, Clone)]
pub struct BearerAuth {
token: String,
}
impl BearerAuth {
pub fn new(token: impl Into<String>) -> Self {
Self {
token: token.into(),
}
}
}
impl<R: aioduct::Runtime> Authenticator<R> for BearerAuth {
fn authenticate<'a>(
&self,
req: aioduct::RequestBuilder<'a, R>,
) -> Result<aioduct::RequestBuilder<'a, R>, Error> {
Ok(req.bearer_auth(&self.token))
}
}
/// API key authentication.
#[derive(Debug, Clone)]
pub struct ApiKeyAuth {
header_name: String,
api_key: String,
}
impl ApiKeyAuth {
pub fn new(header_name: impl Into<String>, api_key: impl Into<String>) -> Self {
Self {
header_name: header_name.into(),
api_key: api_key.into(),
}
}
}
impl<R: aioduct::Runtime> Authenticator<R> for ApiKeyAuth {
fn authenticate<'a>(
&self,
req: aioduct::RequestBuilder<'a, R>,
) -> Result<aioduct::RequestBuilder<'a, R>, Error> {
Ok(req.header_str(&self.header_name, &self.api_key)?)
}
}