use crate::error::Result;
use super::config::{ApiKeyConfig, AuthConfig, OAuthConfig};
use super::types::GeneratedApiKey;
#[derive(Debug, Default)]
pub struct AuthManager {
config: OAuthConfig,
#[cfg(feature = "api-key")]
api_key_config: ApiKeyConfig,
}
impl AuthManager {
pub fn new(config: OAuthConfig) -> Result<Self> {
config.validate()?;
Ok(Self {
config,
#[cfg(feature = "api-key")]
api_key_config: ApiKeyConfig::default(),
})
}
#[cfg(feature = "api-key")]
pub fn with_config(config: AuthConfig) -> Result<Self> {
config.validate()?;
Ok(Self {
config: config.oauth,
api_key_config: config.api_key,
})
}
#[must_use]
#[cfg(feature = "api-key")]
pub fn is_enabled(&self) -> bool {
self.config.enabled || self.api_key_config.enabled
}
#[must_use]
#[cfg(not(feature = "api-key"))]
pub fn is_enabled(&self) -> bool {
self.config.enabled
}
#[must_use]
pub fn config(&self) -> &OAuthConfig {
&self.config
}
#[cfg(feature = "api-key")]
#[must_use]
pub fn api_key_config(&self) -> &ApiKeyConfig {
&self.api_key_config
}
#[cfg(feature = "api-key")]
#[must_use]
pub fn validate_api_key(&self, key: &str) -> bool {
self.api_key_config.is_valid_key(key)
}
#[cfg(feature = "api-key")]
pub fn generate_api_key(&self) -> Result<GeneratedApiKey> {
self.api_key_config.generate_key()
}
#[cfg(feature = "api-key")]
#[must_use]
pub fn extract_api_key_from_headers(
&self,
headers: &std::collections::HashMap<String, String>,
) -> Option<String> {
headers.get(&self.api_key_config.header_name).cloned()
}
}