use std::sync::Arc;
use async_trait::async_trait;
use openapp_sdk_common::ApiKey;
use crate::error::SdkError;
#[derive(Debug, Clone)]
pub struct AuthToken {
pub authorization: String,
}
#[async_trait]
pub trait TokenProvider: Send + Sync + std::fmt::Debug {
async fn token(&self) -> Result<AuthToken, SdkError>;
}
pub type SharedTokenProvider = Arc<dyn TokenProvider>;
#[derive(Debug, Clone)]
pub struct StaticApiKey {
key: ApiKey,
}
impl StaticApiKey {
#[must_use]
pub fn new(key: ApiKey) -> Self {
Self { key }
}
pub fn from_raw(token: impl Into<String>) -> Result<Self, SdkError> {
Ok(Self::new(ApiKey::parse(token)?))
}
#[must_use]
pub fn api_key(&self) -> &ApiKey {
&self.key
}
}
#[async_trait]
impl TokenProvider for StaticApiKey {
async fn token(&self) -> Result<AuthToken, SdkError> {
Ok(AuthToken {
authorization: format!("Bearer {}", self.key.as_bearer()),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn static_provider_emits_bearer() {
let provider =
StaticApiKey::from_raw("https://api.openapp.house/api/v1_openapp_SECRET").unwrap();
let token = provider.token().await.unwrap();
assert_eq!(
token.authorization,
"Bearer https://api.openapp.house/api/v1_openapp_SECRET"
);
}
}