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;
74use zeroize::Zeroizing;
75
76/// Main builder for constructing an [`AuthFramework`] instance.
77///
78/// Start with [`AuthFramework::builder()`] and chain sub-builders for
79/// JWT, storage, security, rate limiting, and audit configuration.
80///
81/// # Example
82///
83/// ```rust,no_run
84/// # #[tokio::main]
85/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
86/// use auth_framework::prelude::*;
87///
88/// let auth = AuthFramework::builder()
89///     .with_jwt().secret("my-secret-key-that-is-long-enough!!").issuer("myapp").done()
90///     .with_storage().memory().done()
91///     .security_preset(SecurityPreset::Balanced)
92///     .build().await?;
93/// # Ok(())
94/// # }
95/// ```
96pub struct AuthBuilder {
97    config: AuthConfig,
98    security_preset: Option<SecurityPreset>,
99    performance_preset: Option<PerformancePreset>,
100    use_case_preset: Option<UseCasePreset>,
101    storage_pool_size: Option<u32>,
102    /// Optional custom storage instance supplied by caller (`Arc<dyn AuthStorage>`)
103    custom_storage: Option<std::sync::Arc<dyn crate::storage::AuthStorage>>,
104}
105
106/// Quick start builder for common authentication setups.
107///
108/// Provides the fastest path to a working [`AuthFramework`] by combining
109/// authentication method, storage, and framework integrations in a single
110/// fluent chain.  Start via [`AuthFramework::quick_start()`].
111///
112/// # Example
113///
114/// ```rust,no_run
115/// # #[tokio::main]
116/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
117/// use auth_framework::prelude::*;
118///
119/// let auth = AuthFramework::quick_start()
120///     .jwt_auth("my-secret-key-that-is-long-enough!!")
121///     .build().await?;
122/// # Ok(())
123/// # }
124/// ```
125#[derive(Debug)]
126pub struct QuickStartBuilder {
127    auth_method: Option<QuickStartAuth>,
128    storage: Option<QuickStartStorage>,
129    framework: Option<QuickStartFramework>,
130    security_level: SecurityPreset,
131}
132
133/// Authentication method selection for [`QuickStartBuilder`].
134#[derive(Debug)]
135pub enum QuickStartAuth {
136    Jwt {
137        secret: Zeroizing<String>,
138    },
139    JwtFromEnv,
140    OAuth2 {
141        client_id: String,
142        client_secret: Zeroizing<String>,
143    },
144    Combined {
145        jwt_secret: Zeroizing<String>,
146        oauth_client_id: String,
147        oauth_client_secret: Zeroizing<String>,
148    },
149}
150
151/// Storage backend selection for [`QuickStartBuilder`].
152#[derive(Debug)]
153pub enum QuickStartStorage {
154    Memory,
155    Postgres(String),
156    PostgresFromEnv,
157    Redis(String),
158    RedisFromEnv,
159}
160
161/// Web framework integration selection for [`QuickStartBuilder`].
162#[derive(Debug)]
163pub enum QuickStartFramework {
164    Axum,
165    ActixWeb,
166    Warp,
167}
168
169impl AuthFramework {
170    /// Create a new builder for the authentication framework
171    pub fn builder() -> AuthBuilder {
172        AuthBuilder::new()
173    }
174
175    /// Quick start builder for common setups
176    pub fn quick_start() -> QuickStartBuilder {
177        QuickStartBuilder::new()
178    }
179
180    /// Create a builder for a specific use case
181    pub fn for_use_case(use_case: UseCasePreset) -> AuthBuilder {
182        AuthBuilder::new().use_case_preset(use_case)
183    }
184
185    /// Create an authentication framework with preset configuration
186    pub fn preset(preset: SecurityPreset) -> AuthBuilder {
187        AuthBuilder::new().security_preset(preset)
188    }
189}
190
191impl AuthBuilder {
192    /// Create a new builder with default configuration.
193    ///
194    /// # Example
195    ///
196    /// ```rust
197    /// use auth_framework::builders::AuthBuilder;
198    ///
199    /// let builder = AuthBuilder::new();
200    /// ```
201    pub fn new() -> Self {
202        Self {
203            config: AuthConfig::default(),
204            security_preset: None,
205            performance_preset: None,
206            use_case_preset: None,
207            storage_pool_size: None,
208            custom_storage: None,
209        }
210    }
211
212    /// Apply a security preset.
213    ///
214    /// # Example
215    ///
216    /// ```rust,no_run
217    /// use auth_framework::prelude::*;
218    ///
219    /// let builder = AuthFramework::builder()
220    ///     .security_preset(SecurityPreset::HighSecurity);
221    /// ```
222    pub fn security_preset(mut self, preset: SecurityPreset) -> Self {
223        self.security_preset = Some(preset);
224        self
225    }
226
227    /// Apply a performance preset.
228    ///
229    /// # Example
230    ///
231    /// ```rust,no_run
232    /// use auth_framework::prelude::*;
233    ///
234    /// let builder = AuthFramework::builder()
235    ///     .performance_preset(PerformancePreset::LowLatency);
236    /// ```
237    pub fn performance_preset(mut self, preset: PerformancePreset) -> Self {
238        self.performance_preset = Some(preset);
239        self
240    }
241
242    /// Apply a use case preset.
243    ///
244    /// # Example
245    ///
246    /// ```rust,no_run
247    /// use auth_framework::prelude::*;
248    ///
249    /// let builder = AuthFramework::builder()
250    ///     .use_case_preset(UseCasePreset::WebApp);
251    /// ```
252    pub fn use_case_preset(mut self, preset: UseCasePreset) -> Self {
253        self.use_case_preset = Some(preset);
254        self
255    }
256
257    /// Configure JWT authentication.
258    ///
259    /// Returns a [`JwtBuilder`] sub-builder. Call `.done()` to return.
260    ///
261    /// # Example
262    ///
263    /// ```rust,no_run
264    /// use auth_framework::prelude::*;
265    ///
266    /// let builder = AuthFramework::builder()
267    ///     .with_jwt().secret("my-long-secret-key-32-chars-min!!").done();
268    /// ```
269    pub fn with_jwt(self) -> JwtBuilder {
270        JwtBuilder::new(self)
271    }
272
273    /// Configure OAuth2 authentication.
274    ///
275    /// Returns an [`OAuth2Builder`] sub-builder. Call `.done()` to return.
276    ///
277    /// # Example
278    ///
279    /// ```rust,no_run
280    /// use auth_framework::prelude::*;
281    ///
282    /// let builder = AuthFramework::builder()
283    ///     .with_oauth2().client_id("id").client_secret("secret").done();
284    /// ```
285    pub fn with_oauth2(self) -> OAuth2Builder {
286        OAuth2Builder::new(self)
287    }
288
289    /// Configure storage backend.
290    ///
291    /// Returns a [`StorageBuilder`] sub-builder. Call `.done()` to return.
292    ///
293    /// # Example
294    ///
295    /// ```rust,no_run
296    /// use auth_framework::prelude::*;
297    ///
298    /// let builder = AuthFramework::builder()
299    ///     .with_storage().memory().done();
300    /// ```
301    pub fn with_storage(self) -> StorageBuilder {
302        StorageBuilder::new(self)
303    }
304
305    /// Configure rate limiting.
306    ///
307    /// Returns a [`RateLimitBuilder`] sub-builder. Call `.done()` to return.
308    ///
309    /// # Example
310    ///
311    /// ```rust,no_run
312    /// use auth_framework::prelude::*;
313    /// use std::time::Duration;
314    ///
315    /// let builder = AuthFramework::builder()
316    ///     .with_rate_limiting().per_ip((200, Duration::from_secs(60))).done();
317    /// ```
318    pub fn with_rate_limiting(self) -> RateLimitBuilder {
319        RateLimitBuilder::new(self)
320    }
321
322    /// Configure security settings.
323    ///
324    /// Returns a [`SecurityBuilder`] sub-builder. Call `.done()` to return.
325    ///
326    /// # Example
327    ///
328    /// ```rust,no_run
329    /// use auth_framework::prelude::*;
330    ///
331    /// let builder = AuthFramework::builder()
332    ///     .with_security().min_password_length(12).secure_cookies(true).done();
333    /// ```
334    pub fn with_security(self) -> SecurityBuilder {
335        SecurityBuilder::new(self)
336    }
337
338    /// Configure audit logging.
339    ///
340    /// Returns an [`AuditBuilder`] sub-builder. Call `.done()` to return.
341    ///
342    /// # Example
343    ///
344    /// ```rust,no_run
345    /// use auth_framework::prelude::*;
346    ///
347    /// let builder = AuthFramework::builder()
348    ///     .with_audit().enabled(true).log_success(true).done();
349    /// ```
350    pub fn with_audit(self) -> AuditBuilder {
351        AuditBuilder::new(self)
352    }
353
354    /// Customize configuration with a closure.
355    ///
356    /// # Example
357    ///
358    /// ```rust,no_run
359    /// use auth_framework::prelude::*;
360    /// use std::time::Duration;
361    ///
362    /// let builder = AuthFramework::builder()
363    ///     .customize(|config| {
364    ///         config.token_lifetime = Duration::from_secs(7200);
365    ///         config
366    ///     });
367    /// ```
368    pub fn customize<F>(mut self, f: F) -> Self
369    where
370        F: FnOnce(&mut AuthConfig) -> &mut AuthConfig,
371    {
372        f(&mut self.config);
373        self
374    }
375
376    /// Build the authentication framework.
377    ///
378    /// Applies presets, validates configuration, initializes storage,
379    /// and returns a ready-to-use [`AuthFramework`] instance.
380    ///
381    /// # Example
382    ///
383    /// ```rust,no_run
384    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
385    /// use auth_framework::prelude::*;
386    ///
387    /// let auth = AuthFramework::builder()
388    ///     .with_jwt().secret("my-long-secret-key-32-chars-min!!").done()
389    ///     .with_storage().memory().done()
390    ///     .build().await?;
391    /// # Ok(()) }
392    /// ```
393    pub async fn build(mut self) -> Result<AuthFramework, AuthError> {
394        // Apply presets before building
395        if let Some(preset) = self.security_preset.take() {
396            self.config.security = self.apply_security_preset(preset);
397        }
398
399        if let Some(preset) = self.performance_preset.take() {
400            self.apply_performance_preset(preset);
401        }
402
403        if let Some(preset) = self.use_case_preset.take() {
404            self.apply_use_case_preset(preset);
405        }
406
407        // Validate configuration
408        self.config.validate()?;
409
410        // Create and initialize framework
411        // If a custom storage was provided via the builder, we'll construct a framework
412        // and replace its storage before initialization so managers use the custom storage.
413        let config = self.config.clone();
414        let mut framework = AuthFramework::new(self.config);
415        if let Some(storage) = self.custom_storage.take() {
416            framework.replace_storage(storage);
417        } else if let Some(pool_size) = self.storage_pool_size {
418            let storage = crate::storage::factory::build_storage_backend_with_encryption(
419                &config.storage,
420                Some(pool_size),
421                &config.storage_encryption,
422            )
423            .await?;
424            framework.replace_storage_from_factory(storage);
425        }
426        framework.initialize().await?;
427
428        Ok(framework)
429    }
430
431    fn apply_security_preset(&self, preset: SecurityPreset) -> SecurityConfig {
432        match preset {
433            SecurityPreset::Development => SecurityConfig::development(),
434            SecurityPreset::Balanced => SecurityConfig::default(),
435            SecurityPreset::HighSecurity | SecurityPreset::Paranoid => SecurityConfig::secure(),
436        }
437    }
438
439    fn apply_performance_preset(&mut self, preset: PerformancePreset) {
440        match preset {
441            PerformancePreset::HighThroughput => {
442                // Optimize for throughput
443                self.config.rate_limiting.max_requests = 1000;
444                self.config.rate_limiting.window = Duration::from_secs(60);
445            }
446            PerformancePreset::LowLatency => {
447                // Optimize for latency
448                self.config.token_lifetime = hours(1);
449                self.config.rate_limiting.max_requests = 100;
450                self.config.rate_limiting.window = Duration::from_secs(60);
451            }
452            PerformancePreset::LowMemory => {
453                // Optimize for memory usage
454                self.config.token_lifetime = minutes(15);
455                self.config.refresh_token_lifetime = hours(2);
456            }
457            PerformancePreset::Balanced => {
458                // Keep defaults
459            }
460        }
461    }
462
463    fn apply_use_case_preset(&mut self, preset: UseCasePreset) {
464        match preset {
465            UseCasePreset::WebApp => {
466                self.config.token_lifetime = hours(24);
467                self.config.refresh_token_lifetime = days(7);
468                self.config.security.secure_cookies = true;
469                self.config.security.csrf_protection = true;
470            }
471            UseCasePreset::ApiService => {
472                self.config.token_lifetime = hours(1);
473                self.config.refresh_token_lifetime = hours(24);
474                self.config.rate_limiting.enabled = true;
475                self.config.rate_limiting.max_requests = 1000;
476            }
477            UseCasePreset::Microservices => {
478                self.config.token_lifetime = minutes(15);
479                self.config.refresh_token_lifetime = hours(1);
480                self.config.audit.enabled = true;
481            }
482            UseCasePreset::MobileBackend => {
483                self.config.token_lifetime = hours(1);
484                self.config.refresh_token_lifetime = days(30);
485                self.config.security.secure_cookies = false; // Mobile doesn't use cookies
486            }
487            UseCasePreset::Enterprise => {
488                self.config.enable_multi_factor = true;
489                self.config.security = SecurityConfig::secure();
490                self.config.audit.enabled = true;
491                self.config.audit.log_success = true;
492                self.config.audit.log_failures = true;
493            }
494        }
495    }
496}
497
498impl QuickStartBuilder {
499    fn new() -> Self {
500        Self {
501            auth_method: None,
502            storage: None,
503            framework: None,
504            security_level: SecurityPreset::Balanced,
505        }
506    }
507
508    /// Configure JWT authentication with a secret key.
509    ///
510    /// # Example
511    ///
512    /// ```rust,no_run
513    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
514    /// use auth_framework::prelude::*;
515    ///
516    /// let auth = AuthFramework::quick_start()
517    ///     .jwt_auth("my-long-secret-key-32-chars-min!!")
518    ///     .build().await?;
519    /// # Ok(()) }
520    /// ```
521    pub fn jwt_auth(mut self, secret: impl Into<String>) -> Self {
522        self.auth_method = Some(QuickStartAuth::Jwt {
523            secret: secret.into().into(),
524        });
525        self
526    }
527
528    /// Configure JWT authentication from `JWT_SECRET` environment variable.
529    ///
530    /// # Example
531    ///
532    /// ```rust,no_run
533    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
534    /// use auth_framework::prelude::*;
535    ///
536    /// // Reads JWT_SECRET from the environment
537    /// let auth = AuthFramework::quick_start()
538    ///     .jwt_auth_from_env()
539    ///     .build().await?;
540    /// # Ok(()) }
541    /// ```
542    pub fn jwt_auth_from_env(mut self) -> Self {
543        self.auth_method = Some(QuickStartAuth::JwtFromEnv);
544        self
545    }
546
547    /// Configure OAuth2 authentication.
548    ///
549    /// # Example
550    ///
551    /// ```rust,no_run
552    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
553    /// use auth_framework::prelude::*;
554    ///
555    /// let auth = AuthFramework::quick_start()
556    ///     .oauth2_auth("client-id", "client-secret")
557    ///     .build().await?;
558    /// # Ok(()) }
559    /// ```
560    pub fn oauth2_auth(
561        mut self,
562        client_id: impl Into<String>,
563        client_secret: impl Into<String>,
564    ) -> Self {
565        self.auth_method = Some(QuickStartAuth::OAuth2 {
566            client_id: client_id.into(),
567            client_secret: client_secret.into().into(),
568        });
569        self
570    }
571
572    /// Configure both JWT and OAuth2 authentication.
573    ///
574    /// # Example
575    ///
576    /// ```rust,no_run
577    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
578    /// use auth_framework::prelude::*;
579    ///
580    /// let auth = AuthFramework::quick_start()
581    ///     .combined_auth("jwt-secret-long-enough-32chars!!", "client-id", "secret")
582    ///     .build().await?;
583    /// # Ok(()) }
584    /// ```
585    pub fn combined_auth(
586        mut self,
587        jwt_secret: impl Into<String>,
588        oauth_client_id: impl Into<String>,
589        oauth_client_secret: impl Into<String>,
590    ) -> Self {
591        self.auth_method = Some(QuickStartAuth::Combined {
592            jwt_secret: jwt_secret.into().into(),
593            oauth_client_id: oauth_client_id.into(),
594            oauth_client_secret: oauth_client_secret.into().into(),
595        });
596        self
597    }
598
599    /// Use PostgreSQL storage with connection string.
600    ///
601    /// # Example
602    ///
603    /// ```rust,no_run
604    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
605    /// use auth_framework::prelude::*;
606    ///
607    /// let auth = AuthFramework::quick_start()
608    ///     .jwt_auth("my-long-secret-key-32-chars-min!!")
609    ///     .with_postgres("postgresql://user:pass@localhost/auth")
610    ///     .build().await?;
611    /// # Ok(()) }
612    /// ```
613    pub fn with_postgres(mut self, connection_string: impl Into<String>) -> Self {
614        self.storage = Some(QuickStartStorage::Postgres(connection_string.into()));
615        self
616    }
617
618    /// Use PostgreSQL storage from `DATABASE_URL` environment variable.
619    ///
620    /// # Example
621    ///
622    /// ```rust,no_run
623    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
624    /// use auth_framework::prelude::*;
625    ///
626    /// let auth = AuthFramework::quick_start()
627    ///     .jwt_auth("my-long-secret-key-32-chars-min!!")
628    ///     .with_postgres_from_env()
629    ///     .build().await?;
630    /// # Ok(()) }
631    /// ```
632    pub fn with_postgres_from_env(mut self) -> Self {
633        self.storage = Some(QuickStartStorage::PostgresFromEnv);
634        self
635    }
636
637    /// Use Redis storage with connection string.
638    ///
639    /// # Example
640    ///
641    /// ```rust,no_run
642    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
643    /// use auth_framework::prelude::*;
644    ///
645    /// let auth = AuthFramework::quick_start()
646    ///     .jwt_auth("my-long-secret-key-32-chars-min!!")
647    ///     .with_redis("redis://localhost:6379")
648    ///     .build().await?;
649    /// # Ok(()) }
650    /// ```
651    pub fn with_redis(mut self, connection_string: impl Into<String>) -> Self {
652        self.storage = Some(QuickStartStorage::Redis(connection_string.into()));
653        self
654    }
655
656    /// Use Redis storage from `REDIS_URL` environment variable.
657    ///
658    /// # Example
659    ///
660    /// ```rust,no_run
661    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
662    /// use auth_framework::prelude::*;
663    ///
664    /// let auth = AuthFramework::quick_start()
665    ///     .jwt_auth("my-long-secret-key-32-chars-min!!")
666    ///     .with_redis_from_env()
667    ///     .build().await?;
668    /// # Ok(()) }
669    /// ```
670    pub fn with_redis_from_env(mut self) -> Self {
671        self.storage = Some(QuickStartStorage::RedisFromEnv);
672        self
673    }
674
675    /// Use in-memory storage (development only).
676    ///
677    /// # Example
678    ///
679    /// ```rust,no_run
680    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
681    /// use auth_framework::prelude::*;
682    ///
683    /// let auth = AuthFramework::quick_start()
684    ///     .jwt_auth("my-long-secret-key-32-chars-min!!")
685    ///     .with_memory_storage()
686    ///     .build().await?;
687    /// # Ok(()) }
688    /// ```
689    pub fn with_memory_storage(mut self) -> Self {
690        self.storage = Some(QuickStartStorage::Memory);
691        self
692    }
693
694    /// Configure for Axum web framework.
695    ///
696    /// # Example
697    ///
698    /// ```rust,no_run
699    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
700    /// use auth_framework::prelude::*;
701    ///
702    /// let auth = AuthFramework::quick_start()
703    ///     .jwt_auth("my-long-secret-key-32-chars-min!!")
704    ///     .with_axum()
705    ///     .build().await?;
706    /// # Ok(()) }
707    /// ```
708    pub fn with_axum(mut self) -> Self {
709        self.framework = Some(QuickStartFramework::Axum);
710        self
711    }
712
713    /// Configure for Actix Web framework.
714    ///
715    /// # Example
716    ///
717    /// ```rust,no_run
718    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
719    /// use auth_framework::prelude::*;
720    ///
721    /// let auth = AuthFramework::quick_start()
722    ///     .jwt_auth("my-long-secret-key-32-chars-min!!")
723    ///     .with_actix()
724    ///     .build().await?;
725    /// # Ok(()) }
726    /// ```
727    pub fn with_actix(mut self) -> Self {
728        self.framework = Some(QuickStartFramework::ActixWeb);
729        self
730    }
731
732    /// Configure for Warp web framework.
733    ///
734    /// # Example
735    ///
736    /// ```rust,no_run
737    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
738    /// use auth_framework::prelude::*;
739    ///
740    /// let auth = AuthFramework::quick_start()
741    ///     .jwt_auth("my-long-secret-key-32-chars-min!!")
742    ///     .with_warp()
743    ///     .build().await?;
744    /// # Ok(()) }
745    /// ```
746    pub fn with_warp(mut self) -> Self {
747        self.framework = Some(QuickStartFramework::Warp);
748        self
749    }
750
751    /// Set security level.
752    ///
753    /// # Example
754    ///
755    /// ```rust,no_run
756    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
757    /// use auth_framework::prelude::*;
758    ///
759    /// let auth = AuthFramework::quick_start()
760    ///     .jwt_auth("my-long-secret-key-32-chars-min!!")
761    ///     .security_level(SecurityPreset::HighSecurity)
762    ///     .build().await?;
763    /// # Ok(()) }
764    /// ```
765    pub fn security_level(mut self, level: SecurityPreset) -> Self {
766        self.security_level = level;
767        self
768    }
769
770    /// Build the authentication framework.
771    ///
772    /// Applies the configured auth method, storage, and security level,
773    /// then delegates to [`AuthBuilder::build`].
774    ///
775    /// # Example
776    ///
777    /// ```rust,no_run
778    /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
779    /// use auth_framework::prelude::*;
780    ///
781    /// let auth = AuthFramework::quick_start()
782    ///     .jwt_auth("my-long-secret-key-32-chars-min!!")
783    ///     .build().await?;
784    /// # Ok(()) }
785    /// ```
786    pub async fn build(self) -> Result<AuthFramework, AuthError> {
787        let mut builder = AuthBuilder::new().security_preset(self.security_level);
788
789        // Configure authentication method
790        match self.auth_method {
791            Some(QuickStartAuth::Jwt { secret }) => {
792                builder = builder.with_jwt().secret(secret.to_string()).done();
793            }
794            Some(QuickStartAuth::JwtFromEnv) => {
795                let secret = std::env::var("JWT_SECRET").map_err(|_| {
796                    AuthError::config("JWT_SECRET environment variable is required")
797                })?;
798                builder = builder.with_jwt().secret(secret).done();
799            }
800            Some(QuickStartAuth::OAuth2 {
801                client_id,
802                client_secret,
803            }) => {
804                builder = builder
805                    .with_oauth2()
806                    .client_id(client_id)
807                    .client_secret(client_secret.to_string())
808                    .done();
809            }
810            Some(QuickStartAuth::Combined {
811                jwt_secret,
812                oauth_client_id,
813                oauth_client_secret,
814            }) => {
815                builder = builder
816                    .with_jwt()
817                    .secret(jwt_secret.to_string())
818                    .done()
819                    .with_oauth2()
820                    .client_id(oauth_client_id)
821                    .client_secret(oauth_client_secret.to_string())
822                    .done();
823            }
824            None => {
825                return Err(AuthError::config("Authentication method is required"));
826            }
827        }
828
829        // Configure storage
830        match self.storage {
831            Some(QuickStartStorage::Memory) => {
832                builder = builder.with_storage().memory().done();
833            }
834            Some(QuickStartStorage::Postgres(_conn_str)) => {
835                #[cfg(feature = "postgres-storage")]
836                {
837                    builder = builder.with_storage().postgres(_conn_str).done();
838                }
839                #[cfg(not(feature = "postgres-storage"))]
840                {
841                    return Err(AuthError::config(
842                        "PostgreSQL storage was requested but the `postgres-storage` feature is not enabled; \
843                         refusing to fall back to in-memory storage, which would lose all data on restart",
844                    ));
845                }
846            }
847            Some(QuickStartStorage::PostgresFromEnv) => {
848                #[cfg(feature = "postgres-storage")]
849                {
850                    let conn_str = std::env::var("DATABASE_URL").map_err(|_| {
851                        AuthError::config("DATABASE_URL environment variable is required")
852                    })?;
853                    builder = builder.with_storage().postgres(conn_str).done();
854                }
855                #[cfg(not(feature = "postgres-storage"))]
856                {
857                    return Err(AuthError::config(
858                        "PostgreSQL storage was requested but the `postgres-storage` feature is not enabled; \
859                         refusing to fall back to in-memory storage, which would lose all data on restart",
860                    ));
861                }
862            }
863            Some(QuickStartStorage::Redis(_conn_str)) => {
864                #[cfg(feature = "redis-storage")]
865                {
866                    builder = builder.with_storage().redis(_conn_str).done();
867                }
868                #[cfg(not(feature = "redis-storage"))]
869                {
870                    return Err(AuthError::config(
871                        "Redis storage was requested but the `redis-storage` feature is not enabled; \
872                         refusing to fall back to in-memory storage, which would lose all data on restart",
873                    ));
874                }
875            }
876            Some(QuickStartStorage::RedisFromEnv) => {
877                #[cfg(feature = "redis-storage")]
878                {
879                    builder = builder.with_storage().redis_from_env().done();
880                }
881                #[cfg(not(feature = "redis-storage"))]
882                {
883                    return Err(AuthError::config(
884                        "Redis storage was requested but the `redis-storage` feature is not enabled; \
885                         refusing to fall back to in-memory storage, which would lose all data on restart",
886                    ));
887                }
888            }
889            None => {
890                // Default to memory storage for quick start
891                builder = builder.with_storage().memory().done();
892            }
893        }
894
895        builder.build().await
896    }
897}
898
899/// Sub-builder for JWT settings.
900///
901/// Entered via [`AuthBuilder::with_jwt()`]; call [`done()`](JwtBuilder::done)
902/// to return to the parent builder.
903pub struct JwtBuilder {
904    parent: AuthBuilder,
905    secret: Option<String>,
906    issuer: Option<String>,
907    audience: Option<String>,
908    token_lifetime: Option<Duration>,
909    refresh_token_lifetime: Option<Duration>,
910    algorithm: Option<crate::config::JwtAlgorithm>,
911}
912
913impl JwtBuilder {
914    fn new(parent: AuthBuilder) -> Self {
915        Self {
916            parent,
917            secret: None,
918            issuer: None,
919            audience: None,
920            token_lifetime: None,
921            refresh_token_lifetime: None,
922            algorithm: None,
923        }
924    }
925
926    /// Set JWT secret key.
927    ///
928    /// Must be at least 32 characters for HMAC algorithms.
929    ///
930    /// # Example
931    ///
932    /// ```rust,no_run
933    /// use auth_framework::prelude::*;
934    ///
935    /// let builder = AuthFramework::builder()
936    ///     .with_jwt().secret("my-long-secret-key-32-chars-min!!").done();
937    /// ```
938    pub fn secret(mut self, secret: impl Into<String>) -> Self {
939        self.secret = Some(secret.into());
940        self
941    }
942
943    /// Set JWT secret from environment variable.
944    ///
945    /// # Example
946    ///
947    /// ```rust,no_run
948    /// use auth_framework::prelude::*;
949    ///
950    /// let builder = AuthFramework::builder()
951    ///     .with_jwt().secret_from_env("MY_JWT_SECRET").done();
952    /// ```
953    pub fn secret_from_env(mut self, env_var: &str) -> Self {
954        if let Ok(secret) = std::env::var(env_var) {
955            self.secret = Some(secret);
956        }
957        self
958    }
959
960    /// Set JWT issuer.
961    ///
962    /// # Example
963    ///
964    /// ```rust,no_run
965    /// use auth_framework::prelude::*;
966    ///
967    /// let builder = AuthFramework::builder()
968    ///     .with_jwt().secret("secret-key-at-least-32-characters!!").issuer("my-service").done();
969    /// ```
970    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
971        self.issuer = Some(issuer.into());
972        self
973    }
974
975    /// Set JWT audience.
976    ///
977    /// # Example
978    ///
979    /// ```rust,no_run
980    /// use auth_framework::prelude::*;
981    ///
982    /// let builder = AuthFramework::builder()
983    ///     .with_jwt().secret("secret-key-at-least-32-characters!!").audience("my-api").done();
984    /// ```
985    pub fn audience(mut self, audience: impl Into<String>) -> Self {
986        self.audience = Some(audience.into());
987        self
988    }
989
990    /// Set token lifetime.
991    ///
992    /// # Example
993    ///
994    /// ```rust,no_run
995    /// use auth_framework::prelude::*;
996    /// use std::time::Duration;
997    ///
998    /// let builder = AuthFramework::builder()
999    ///     .with_jwt()
1000    ///     .secret("secret-key-at-least-32-characters!!")
1001    ///     .token_lifetime(Duration::from_secs(1800))
1002    ///     .done();
1003    /// ```
1004    pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
1005        self.token_lifetime = Some(lifetime);
1006        self
1007    }
1008
1009    /// Set refresh token lifetime (defaults to 7 days).
1010    ///
1011    /// # Example
1012    ///
1013    /// ```rust,no_run
1014    /// use auth_framework::prelude::*;
1015    /// use std::time::Duration;
1016    ///
1017    /// let builder = AuthFramework::builder()
1018    ///     .with_jwt()
1019    ///     .secret("secret-key-at-least-32-characters!!")
1020    ///     .refresh_token_lifetime(Duration::from_secs(86400))
1021    ///     .done();
1022    /// ```
1023    pub fn refresh_token_lifetime(mut self, lifetime: Duration) -> Self {
1024        self.refresh_token_lifetime = Some(lifetime);
1025        self
1026    }
1027
1028    /// Set the JWT signing algorithm (defaults to HS256).
1029    ///
1030    /// # Example
1031    ///
1032    /// ```rust,no_run
1033    /// use auth_framework::prelude::*;
1034    /// use auth_framework::config::JwtAlgorithm;
1035    ///
1036    /// let builder = AuthFramework::builder()
1037    ///     .with_jwt()
1038    ///     .secret("secret-key-at-least-32-characters!!")
1039    ///     .algorithm(JwtAlgorithm::HS512)
1040    ///     .done();
1041    /// ```
1042    pub fn algorithm(mut self, algorithm: crate::config::JwtAlgorithm) -> Self {
1043        self.algorithm = Some(algorithm);
1044        self
1045    }
1046
1047    /// Complete JWT configuration and return to main builder.
1048    ///
1049    /// # Example
1050    ///
1051    /// ```rust,no_run
1052    /// use auth_framework::prelude::*;
1053    ///
1054    /// let builder = AuthFramework::builder()
1055    ///     .with_jwt().secret("secret-key-at-least-32-characters!!").done()
1056    ///     .with_storage().memory().done();
1057    /// ```
1058    pub fn done(mut self) -> AuthBuilder {
1059        if let Some(secret) = self.secret {
1060            self.parent.config.secret = Some(secret);
1061        }
1062        if let Some(issuer) = self.issuer {
1063            self.parent.config.issuer = issuer;
1064        }
1065        if let Some(audience) = self.audience {
1066            self.parent.config.audience = audience;
1067        }
1068        if let Some(lifetime) = self.token_lifetime {
1069            self.parent.config.token_lifetime = lifetime;
1070        }
1071        if let Some(lifetime) = self.refresh_token_lifetime {
1072            self.parent.config.refresh_token_lifetime = lifetime;
1073        }
1074        if let Some(algorithm) = self.algorithm {
1075            self.parent.config.security.jwt_algorithm = algorithm;
1076        }
1077        self.parent
1078    }
1079}
1080
1081/// Sub-builder for OAuth 2.0 client credentials.
1082///
1083/// Entered via [`AuthBuilder::with_oauth2()`]; call [`done()`](OAuth2Builder::done)
1084/// to return to the parent builder.
1085pub struct OAuth2Builder {
1086    parent: AuthBuilder,
1087    client_id: Option<String>,
1088    client_secret: Option<String>,
1089    redirect_uri: Option<String>,
1090}
1091
1092impl OAuth2Builder {
1093    fn new(parent: AuthBuilder) -> Self {
1094        Self {
1095            parent,
1096            client_id: None,
1097            client_secret: None,
1098            redirect_uri: None,
1099        }
1100    }
1101
1102    /// Set OAuth2 client ID.
1103    ///
1104    /// # Example
1105    ///
1106    /// ```rust,no_run
1107    /// use auth_framework::prelude::*;
1108    ///
1109    /// let builder = AuthFramework::builder()
1110    ///     .with_oauth2().client_id("my-client-id").done();
1111    /// ```
1112    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
1113        self.client_id = Some(client_id.into());
1114        self
1115    }
1116
1117    /// Set OAuth2 client secret.
1118    ///
1119    /// # Example
1120    ///
1121    /// ```rust,no_run
1122    /// use auth_framework::prelude::*;
1123    ///
1124    /// let builder = AuthFramework::builder()
1125    ///     .with_oauth2().client_id("id").client_secret("secret").done();
1126    /// ```
1127    pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
1128        self.client_secret = Some(client_secret.into());
1129        self
1130    }
1131
1132    /// Set redirect URI.
1133    ///
1134    /// # Example
1135    ///
1136    /// ```rust,no_run
1137    /// use auth_framework::prelude::*;
1138    ///
1139    /// let builder = AuthFramework::builder()
1140    ///     .with_oauth2()
1141    ///     .client_id("id")
1142    ///     .redirect_uri("https://example.com/callback")
1143    ///     .done();
1144    /// ```
1145    pub fn redirect_uri(mut self, redirect_uri: impl Into<String>) -> Self {
1146        self.redirect_uri = Some(redirect_uri.into());
1147        self
1148    }
1149
1150    /// Configure Google OAuth2.
1151    ///
1152    /// Alias for [`client_id`](Self::client_id).
1153    ///
1154    /// # Example
1155    ///
1156    /// ```rust,no_run
1157    /// use auth_framework::prelude::*;
1158    ///
1159    /// let builder = AuthFramework::builder()
1160    ///     .with_oauth2().google_client_id("123.apps.googleusercontent.com").done();
1161    /// ```
1162    pub fn google_client_id(self, client_id: impl Into<String>) -> Self {
1163        self.client_id(client_id)
1164    }
1165
1166    /// Configure GitHub OAuth2.
1167    ///
1168    /// Alias for [`client_id`](Self::client_id).
1169    ///
1170    /// # Example
1171    ///
1172    /// ```rust,no_run
1173    /// use auth_framework::prelude::*;
1174    ///
1175    /// let builder = AuthFramework::builder()
1176    ///     .with_oauth2().github_client_id("Iv1.abc123").done();
1177    /// ```
1178    pub fn github_client_id(self, client_id: impl Into<String>) -> Self {
1179        self.client_id(client_id)
1180    }
1181
1182    /// Complete OAuth2 configuration and return to main builder.
1183    ///
1184    /// # Example
1185    ///
1186    /// ```rust,no_run
1187    /// use auth_framework::prelude::*;
1188    ///
1189    /// let builder = AuthFramework::builder()
1190    ///     .with_oauth2().client_id("id").client_secret("secret").done();
1191    /// ```
1192    pub fn done(mut self) -> AuthBuilder {
1193        let mut oauth2_config = serde_json::Map::new();
1194        if let Some(client_id) = self.client_id {
1195            oauth2_config.insert(
1196                "client_id".to_string(),
1197                serde_json::Value::String(client_id),
1198            );
1199        }
1200        if let Some(client_secret) = self.client_secret {
1201            oauth2_config.insert(
1202                "client_secret".to_string(),
1203                serde_json::Value::String(client_secret),
1204            );
1205        }
1206        if let Some(redirect_uri) = self.redirect_uri {
1207            oauth2_config.insert(
1208                "redirect_uri".to_string(),
1209                serde_json::Value::String(redirect_uri),
1210            );
1211        }
1212        self.parent.config.method_configs.insert(
1213            "oauth2".to_string(),
1214            serde_json::Value::Object(oauth2_config),
1215        );
1216        self.parent
1217    }
1218}
1219
1220/// Sub-builder for storage backend selection.
1221///
1222/// Entered via [`AuthBuilder::with_storage()`]; call [`done()`](StorageBuilder::done)
1223/// to return to the parent builder.
1224pub struct StorageBuilder {
1225    parent: AuthBuilder,
1226}
1227
1228impl StorageBuilder {
1229    fn new(parent: AuthBuilder) -> Self {
1230        Self { parent }
1231    }
1232
1233    /// Use a custom storage instance (already initialized) instead of
1234    /// the built-in storage backends.
1235    ///
1236    /// Pass any type that implements [`AuthStorage`](crate::storage::AuthStorage)
1237    /// wrapped in an `Arc`. This is the extension point for third-party or
1238    /// proprietary databases (SurrealDB, FoundationDB, DynamoDB, etc.).
1239    ///
1240    /// # Example
1241    ///
1242    /// ```rust,ignore
1243    /// use std::sync::Arc;
1244    /// use auth_framework::prelude::*;
1245    /// use auth_framework::storage::AuthStorage;
1246    ///
1247    /// // Implement `AuthStorage` for your backend, then:
1248    /// let storage: Arc<dyn AuthStorage> = Arc::new(
1249    ///     MySurrealStorage::connect("ws://localhost:8000").await?,
1250    /// );
1251    ///
1252    /// let auth = AuthFramework::builder()
1253    ///     .with_storage()
1254    ///     .custom(storage)
1255    ///     .done()
1256    ///     .build()
1257    ///     .await?;
1258    /// ```
1259    pub fn custom(mut self, storage: std::sync::Arc<dyn crate::storage::AuthStorage>) -> Self {
1260        self.parent.custom_storage = Some(storage);
1261        self
1262    }
1263
1264    /// Configure in-memory storage.
1265    ///
1266    /// # Example
1267    ///
1268    /// ```rust,no_run
1269    /// use auth_framework::prelude::*;
1270    ///
1271    /// let builder = AuthFramework::builder()
1272    ///     .with_storage().memory().done();
1273    /// ```
1274    pub fn memory(mut self) -> Self {
1275        self.parent.config.storage = StorageConfig::Memory;
1276        self
1277    }
1278
1279    /// Configure PostgreSQL storage.
1280    ///
1281    /// # Example
1282    ///
1283    /// ```rust,no_run
1284    /// use auth_framework::prelude::*;
1285    ///
1286    /// let builder = AuthFramework::builder()
1287    ///     .with_storage().postgres("postgresql://user:pass@localhost/db").done();
1288    /// ```
1289    #[cfg(feature = "postgres-storage")]
1290    pub fn postgres(mut self, connection_string: impl Into<String>) -> Self {
1291        self.parent.config.storage = StorageConfig::Postgres {
1292            connection_string: connection_string.into(),
1293            table_prefix: "auth_".to_string(),
1294        };
1295        self
1296    }
1297
1298    /// Configure PostgreSQL storage from environment.
1299    ///
1300    /// Reads `DATABASE_URL` from the environment.
1301    ///
1302    /// # Example
1303    ///
1304    /// ```rust,no_run
1305    /// use auth_framework::prelude::*;
1306    ///
1307    /// let builder = AuthFramework::builder()
1308    ///     .with_storage().postgres_from_env().done();
1309    /// ```
1310    #[cfg(feature = "postgres-storage")]
1311    pub fn postgres_from_env(mut self) -> Self {
1312        if let Ok(conn_str) = std::env::var("DATABASE_URL") {
1313            self = self.postgres(conn_str);
1314        }
1315        self
1316    }
1317
1318    /// Configure Redis storage.
1319    ///
1320    /// # Example
1321    ///
1322    /// ```rust,no_run
1323    /// use auth_framework::prelude::*;
1324    ///
1325    /// let builder = AuthFramework::builder()
1326    ///     .with_storage().redis("redis://localhost:6379").done();
1327    /// ```
1328    #[cfg(feature = "redis-storage")]
1329    pub fn redis(mut self, url: impl Into<String>) -> Self {
1330        self.parent.config.storage = StorageConfig::Redis {
1331            url: url.into(),
1332            key_prefix: "auth:".to_string(),
1333        };
1334        self
1335    }
1336
1337    /// Configure Redis storage from environment.
1338    ///
1339    /// Reads `REDIS_URL` from the environment.
1340    ///
1341    /// # Example
1342    ///
1343    /// ```rust,no_run
1344    /// use auth_framework::prelude::*;
1345    ///
1346    /// let builder = AuthFramework::builder()
1347    ///     .with_storage().redis_from_env().done();
1348    /// ```
1349    #[cfg(feature = "redis-storage")]
1350    pub fn redis_from_env(mut self) -> Self {
1351        if let Ok(url) = std::env::var("REDIS_URL") {
1352            self = self.redis(url);
1353        }
1354        self
1355    }
1356
1357    /// Configure SQLite storage
1358    #[cfg(feature = "sqlite-storage")]
1359    pub fn sqlite(mut self, connection_string: impl Into<String>) -> Self {
1360        self.parent.config.storage = StorageConfig::Sqlite {
1361            connection_string: connection_string.into(),
1362        };
1363        self
1364    }
1365
1366    /// Set connection pool size.
1367    ///
1368    /// # Example
1369    ///
1370    /// ```rust,no_run
1371    /// use auth_framework::prelude::*;
1372    ///
1373    /// let builder = AuthFramework::builder()
1374    ///     .with_storage().memory().connection_pool_size(20).done();
1375    /// ```
1376    pub fn connection_pool_size(mut self, size: u32) -> Self {
1377        self.parent.storage_pool_size = Some(size);
1378        self
1379    }
1380
1381    /// Complete storage configuration and return to main builder.
1382    pub fn done(self) -> AuthBuilder {
1383        self.parent
1384    }
1385}
1386
1387/// Sub-builder for rate limiting policy.
1388///
1389/// Entered via [`AuthBuilder::with_rate_limit()`]; call
1390/// [`done()`](RateLimitBuilder::done) to return to the parent builder.
1391pub struct RateLimitBuilder {
1392    parent: AuthBuilder,
1393}
1394
1395impl RateLimitBuilder {
1396    fn new(parent: AuthBuilder) -> Self {
1397        Self { parent }
1398    }
1399
1400    /// Configure rate limiting per IP.
1401    ///
1402    /// # Example
1403    ///
1404    /// ```rust,no_run
1405    /// use auth_framework::prelude::*;
1406    /// use std::time::Duration;
1407    ///
1408    /// let builder = AuthFramework::builder()
1409    ///     .with_rate_limiting().per_ip((200, Duration::from_secs(60))).done();
1410    /// ```
1411    pub fn per_ip(mut self, (requests, window): (u32, Duration)) -> Self {
1412        self.parent.config.rate_limiting = RateLimitConfig {
1413            enabled: true,
1414            max_requests: requests,
1415            window,
1416            burst: requests / 10,
1417        };
1418        self
1419    }
1420
1421    /// Disable rate limiting.
1422    ///
1423    /// # Example
1424    ///
1425    /// ```rust,no_run
1426    /// use auth_framework::prelude::*;
1427    ///
1428    /// let builder = AuthFramework::builder()
1429    ///     .with_rate_limiting().disabled().done();
1430    /// ```
1431    pub fn disabled(mut self) -> Self {
1432        self.parent.config.rate_limiting.enabled = false;
1433        self
1434    }
1435
1436    /// Complete rate limiting configuration and return to main builder.
1437    pub fn done(self) -> AuthBuilder {
1438        self.parent
1439    }
1440}
1441
1442/// Sub-builder for security settings (passwords, cookies, CSRF).
1443///
1444/// Entered via [`AuthBuilder::with_security()`]; call
1445/// [`done()`](SecurityBuilder::done) to return to the parent builder.
1446pub struct SecurityBuilder {
1447    parent: AuthBuilder,
1448}
1449
1450impl SecurityBuilder {
1451    fn new(parent: AuthBuilder) -> Self {
1452        Self { parent }
1453    }
1454
1455    /// Set minimum password length.
1456    ///
1457    /// # Example
1458    ///
1459    /// ```rust,no_run
1460    /// use auth_framework::prelude::*;
1461    ///
1462    /// let builder = AuthFramework::builder()
1463    ///     .with_security().min_password_length(12).done();
1464    /// ```
1465    pub fn min_password_length(mut self, length: usize) -> Self {
1466        self.parent.config.security.min_password_length = length;
1467        self
1468    }
1469
1470    /// Enable/disable password complexity requirements.
1471    ///
1472    /// # Example
1473    ///
1474    /// ```rust,no_run
1475    /// use auth_framework::prelude::*;
1476    ///
1477    /// let builder = AuthFramework::builder()
1478    ///     .with_security().require_password_complexity(false).done();
1479    /// ```
1480    pub fn require_password_complexity(mut self, required: bool) -> Self {
1481        self.parent.config.security.require_password_complexity = required;
1482        self
1483    }
1484
1485    /// Enable/disable secure cookies.
1486    ///
1487    /// # Example
1488    ///
1489    /// ```rust,no_run
1490    /// use auth_framework::prelude::*;
1491    ///
1492    /// let builder = AuthFramework::builder()
1493    ///     .with_security().secure_cookies(true).done();
1494    /// ```
1495    pub fn secure_cookies(mut self, enabled: bool) -> Self {
1496        self.parent.config.security.secure_cookies = enabled;
1497        self
1498    }
1499
1500    /// Complete security configuration and return to main builder.
1501    pub fn done(self) -> AuthBuilder {
1502        self.parent
1503    }
1504}
1505
1506/// Sub-builder for audit logging settings.
1507///
1508/// Entered via [`AuthBuilder::with_audit()`]; call
1509/// [`done()`](AuditBuilder::done) to return to the parent builder.
1510pub struct AuditBuilder {
1511    parent: AuthBuilder,
1512}
1513
1514impl AuditBuilder {
1515    fn new(parent: AuthBuilder) -> Self {
1516        Self { parent }
1517    }
1518
1519    /// Enable audit logging.
1520    ///
1521    /// # Example
1522    ///
1523    /// ```rust,no_run
1524    /// use auth_framework::prelude::*;
1525    ///
1526    /// let builder = AuthFramework::builder()
1527    ///     .with_audit().enabled(true).done();
1528    /// ```
1529    pub fn enabled(mut self, enabled: bool) -> Self {
1530        self.parent.config.audit.enabled = enabled;
1531        self
1532    }
1533
1534    /// Log successful authentications.
1535    ///
1536    /// # Example
1537    ///
1538    /// ```rust,no_run
1539    /// use auth_framework::prelude::*;
1540    ///
1541    /// let builder = AuthFramework::builder()
1542    ///     .with_audit().log_success(true).done();
1543    /// ```
1544    pub fn log_success(mut self, enabled: bool) -> Self {
1545        self.parent.config.audit.log_success = enabled;
1546        self
1547    }
1548
1549    /// Log failed authentications.
1550    ///
1551    /// # Example
1552    ///
1553    /// ```rust,no_run
1554    /// use auth_framework::prelude::*;
1555    ///
1556    /// let builder = AuthFramework::builder()
1557    ///     .with_audit().log_failures(true).done();
1558    /// ```
1559    pub fn log_failures(mut self, enabled: bool) -> Self {
1560        self.parent.config.audit.log_failures = enabled;
1561        self
1562    }
1563
1564    /// Complete audit configuration and return to main builder.
1565    pub fn done(self) -> AuthBuilder {
1566        self.parent
1567    }
1568}
1569
1570impl Default for AuthBuilder {
1571    fn default() -> Self {
1572        Self::new()
1573    }
1574}