crates_docs/server/auth/
manager.rs1use crate::error::Result;
4
5use super::config::{ApiKeyConfig, AuthConfig, OAuthConfig};
6use super::types::GeneratedApiKey;
7
8#[derive(Debug, Default)]
10pub struct AuthManager {
11 config: OAuthConfig,
12 #[cfg(feature = "api-key")]
13 api_key_config: ApiKeyConfig,
14}
15
16impl AuthManager {
17 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 #[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 #[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 #[must_use]
46 #[cfg(not(feature = "api-key"))]
47 pub fn is_enabled(&self) -> bool {
48 self.config.enabled
49 }
50
51 #[must_use]
53 pub fn config(&self) -> &OAuthConfig {
54 &self.config
55 }
56
57 #[cfg(feature = "api-key")]
59 #[must_use]
60 pub fn api_key_config(&self) -> &ApiKeyConfig {
61 &self.api_key_config
62 }
63
64 #[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 #[cfg(feature = "api-key")]
77 pub fn generate_api_key(&self) -> Result<GeneratedApiKey> {
78 self.api_key_config.generate_key()
79 }
80
81 #[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}