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