use std::collections::HashMap;
#[derive(Clone)]
pub struct KrxAuth {
pub auth_key: Option<String>,
pub public_data_portal_key: Option<String>,
}
impl KrxAuth {
pub fn from_env() -> Self {
Self {
auth_key: std::env::var("KRX_AUTH_KEY").ok(),
public_data_portal_key: std::env::var("KRX_DATA_PORTAL_KEY").ok(),
}
}
pub fn new_openapi(auth_key: impl Into<String>) -> Self {
Self {
auth_key: Some(auth_key.into()),
public_data_portal_key: None,
}
}
pub fn new_portal(service_key: impl Into<String>) -> Self {
Self {
auth_key: None,
public_data_portal_key: Some(service_key.into()),
}
}
pub fn new_full(auth_key: impl Into<String>, portal_key: impl Into<String>) -> Self {
Self {
auth_key: Some(auth_key.into()),
public_data_portal_key: Some(portal_key.into()),
}
}
pub fn sign_openapi_headers(&self, headers: &mut HashMap<String, String>) {
if let Some(key) = &self.auth_key {
headers.insert("AUTH_KEY".to_string(), key.clone());
}
headers.insert("Content-Type".to_string(), "application/json".to_string());
headers.insert("Accept".to_string(), "application/json".to_string());
}
pub fn sign_portal_query(&self, params: &mut HashMap<String, String>) {
if let Some(key) = &self.public_data_portal_key {
params.insert("serviceKey".to_string(), key.clone());
}
}
pub fn has_openapi_auth(&self) -> bool {
self.auth_key.is_some()
}
pub fn has_portal_auth(&self) -> bool {
self.public_data_portal_key.is_some()
}
}
impl Default for KrxAuth {
fn default() -> Self {
Self::from_env()
}
}