use reqwest::header::{HeaderMap, HeaderValue};
#[derive(Debug, Clone, Copy)]
pub enum AuthMethod {
UrlParameter,
Header,
}
impl Default for AuthMethod {
fn default() -> Self {
Self::Header }
}
#[derive(Debug, Clone)]
pub struct Auth {
api_key: String,
method: AuthMethod,
}
impl Auth {
pub fn new(api_key: impl Into<String>) -> Self {
Self {
api_key: api_key.into(),
method: AuthMethod::default(),
}
}
pub fn with_method(api_key: impl Into<String>, method: AuthMethod) -> Self {
Self {
api_key: api_key.into(),
method,
}
}
pub fn api_key(&self) -> &str {
&self.api_key
}
pub fn method(&self) -> &AuthMethod {
&self.method
}
pub fn apply_to_url(&self, url: &mut url::Url) {
if matches!(self.method, AuthMethod::UrlParameter) {
url.query_pairs_mut().append_pair("token", &self.api_key);
}
}
pub fn headers(&self) -> HeaderMap {
let mut headers = HeaderMap::new();
if matches!(self.method, AuthMethod::Header) {
if let Ok(value) = HeaderValue::from_str(&self.api_key) {
headers.insert("X-Finnhub-Token", value);
}
}
headers
}
}