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