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