use std::collections::HashMap;
use async_trait::async_trait;
use crate::Result;
#[derive(Debug, Clone)]
pub struct RESTAuthParameter {
pub method: String,
pub path: String,
pub data: Option<String>,
pub parameters: HashMap<String, String>,
}
impl RESTAuthParameter {
pub fn new(
method: impl Into<String>,
path: impl Into<String>,
data: Option<String>,
parameters: HashMap<String, String>,
) -> Self {
Self {
method: method.into(),
path: path.into(),
data,
parameters,
}
}
pub fn for_get(path: impl Into<String>, parameters: HashMap<String, String>) -> Self {
Self::new("GET", path, None, parameters)
}
pub fn for_post(path: impl Into<String>, data: String) -> Self {
Self::new("POST", path, Some(data), HashMap::new())
}
pub fn for_delete(path: impl Into<String>) -> Self {
Self::new("DELETE", path, None, HashMap::new())
}
}
#[async_trait]
pub trait AuthProvider: Send + Sync {
async fn merge_auth_header(
&self,
base_header: HashMap<String, String>,
parameter: &RESTAuthParameter,
) -> Result<HashMap<String, String>>;
}
pub const AUTHORIZATION_HEADER_KEY: &str = "Authorization";
pub struct RESTAuthFunction {
init_header: HashMap<String, String>,
auth_provider: Box<dyn AuthProvider>,
}
impl RESTAuthFunction {
pub fn new(init_header: HashMap<String, String>, auth_provider: Box<dyn AuthProvider>) -> Self {
Self {
init_header,
auth_provider,
}
}
pub async fn apply(&self, parameter: &RESTAuthParameter) -> Result<HashMap<String, String>> {
self.auth_provider
.merge_auth_header(self.init_header.clone(), parameter)
.await
}
}