Skip to main content

crates_docs/server/auth/
manager.rs

1//! Authentication manager
2
3use crate::error::Result;
4
5use super::config::{ApiKeyConfig, AuthConfig, OAuthConfig};
6use super::types::GeneratedApiKey;
7
8/// Authentication manager
9#[derive(Debug, Default)]
10pub struct AuthManager {
11    config: OAuthConfig,
12    #[cfg(feature = "api-key")]
13    api_key_config: ApiKeyConfig,
14}
15
16impl AuthManager {
17    /// Create a new authentication manager
18    pub fn new(config: OAuthConfig) -> Result<Self> {
19        config.validate()?;
20        Ok(Self {
21            config,
22            #[cfg(feature = "api-key")]
23            api_key_config: ApiKeyConfig::default(),
24        })
25    }
26
27    /// Create a new authentication manager with full config
28    #[cfg(feature = "api-key")]
29    pub fn with_config(config: AuthConfig) -> Result<Self> {
30        config.validate()?;
31        Ok(Self {
32            config: config.oauth,
33            api_key_config: config.api_key,
34        })
35    }
36
37    /// Check if authentication is enabled
38    #[must_use]
39    #[cfg(feature = "api-key")]
40    pub fn is_enabled(&self) -> bool {
41        self.config.enabled || self.api_key_config.enabled
42    }
43
44    /// Check if authentication is enabled
45    #[must_use]
46    #[cfg(not(feature = "api-key"))]
47    pub fn is_enabled(&self) -> bool {
48        self.config.enabled
49    }
50
51    /// Get OAuth configuration
52    #[must_use]
53    pub fn config(&self) -> &OAuthConfig {
54        &self.config
55    }
56
57    /// Get API key configuration
58    #[cfg(feature = "api-key")]
59    #[must_use]
60    pub fn api_key_config(&self) -> &ApiKeyConfig {
61        &self.api_key_config
62    }
63
64    /// Validate API key
65    #[cfg(feature = "api-key")]
66    #[must_use]
67    pub fn validate_api_key(&self, key: &str) -> bool {
68        self.api_key_config.is_valid_key(key)
69    }
70
71    /// Generate a new API key and hash pair
72    ///
73    /// # Errors
74    ///
75    /// Returns an error if key generation fails
76    #[cfg(feature = "api-key")]
77    pub fn generate_api_key(&self) -> Result<GeneratedApiKey> {
78        self.api_key_config.generate_key()
79    }
80
81    /// Extract API key from request headers
82    #[cfg(feature = "api-key")]
83    #[must_use]
84    pub fn extract_api_key_from_headers(
85        &self,
86        headers: &std::collections::HashMap<String, String>,
87    ) -> Option<String> {
88        headers.get(&self.api_key_config.header_name).cloned()
89    }
90}