Skip to main content

auth_framework/
builders.rs

1//! Builder patterns and ergonomic helpers for the Auth Framework
2//!
3//! This module provides fluent builder APIs and helper functions to make
4//! common authentication setup tasks easier and more discoverable.
5//!
6//! # Quick Start Builders
7//!
8//! For the most common setups, use the quick start builders:
9//!
10//! ```rust,no_run
11//! # #[tokio::main]
12//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
13//! use auth_framework::prelude::*;
14//!
15//! // Simple JWT auth with environment variables
16//! let auth = AuthFramework::quick_start()
17//!     .jwt_auth_from_env()
18//!     .build().await?;
19//!
20//! // Web app with database
21//! let auth = AuthFramework::quick_start()
22//!     .jwt_auth("your-secret-key")
23//!     .with_postgres("postgresql://...")
24//!     .with_axum()
25//!     .build().await?;
26//! # Ok(())
27//! # }
28//! ```
29//!
30//! # Preset Configurations
31//!
32//! Use presets for common security and performance configurations:
33//!
34//! ```rust,no_run
35//! # #[tokio::main]
36//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
37//! use auth_framework::prelude::*;
38//!
39//! let auth = AuthFramework::builder()
40//!     .security_preset(SecurityPreset::HighSecurity)
41//!     .performance_preset(PerformancePreset::LowLatency)
42//!     .build().await?;
43//! # Ok(())
44//! # }
45//! ```
46//!
47//! # Use Case Templates
48//!
49//! Get started quickly with templates for common use cases:
50//!
51//! ```rust,no_run
52//! # #[tokio::main]
53//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
54//! use auth_framework::prelude::*;
55//!
56//! // Configure for web application
57//! let auth = AuthFramework::for_use_case(UseCasePreset::WebApp)
58//!     .customize(|config| {
59//!         config.token_lifetime = hours(24);
60//!         config
61//!     })
62//!     .build().await?;
63//! # Ok(())
64//! # }
65//! ```
66
67use crate::{
68    AuthConfig, AuthError, AuthFramework,
69    config::{RateLimitConfig, SecurityConfig, StorageConfig},
70    prelude::{PerformancePreset, UseCasePreset, days, hours, minutes},
71    security::SecurityPreset,
72};
73use std::time::Duration;
74
75/// Main builder for AuthFramework with fluent API
76#[derive(Debug)]
77pub struct AuthBuilder {
78    config: AuthConfig,
79    security_preset: Option<SecurityPreset>,
80    performance_preset: Option<PerformancePreset>,
81    use_case_preset: Option<UseCasePreset>,
82}
83
84/// Quick start builder for common authentication setups
85#[derive(Debug)]
86pub struct QuickStartBuilder {
87    auth_method: Option<QuickStartAuth>,
88    storage: Option<QuickStartStorage>,
89    framework: Option<QuickStartFramework>,
90    security_level: SecurityPreset,
91}
92
93/// Authentication method configuration for quick start
94pub enum QuickStartAuth {
95    Jwt {
96        secret: String,
97    },
98    JwtFromEnv,
99    OAuth2 {
100        client_id: String,
101        client_secret: String,
102    },
103    Combined {
104        jwt_secret: String,
105        oauth_client_id: String,
106        oauth_client_secret: String,
107    },
108}
109
110impl std::fmt::Debug for QuickStartAuth {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        use crate::utils::redact::redacted;
113        match self {
114            Self::Jwt { secret } => f
115                .debug_struct("Jwt")
116                .field("secret", &redacted(secret))
117                .finish(),
118            Self::JwtFromEnv => f.write_str("JwtFromEnv"),
119            Self::OAuth2 {
120                client_id,
121                client_secret,
122            } => f
123                .debug_struct("OAuth2")
124                .field("client_id", client_id)
125                .field("client_secret", &redacted(client_secret))
126                .finish(),
127            Self::Combined {
128                jwt_secret,
129                oauth_client_id,
130                oauth_client_secret,
131            } => f
132                .debug_struct("Combined")
133                .field("jwt_secret", &redacted(jwt_secret))
134                .field("oauth_client_id", oauth_client_id)
135                .field("oauth_client_secret", &redacted(oauth_client_secret))
136                .finish(),
137        }
138    }
139}
140
141/// Storage configuration for quick start
142pub enum QuickStartStorage {
143    Memory,
144    Postgres(String),
145    PostgresFromEnv,
146    Redis(String),
147    RedisFromEnv,
148}
149
150impl std::fmt::Debug for QuickStartStorage {
151    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152        use crate::utils::redact::redacted;
153        match self {
154            Self::Memory => f.write_str("Memory"),
155            // Connection URLs usually embed a password.
156            Self::Postgres(url) => f.debug_tuple("Postgres").field(&redacted(url)).finish(),
157            Self::PostgresFromEnv => f.write_str("PostgresFromEnv"),
158            Self::Redis(url) => f.debug_tuple("Redis").field(&redacted(url)).finish(),
159            Self::RedisFromEnv => f.write_str("RedisFromEnv"),
160        }
161    }
162}
163
164/// Web framework integration for quick start
165#[derive(Debug)]
166pub enum QuickStartFramework {
167    Axum,
168    ActixWeb,
169    Warp,
170}
171
172impl AuthFramework {
173    /// Create a new builder for the authentication framework
174    pub fn builder() -> AuthBuilder {
175        AuthBuilder::new()
176    }
177
178    /// Quick start builder for common setups
179    pub fn quick_start() -> QuickStartBuilder {
180        QuickStartBuilder::new()
181    }
182
183    /// Create a builder for a specific use case
184    pub fn for_use_case(use_case: UseCasePreset) -> AuthBuilder {
185        AuthBuilder::new().use_case_preset(use_case)
186    }
187
188    /// Create an authentication framework with preset configuration
189    pub fn preset(preset: SecurityPreset) -> AuthBuilder {
190        AuthBuilder::new().security_preset(preset)
191    }
192}
193
194impl AuthBuilder {
195    /// Create a new builder with default configuration
196    pub fn new() -> Self {
197        Self {
198            config: AuthConfig::default(),
199            security_preset: None,
200            performance_preset: None,
201            use_case_preset: None,
202        }
203    }
204
205    /// Apply a security preset
206    pub fn security_preset(mut self, preset: SecurityPreset) -> Self {
207        self.security_preset = Some(preset);
208        self
209    }
210
211    /// Apply a performance preset
212    pub fn performance_preset(mut self, preset: PerformancePreset) -> Self {
213        self.performance_preset = Some(preset);
214        self
215    }
216
217    /// Apply a use case preset
218    pub fn use_case_preset(mut self, preset: UseCasePreset) -> Self {
219        self.use_case_preset = Some(preset);
220        self
221    }
222
223    /// Configure JWT authentication
224    pub fn with_jwt(self) -> JwtBuilder {
225        JwtBuilder::new(self)
226    }
227
228    /// Configure OAuth2 authentication
229    pub fn with_oauth2(self) -> OAuth2Builder {
230        OAuth2Builder::new(self)
231    }
232
233    /// Configure storage backend
234    pub fn with_storage(self) -> StorageBuilder {
235        StorageBuilder::new(self)
236    }
237
238    /// Configure rate limiting
239    pub fn with_rate_limiting(self) -> RateLimitBuilder {
240        RateLimitBuilder::new(self)
241    }
242
243    /// Configure security settings
244    pub fn with_security(self) -> SecurityBuilder {
245        SecurityBuilder::new(self)
246    }
247
248    /// Configure audit logging
249    pub fn with_audit(self) -> AuditBuilder {
250        AuditBuilder::new(self)
251    }
252
253    /// Customize configuration with a closure
254    pub fn customize<F>(mut self, f: F) -> Self
255    where
256        F: FnOnce(&mut AuthConfig) -> &mut AuthConfig,
257    {
258        f(&mut self.config);
259        self
260    }
261
262    /// Build the authentication framework
263    pub async fn build(mut self) -> Result<AuthFramework, AuthError> {
264        // Apply presets before building
265        if let Some(preset) = self.security_preset.take() {
266            self.config.security = self.apply_security_preset(preset);
267        }
268
269        if let Some(preset) = self.performance_preset.take() {
270            self.apply_performance_preset(preset);
271        }
272
273        if let Some(preset) = self.use_case_preset.take() {
274            self.apply_use_case_preset(preset);
275        }
276
277        // Validate configuration
278        self.config.validate()?;
279
280        // Create and initialize framework
281        let mut framework = AuthFramework::new(self.config);
282        framework.initialize().await?;
283
284        Ok(framework)
285    }
286
287    fn apply_security_preset(&self, preset: SecurityPreset) -> SecurityConfig {
288        match preset {
289            SecurityPreset::Development => SecurityConfig::development(),
290            SecurityPreset::Balanced => SecurityConfig::default(),
291            SecurityPreset::HighSecurity | SecurityPreset::Paranoid => SecurityConfig::secure(),
292        }
293    }
294
295    fn apply_performance_preset(&mut self, preset: PerformancePreset) {
296        match preset {
297            PerformancePreset::HighThroughput => {
298                // Optimize for throughput
299                self.config.rate_limiting.max_requests = 1000;
300                self.config.rate_limiting.window = Duration::from_secs(60);
301            }
302            PerformancePreset::LowLatency => {
303                // Optimize for latency
304                self.config.token_lifetime = hours(1);
305                self.config.rate_limiting.max_requests = 100;
306                self.config.rate_limiting.window = Duration::from_secs(60);
307            }
308            PerformancePreset::LowMemory => {
309                // Optimize for memory usage
310                self.config.token_lifetime = minutes(15);
311                self.config.refresh_token_lifetime = hours(2);
312            }
313            PerformancePreset::Balanced => {
314                // Keep defaults
315            }
316        }
317    }
318
319    fn apply_use_case_preset(&mut self, preset: UseCasePreset) {
320        match preset {
321            UseCasePreset::WebApp => {
322                self.config.token_lifetime = hours(24);
323                self.config.refresh_token_lifetime = days(7);
324                self.config.security.secure_cookies = true;
325                self.config.security.csrf_protection = true;
326            }
327            UseCasePreset::ApiService => {
328                self.config.token_lifetime = hours(1);
329                self.config.refresh_token_lifetime = hours(24);
330                self.config.rate_limiting.enabled = true;
331                self.config.rate_limiting.max_requests = 1000;
332            }
333            UseCasePreset::Microservices => {
334                self.config.token_lifetime = minutes(15);
335                self.config.refresh_token_lifetime = hours(1);
336                self.config.audit.enabled = true;
337            }
338            UseCasePreset::MobileBackend => {
339                self.config.token_lifetime = hours(1);
340                self.config.refresh_token_lifetime = days(30);
341                self.config.security.secure_cookies = false; // Mobile doesn't use cookies
342            }
343            UseCasePreset::Enterprise => {
344                self.config.enable_multi_factor = true;
345                self.config.security = SecurityConfig::secure();
346                self.config.audit.enabled = true;
347                self.config.audit.log_success = true;
348                self.config.audit.log_failures = true;
349            }
350        }
351    }
352}
353
354impl QuickStartBuilder {
355    fn new() -> Self {
356        Self {
357            auth_method: None,
358            storage: None,
359            framework: None,
360            security_level: SecurityPreset::Balanced,
361        }
362    }
363
364    /// Configure JWT authentication with a secret key
365    pub fn jwt_auth(mut self, secret: impl Into<String>) -> Self {
366        self.auth_method = Some(QuickStartAuth::Jwt {
367            secret: secret.into(),
368        });
369        self
370    }
371
372    /// Configure JWT authentication from JWT_SECRET environment variable
373    pub fn jwt_auth_from_env(mut self) -> Self {
374        self.auth_method = Some(QuickStartAuth::JwtFromEnv);
375        self
376    }
377
378    /// Configure OAuth2 authentication
379    pub fn oauth2_auth(
380        mut self,
381        client_id: impl Into<String>,
382        client_secret: impl Into<String>,
383    ) -> Self {
384        self.auth_method = Some(QuickStartAuth::OAuth2 {
385            client_id: client_id.into(),
386            client_secret: client_secret.into(),
387        });
388        self
389    }
390
391    /// Configure both JWT and OAuth2 authentication
392    pub fn combined_auth(
393        mut self,
394        jwt_secret: impl Into<String>,
395        oauth_client_id: impl Into<String>,
396        oauth_client_secret: impl Into<String>,
397    ) -> Self {
398        self.auth_method = Some(QuickStartAuth::Combined {
399            jwt_secret: jwt_secret.into(),
400            oauth_client_id: oauth_client_id.into(),
401            oauth_client_secret: oauth_client_secret.into(),
402        });
403        self
404    }
405
406    /// Use PostgreSQL storage with connection string
407    pub fn with_postgres(mut self, connection_string: impl Into<String>) -> Self {
408        self.storage = Some(QuickStartStorage::Postgres(connection_string.into()));
409        self
410    }
411
412    /// Use PostgreSQL storage from DATABASE_URL environment variable
413    pub fn with_postgres_from_env(mut self) -> Self {
414        self.storage = Some(QuickStartStorage::PostgresFromEnv);
415        self
416    }
417
418    /// Use Redis storage with connection string
419    pub fn with_redis(mut self, connection_string: impl Into<String>) -> Self {
420        self.storage = Some(QuickStartStorage::Redis(connection_string.into()));
421        self
422    }
423
424    /// Use Redis storage from REDIS_URL environment variable
425    pub fn with_redis_from_env(mut self) -> Self {
426        self.storage = Some(QuickStartStorage::RedisFromEnv);
427        self
428    }
429
430    /// Use in-memory storage (development only)
431    pub fn with_memory_storage(mut self) -> Self {
432        self.storage = Some(QuickStartStorage::Memory);
433        self
434    }
435
436    /// Configure for Axum web framework
437    pub fn with_axum(mut self) -> Self {
438        self.framework = Some(QuickStartFramework::Axum);
439        self
440    }
441
442    /// Configure for Actix Web framework
443    pub fn with_actix(mut self) -> Self {
444        self.framework = Some(QuickStartFramework::ActixWeb);
445        self
446    }
447
448    /// Configure for Warp web framework
449    pub fn with_warp(mut self) -> Self {
450        self.framework = Some(QuickStartFramework::Warp);
451        self
452    }
453
454    /// Set security level
455    pub fn security_level(mut self, level: SecurityPreset) -> Self {
456        self.security_level = level;
457        self
458    }
459
460    /// Build the authentication framework
461    pub async fn build(self) -> Result<AuthFramework, AuthError> {
462        let mut builder = AuthBuilder::new().security_preset(self.security_level);
463
464        // Configure authentication method
465        match self.auth_method {
466            Some(QuickStartAuth::Jwt { secret }) => {
467                builder = builder.with_jwt().secret(secret).done();
468            }
469            Some(QuickStartAuth::JwtFromEnv) => {
470                let secret = std::env::var("JWT_SECRET").map_err(|_| {
471                    AuthError::config("JWT_SECRET environment variable is required")
472                })?;
473                builder = builder.with_jwt().secret(secret).done();
474            }
475            Some(QuickStartAuth::OAuth2 {
476                client_id,
477                client_secret,
478            }) => {
479                builder = builder
480                    .with_oauth2()
481                    .client_id(client_id)
482                    .client_secret(client_secret)
483                    .done();
484            }
485            Some(QuickStartAuth::Combined {
486                jwt_secret,
487                oauth_client_id,
488                oauth_client_secret,
489            }) => {
490                builder = builder
491                    .with_jwt()
492                    .secret(jwt_secret)
493                    .done()
494                    .with_oauth2()
495                    .client_id(oauth_client_id)
496                    .client_secret(oauth_client_secret)
497                    .done();
498            }
499            None => {
500                return Err(AuthError::config("Authentication method is required"));
501            }
502        }
503
504        // Configure storage
505        match self.storage {
506            Some(QuickStartStorage::Memory) => {
507                builder = builder.with_storage().memory().done();
508            }
509            Some(QuickStartStorage::Postgres(conn_str)) => {
510                builder = builder.with_storage().postgres(conn_str).done();
511            }
512            Some(QuickStartStorage::PostgresFromEnv) => {
513                let conn_str = std::env::var("DATABASE_URL").map_err(|_| {
514                    AuthError::config("DATABASE_URL environment variable is required")
515                })?;
516                builder = builder.with_storage().postgres(conn_str).done();
517            }
518            Some(QuickStartStorage::Redis(_conn_str)) => {
519                // Redis storage not yet implemented, fallback to memory
520                builder = builder.with_storage().memory().done();
521            }
522            Some(QuickStartStorage::RedisFromEnv) => {
523                // Redis storage not yet implemented, fallback to memory
524                builder = builder.with_storage().memory().done();
525            }
526            None => {
527                // Default to memory storage for quick start
528                builder = builder.with_storage().memory().done();
529            }
530        }
531
532        builder.build().await
533    }
534}
535
536/// JWT configuration builder
537pub struct JwtBuilder {
538    parent: AuthBuilder,
539    secret: Option<String>,
540    issuer: Option<String>,
541    audience: Option<String>,
542    token_lifetime: Option<Duration>,
543}
544
545impl JwtBuilder {
546    fn new(parent: AuthBuilder) -> Self {
547        Self {
548            parent,
549            secret: None,
550            issuer: None,
551            audience: None,
552            token_lifetime: None,
553        }
554    }
555
556    /// Set JWT secret key
557    pub fn secret(mut self, secret: impl Into<String>) -> Self {
558        self.secret = Some(secret.into());
559        self
560    }
561
562    /// Load JWT secret from environment variable
563    pub fn secret_from_env(mut self, env_var: &str) -> Self {
564        if let Ok(secret) = std::env::var(env_var) {
565            self.secret = Some(secret);
566        }
567        self
568    }
569
570    /// Set JWT issuer
571    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
572        self.issuer = Some(issuer.into());
573        self
574    }
575
576    /// Set JWT audience
577    pub fn audience(mut self, audience: impl Into<String>) -> Self {
578        self.audience = Some(audience.into());
579        self
580    }
581
582    /// Set token lifetime
583    pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
584        self.token_lifetime = Some(lifetime);
585        self
586    }
587
588    /// Complete JWT configuration and return to main builder
589    pub fn done(mut self) -> AuthBuilder {
590        if let Some(secret) = self.secret {
591            self.parent.config.secret = Some(secret);
592        }
593        if let Some(issuer) = self.issuer {
594            self.parent.config.issuer = issuer;
595        }
596        if let Some(audience) = self.audience {
597            self.parent.config.audience = audience;
598        }
599        if let Some(lifetime) = self.token_lifetime {
600            self.parent.config.token_lifetime = lifetime;
601        }
602        self.parent
603    }
604}
605
606/// OAuth2 configuration builder
607pub struct OAuth2Builder {
608    parent: AuthBuilder,
609    client_id: Option<String>,
610    client_secret: Option<String>,
611    redirect_uri: Option<String>,
612}
613
614impl OAuth2Builder {
615    fn new(parent: AuthBuilder) -> Self {
616        Self {
617            parent,
618            client_id: None,
619            client_secret: None,
620            redirect_uri: None,
621        }
622    }
623
624    /// Set OAuth2 client ID
625    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
626        self.client_id = Some(client_id.into());
627        self
628    }
629
630    /// Set OAuth2 client secret
631    pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
632        self.client_secret = Some(client_secret.into());
633        self
634    }
635
636    /// Set redirect URI
637    pub fn redirect_uri(mut self, redirect_uri: impl Into<String>) -> Self {
638        self.redirect_uri = Some(redirect_uri.into());
639        self
640    }
641
642    /// Configure Google OAuth2
643    pub fn google_client_id(self, client_id: impl Into<String>) -> Self {
644        self.client_id(client_id)
645    }
646
647    /// Configure GitHub OAuth2
648    pub fn github_client_id(self, client_id: impl Into<String>) -> Self {
649        self.client_id(client_id)
650    }
651
652    /// Complete OAuth2 configuration and return to main builder
653    pub fn done(self) -> AuthBuilder {
654        // OAuth2 configuration would be stored in method_configs
655        // This is a simplified version
656        self.parent
657    }
658}
659
660/// Storage configuration builder
661pub struct StorageBuilder {
662    parent: AuthBuilder,
663}
664
665impl StorageBuilder {
666    fn new(parent: AuthBuilder) -> Self {
667        Self { parent }
668    }
669
670    /// Configure in-memory storage
671    pub fn memory(mut self) -> Self {
672        self.parent.config.storage = StorageConfig::Memory;
673        self
674    }
675
676    /// Configure PostgreSQL storage
677    #[cfg(feature = "postgres-storage")]
678    pub fn postgres(mut self, connection_string: impl Into<String>) -> Self {
679        self.parent.config.storage = StorageConfig::Postgres {
680            connection_string: connection_string.into(),
681            table_prefix: "auth_".to_string(),
682        };
683        self
684    }
685
686    /// Configure PostgreSQL storage from environment
687    #[cfg(feature = "postgres-storage")]
688    pub fn postgres_from_env(mut self) -> Self {
689        if let Ok(conn_str) = std::env::var("DATABASE_URL") {
690            self = self.postgres(conn_str);
691        }
692        self
693    }
694
695    /// Configure Redis storage
696    #[cfg(feature = "redis-storage")]
697    pub fn redis(mut self, url: impl Into<String>) -> Self {
698        self.parent.config.storage = StorageConfig::Redis {
699            url: url.into(),
700            key_prefix: "auth:".to_string(),
701        };
702        self
703    }
704
705    /// Configure Redis storage from environment
706    #[cfg(feature = "redis-storage")]
707    pub fn redis_from_env(mut self) -> Self {
708        if let Ok(url) = std::env::var("REDIS_URL") {
709            self = self.redis(url);
710        }
711        self
712    }
713
714    /// Set connection pool size
715    pub fn connection_pool_size(self, _size: u32) -> Self {
716        // This would be implemented when storage supports connection pooling
717        self
718    }
719
720    /// Complete storage configuration and return to main builder
721    pub fn done(self) -> AuthBuilder {
722        self.parent
723    }
724}
725
726/// Rate limiting configuration builder
727pub struct RateLimitBuilder {
728    parent: AuthBuilder,
729}
730
731impl RateLimitBuilder {
732    fn new(parent: AuthBuilder) -> Self {
733        Self { parent }
734    }
735
736    /// Configure rate limiting per IP
737    pub fn per_ip(mut self, (requests, window): (u32, Duration)) -> Self {
738        self.parent.config.rate_limiting = RateLimitConfig {
739            enabled: true,
740            max_requests: requests,
741            window,
742            burst: requests / 10,
743        };
744        self
745    }
746
747    /// Disable rate limiting
748    pub fn disabled(mut self) -> Self {
749        self.parent.config.rate_limiting.enabled = false;
750        self
751    }
752
753    /// Complete rate limiting configuration and return to main builder
754    pub fn done(self) -> AuthBuilder {
755        self.parent
756    }
757}
758
759/// Security configuration builder
760pub struct SecurityBuilder {
761    parent: AuthBuilder,
762}
763
764impl SecurityBuilder {
765    fn new(parent: AuthBuilder) -> Self {
766        Self { parent }
767    }
768
769    /// Set minimum password length
770    pub fn min_password_length(mut self, length: usize) -> Self {
771        self.parent.config.security.min_password_length = length;
772        self
773    }
774
775    /// Enable/disable password complexity requirements
776    pub fn require_password_complexity(mut self, required: bool) -> Self {
777        self.parent.config.security.require_password_complexity = required;
778        self
779    }
780
781    /// Enable/disable secure cookies
782    pub fn secure_cookies(mut self, enabled: bool) -> Self {
783        self.parent.config.security.secure_cookies = enabled;
784        self
785    }
786
787    /// Complete security configuration and return to main builder
788    pub fn done(self) -> AuthBuilder {
789        self.parent
790    }
791}
792
793/// Audit configuration builder
794pub struct AuditBuilder {
795    parent: AuthBuilder,
796}
797
798impl AuditBuilder {
799    fn new(parent: AuthBuilder) -> Self {
800        Self { parent }
801    }
802
803    /// Enable audit logging
804    pub fn enabled(mut self, enabled: bool) -> Self {
805        self.parent.config.audit.enabled = enabled;
806        self
807    }
808
809    /// Log successful authentications
810    pub fn log_success(mut self, enabled: bool) -> Self {
811        self.parent.config.audit.log_success = enabled;
812        self
813    }
814
815    /// Log failed authentications
816    pub fn log_failures(mut self, enabled: bool) -> Self {
817        self.parent.config.audit.log_failures = enabled;
818        self
819    }
820
821    /// Complete audit configuration and return to main builder
822    pub fn done(self) -> AuthBuilder {
823        self.parent
824    }
825}
826
827impl Default for AuthBuilder {
828    fn default() -> Self {
829        Self::new()
830    }
831}