1use crate::{
68 AuthConfig, AuthError, AuthFramework,
69 config::{RateLimitConfig, SecurityConfig, StorageConfig},
70 prelude::{PerformancePreset, UseCasePreset, days, hours, minutes},
71 security::SecurityPreset,
72};
73use std::time::Duration;
74
75#[derive(Debug)]
77pub struct AuthBuilder {
78 config: AuthConfig,
79 security_preset: Option<SecurityPreset>,
80 performance_preset: Option<PerformancePreset>,
81 use_case_preset: Option<UseCasePreset>,
82}
83
84#[derive(Debug)]
86pub struct QuickStartBuilder {
87 auth_method: Option<QuickStartAuth>,
88 storage: Option<QuickStartStorage>,
89 framework: Option<QuickStartFramework>,
90 security_level: SecurityPreset,
91}
92
93pub enum QuickStartAuth {
95 Jwt {
96 secret: String,
97 },
98 JwtFromEnv,
99 OAuth2 {
100 client_id: String,
101 client_secret: String,
102 },
103 Combined {
104 jwt_secret: String,
105 oauth_client_id: String,
106 oauth_client_secret: String,
107 },
108}
109
110impl std::fmt::Debug for QuickStartAuth {
111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112 use crate::utils::redact::redacted;
113 match self {
114 Self::Jwt { secret } => f
115 .debug_struct("Jwt")
116 .field("secret", &redacted(secret))
117 .finish(),
118 Self::JwtFromEnv => f.write_str("JwtFromEnv"),
119 Self::OAuth2 {
120 client_id,
121 client_secret,
122 } => f
123 .debug_struct("OAuth2")
124 .field("client_id", client_id)
125 .field("client_secret", &redacted(client_secret))
126 .finish(),
127 Self::Combined {
128 jwt_secret,
129 oauth_client_id,
130 oauth_client_secret,
131 } => f
132 .debug_struct("Combined")
133 .field("jwt_secret", &redacted(jwt_secret))
134 .field("oauth_client_id", oauth_client_id)
135 .field("oauth_client_secret", &redacted(oauth_client_secret))
136 .finish(),
137 }
138 }
139}
140
141pub enum QuickStartStorage {
143 Memory,
144 Postgres(String),
145 PostgresFromEnv,
146 Redis(String),
147 RedisFromEnv,
148}
149
150impl std::fmt::Debug for QuickStartStorage {
151 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
152 use crate::utils::redact::redacted;
153 match self {
154 Self::Memory => f.write_str("Memory"),
155 Self::Postgres(url) => f.debug_tuple("Postgres").field(&redacted(url)).finish(),
157 Self::PostgresFromEnv => f.write_str("PostgresFromEnv"),
158 Self::Redis(url) => f.debug_tuple("Redis").field(&redacted(url)).finish(),
159 Self::RedisFromEnv => f.write_str("RedisFromEnv"),
160 }
161 }
162}
163
164#[derive(Debug)]
166pub enum QuickStartFramework {
167 Axum,
168 ActixWeb,
169 Warp,
170}
171
172impl AuthFramework {
173 pub fn builder() -> AuthBuilder {
175 AuthBuilder::new()
176 }
177
178 pub fn quick_start() -> QuickStartBuilder {
180 QuickStartBuilder::new()
181 }
182
183 pub fn for_use_case(use_case: UseCasePreset) -> AuthBuilder {
185 AuthBuilder::new().use_case_preset(use_case)
186 }
187
188 pub fn preset(preset: SecurityPreset) -> AuthBuilder {
190 AuthBuilder::new().security_preset(preset)
191 }
192}
193
194impl AuthBuilder {
195 pub fn new() -> Self {
197 Self {
198 config: AuthConfig::default(),
199 security_preset: None,
200 performance_preset: None,
201 use_case_preset: None,
202 }
203 }
204
205 pub fn security_preset(mut self, preset: SecurityPreset) -> Self {
207 self.security_preset = Some(preset);
208 self
209 }
210
211 pub fn performance_preset(mut self, preset: PerformancePreset) -> Self {
213 self.performance_preset = Some(preset);
214 self
215 }
216
217 pub fn use_case_preset(mut self, preset: UseCasePreset) -> Self {
219 self.use_case_preset = Some(preset);
220 self
221 }
222
223 pub fn with_jwt(self) -> JwtBuilder {
225 JwtBuilder::new(self)
226 }
227
228 pub fn with_oauth2(self) -> OAuth2Builder {
230 OAuth2Builder::new(self)
231 }
232
233 pub fn with_storage(self) -> StorageBuilder {
235 StorageBuilder::new(self)
236 }
237
238 pub fn with_rate_limiting(self) -> RateLimitBuilder {
240 RateLimitBuilder::new(self)
241 }
242
243 pub fn with_security(self) -> SecurityBuilder {
245 SecurityBuilder::new(self)
246 }
247
248 pub fn with_audit(self) -> AuditBuilder {
250 AuditBuilder::new(self)
251 }
252
253 pub fn customize<F>(mut self, f: F) -> Self
255 where
256 F: FnOnce(&mut AuthConfig) -> &mut AuthConfig,
257 {
258 f(&mut self.config);
259 self
260 }
261
262 pub async fn build(mut self) -> Result<AuthFramework, AuthError> {
264 if let Some(preset) = self.security_preset.take() {
266 self.config.security = self.apply_security_preset(preset);
267 }
268
269 if let Some(preset) = self.performance_preset.take() {
270 self.apply_performance_preset(preset);
271 }
272
273 if let Some(preset) = self.use_case_preset.take() {
274 self.apply_use_case_preset(preset);
275 }
276
277 self.config.validate()?;
279
280 let mut framework = AuthFramework::new(self.config);
282 framework.initialize().await?;
283
284 Ok(framework)
285 }
286
287 fn apply_security_preset(&self, preset: SecurityPreset) -> SecurityConfig {
288 match preset {
289 SecurityPreset::Development => SecurityConfig::development(),
290 SecurityPreset::Balanced => SecurityConfig::default(),
291 SecurityPreset::HighSecurity | SecurityPreset::Paranoid => SecurityConfig::secure(),
292 }
293 }
294
295 fn apply_performance_preset(&mut self, preset: PerformancePreset) {
296 match preset {
297 PerformancePreset::HighThroughput => {
298 self.config.rate_limiting.max_requests = 1000;
300 self.config.rate_limiting.window = Duration::from_secs(60);
301 }
302 PerformancePreset::LowLatency => {
303 self.config.token_lifetime = hours(1);
305 self.config.rate_limiting.max_requests = 100;
306 self.config.rate_limiting.window = Duration::from_secs(60);
307 }
308 PerformancePreset::LowMemory => {
309 self.config.token_lifetime = minutes(15);
311 self.config.refresh_token_lifetime = hours(2);
312 }
313 PerformancePreset::Balanced => {
314 }
316 }
317 }
318
319 fn apply_use_case_preset(&mut self, preset: UseCasePreset) {
320 match preset {
321 UseCasePreset::WebApp => {
322 self.config.token_lifetime = hours(24);
323 self.config.refresh_token_lifetime = days(7);
324 self.config.security.secure_cookies = true;
325 self.config.security.csrf_protection = true;
326 }
327 UseCasePreset::ApiService => {
328 self.config.token_lifetime = hours(1);
329 self.config.refresh_token_lifetime = hours(24);
330 self.config.rate_limiting.enabled = true;
331 self.config.rate_limiting.max_requests = 1000;
332 }
333 UseCasePreset::Microservices => {
334 self.config.token_lifetime = minutes(15);
335 self.config.refresh_token_lifetime = hours(1);
336 self.config.audit.enabled = true;
337 }
338 UseCasePreset::MobileBackend => {
339 self.config.token_lifetime = hours(1);
340 self.config.refresh_token_lifetime = days(30);
341 self.config.security.secure_cookies = false; }
343 UseCasePreset::Enterprise => {
344 self.config.enable_multi_factor = true;
345 self.config.security = SecurityConfig::secure();
346 self.config.audit.enabled = true;
347 self.config.audit.log_success = true;
348 self.config.audit.log_failures = true;
349 }
350 }
351 }
352}
353
354impl QuickStartBuilder {
355 fn new() -> Self {
356 Self {
357 auth_method: None,
358 storage: None,
359 framework: None,
360 security_level: SecurityPreset::Balanced,
361 }
362 }
363
364 pub fn jwt_auth(mut self, secret: impl Into<String>) -> Self {
366 self.auth_method = Some(QuickStartAuth::Jwt {
367 secret: secret.into(),
368 });
369 self
370 }
371
372 pub fn jwt_auth_from_env(mut self) -> Self {
374 self.auth_method = Some(QuickStartAuth::JwtFromEnv);
375 self
376 }
377
378 pub fn oauth2_auth(
380 mut self,
381 client_id: impl Into<String>,
382 client_secret: impl Into<String>,
383 ) -> Self {
384 self.auth_method = Some(QuickStartAuth::OAuth2 {
385 client_id: client_id.into(),
386 client_secret: client_secret.into(),
387 });
388 self
389 }
390
391 pub fn combined_auth(
393 mut self,
394 jwt_secret: impl Into<String>,
395 oauth_client_id: impl Into<String>,
396 oauth_client_secret: impl Into<String>,
397 ) -> Self {
398 self.auth_method = Some(QuickStartAuth::Combined {
399 jwt_secret: jwt_secret.into(),
400 oauth_client_id: oauth_client_id.into(),
401 oauth_client_secret: oauth_client_secret.into(),
402 });
403 self
404 }
405
406 pub fn with_postgres(mut self, connection_string: impl Into<String>) -> Self {
408 self.storage = Some(QuickStartStorage::Postgres(connection_string.into()));
409 self
410 }
411
412 pub fn with_postgres_from_env(mut self) -> Self {
414 self.storage = Some(QuickStartStorage::PostgresFromEnv);
415 self
416 }
417
418 pub fn with_redis(mut self, connection_string: impl Into<String>) -> Self {
420 self.storage = Some(QuickStartStorage::Redis(connection_string.into()));
421 self
422 }
423
424 pub fn with_redis_from_env(mut self) -> Self {
426 self.storage = Some(QuickStartStorage::RedisFromEnv);
427 self
428 }
429
430 pub fn with_memory_storage(mut self) -> Self {
432 self.storage = Some(QuickStartStorage::Memory);
433 self
434 }
435
436 pub fn with_axum(mut self) -> Self {
438 self.framework = Some(QuickStartFramework::Axum);
439 self
440 }
441
442 pub fn with_actix(mut self) -> Self {
444 self.framework = Some(QuickStartFramework::ActixWeb);
445 self
446 }
447
448 pub fn with_warp(mut self) -> Self {
450 self.framework = Some(QuickStartFramework::Warp);
451 self
452 }
453
454 pub fn security_level(mut self, level: SecurityPreset) -> Self {
456 self.security_level = level;
457 self
458 }
459
460 pub async fn build(self) -> Result<AuthFramework, AuthError> {
462 let mut builder = AuthBuilder::new().security_preset(self.security_level);
463
464 match self.auth_method {
466 Some(QuickStartAuth::Jwt { secret }) => {
467 builder = builder.with_jwt().secret(secret).done();
468 }
469 Some(QuickStartAuth::JwtFromEnv) => {
470 let secret = std::env::var("JWT_SECRET").map_err(|_| {
471 AuthError::config("JWT_SECRET environment variable is required")
472 })?;
473 builder = builder.with_jwt().secret(secret).done();
474 }
475 Some(QuickStartAuth::OAuth2 {
476 client_id,
477 client_secret,
478 }) => {
479 builder = builder
480 .with_oauth2()
481 .client_id(client_id)
482 .client_secret(client_secret)
483 .done();
484 }
485 Some(QuickStartAuth::Combined {
486 jwt_secret,
487 oauth_client_id,
488 oauth_client_secret,
489 }) => {
490 builder = builder
491 .with_jwt()
492 .secret(jwt_secret)
493 .done()
494 .with_oauth2()
495 .client_id(oauth_client_id)
496 .client_secret(oauth_client_secret)
497 .done();
498 }
499 None => {
500 return Err(AuthError::config("Authentication method is required"));
501 }
502 }
503
504 match self.storage {
506 Some(QuickStartStorage::Memory) => {
507 builder = builder.with_storage().memory().done();
508 }
509 Some(QuickStartStorage::Postgres(conn_str)) => {
510 builder = builder.with_storage().postgres(conn_str).done();
511 }
512 Some(QuickStartStorage::PostgresFromEnv) => {
513 let conn_str = std::env::var("DATABASE_URL").map_err(|_| {
514 AuthError::config("DATABASE_URL environment variable is required")
515 })?;
516 builder = builder.with_storage().postgres(conn_str).done();
517 }
518 Some(QuickStartStorage::Redis(_conn_str)) => {
519 builder = builder.with_storage().memory().done();
521 }
522 Some(QuickStartStorage::RedisFromEnv) => {
523 builder = builder.with_storage().memory().done();
525 }
526 None => {
527 builder = builder.with_storage().memory().done();
529 }
530 }
531
532 builder.build().await
533 }
534}
535
536pub struct JwtBuilder {
538 parent: AuthBuilder,
539 secret: Option<String>,
540 issuer: Option<String>,
541 audience: Option<String>,
542 token_lifetime: Option<Duration>,
543}
544
545impl JwtBuilder {
546 fn new(parent: AuthBuilder) -> Self {
547 Self {
548 parent,
549 secret: None,
550 issuer: None,
551 audience: None,
552 token_lifetime: None,
553 }
554 }
555
556 pub fn secret(mut self, secret: impl Into<String>) -> Self {
558 self.secret = Some(secret.into());
559 self
560 }
561
562 pub fn secret_from_env(mut self, env_var: &str) -> Self {
564 if let Ok(secret) = std::env::var(env_var) {
565 self.secret = Some(secret);
566 }
567 self
568 }
569
570 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
572 self.issuer = Some(issuer.into());
573 self
574 }
575
576 pub fn audience(mut self, audience: impl Into<String>) -> Self {
578 self.audience = Some(audience.into());
579 self
580 }
581
582 pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
584 self.token_lifetime = Some(lifetime);
585 self
586 }
587
588 pub fn done(mut self) -> AuthBuilder {
590 if let Some(secret) = self.secret {
591 self.parent.config.secret = Some(secret);
592 }
593 if let Some(issuer) = self.issuer {
594 self.parent.config.issuer = issuer;
595 }
596 if let Some(audience) = self.audience {
597 self.parent.config.audience = audience;
598 }
599 if let Some(lifetime) = self.token_lifetime {
600 self.parent.config.token_lifetime = lifetime;
601 }
602 self.parent
603 }
604}
605
606pub struct OAuth2Builder {
608 parent: AuthBuilder,
609 client_id: Option<String>,
610 client_secret: Option<String>,
611 redirect_uri: Option<String>,
612}
613
614impl OAuth2Builder {
615 fn new(parent: AuthBuilder) -> Self {
616 Self {
617 parent,
618 client_id: None,
619 client_secret: None,
620 redirect_uri: None,
621 }
622 }
623
624 pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
626 self.client_id = Some(client_id.into());
627 self
628 }
629
630 pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
632 self.client_secret = Some(client_secret.into());
633 self
634 }
635
636 pub fn redirect_uri(mut self, redirect_uri: impl Into<String>) -> Self {
638 self.redirect_uri = Some(redirect_uri.into());
639 self
640 }
641
642 pub fn google_client_id(self, client_id: impl Into<String>) -> Self {
644 self.client_id(client_id)
645 }
646
647 pub fn github_client_id(self, client_id: impl Into<String>) -> Self {
649 self.client_id(client_id)
650 }
651
652 pub fn done(self) -> AuthBuilder {
654 self.parent
657 }
658}
659
660pub struct StorageBuilder {
662 parent: AuthBuilder,
663}
664
665impl StorageBuilder {
666 fn new(parent: AuthBuilder) -> Self {
667 Self { parent }
668 }
669
670 pub fn memory(mut self) -> Self {
672 self.parent.config.storage = StorageConfig::Memory;
673 self
674 }
675
676 #[cfg(feature = "postgres-storage")]
678 pub fn postgres(mut self, connection_string: impl Into<String>) -> Self {
679 self.parent.config.storage = StorageConfig::Postgres {
680 connection_string: connection_string.into(),
681 table_prefix: "auth_".to_string(),
682 };
683 self
684 }
685
686 #[cfg(feature = "postgres-storage")]
688 pub fn postgres_from_env(mut self) -> Self {
689 if let Ok(conn_str) = std::env::var("DATABASE_URL") {
690 self = self.postgres(conn_str);
691 }
692 self
693 }
694
695 #[cfg(feature = "redis-storage")]
697 pub fn redis(mut self, url: impl Into<String>) -> Self {
698 self.parent.config.storage = StorageConfig::Redis {
699 url: url.into(),
700 key_prefix: "auth:".to_string(),
701 };
702 self
703 }
704
705 #[cfg(feature = "redis-storage")]
707 pub fn redis_from_env(mut self) -> Self {
708 if let Ok(url) = std::env::var("REDIS_URL") {
709 self = self.redis(url);
710 }
711 self
712 }
713
714 pub fn connection_pool_size(self, _size: u32) -> Self {
716 self
718 }
719
720 pub fn done(self) -> AuthBuilder {
722 self.parent
723 }
724}
725
726pub struct RateLimitBuilder {
728 parent: AuthBuilder,
729}
730
731impl RateLimitBuilder {
732 fn new(parent: AuthBuilder) -> Self {
733 Self { parent }
734 }
735
736 pub fn per_ip(mut self, (requests, window): (u32, Duration)) -> Self {
738 self.parent.config.rate_limiting = RateLimitConfig {
739 enabled: true,
740 max_requests: requests,
741 window,
742 burst: requests / 10,
743 };
744 self
745 }
746
747 pub fn disabled(mut self) -> Self {
749 self.parent.config.rate_limiting.enabled = false;
750 self
751 }
752
753 pub fn done(self) -> AuthBuilder {
755 self.parent
756 }
757}
758
759pub struct SecurityBuilder {
761 parent: AuthBuilder,
762}
763
764impl SecurityBuilder {
765 fn new(parent: AuthBuilder) -> Self {
766 Self { parent }
767 }
768
769 pub fn min_password_length(mut self, length: usize) -> Self {
771 self.parent.config.security.min_password_length = length;
772 self
773 }
774
775 pub fn require_password_complexity(mut self, required: bool) -> Self {
777 self.parent.config.security.require_password_complexity = required;
778 self
779 }
780
781 pub fn secure_cookies(mut self, enabled: bool) -> Self {
783 self.parent.config.security.secure_cookies = enabled;
784 self
785 }
786
787 pub fn done(self) -> AuthBuilder {
789 self.parent
790 }
791}
792
793pub struct AuditBuilder {
795 parent: AuthBuilder,
796}
797
798impl AuditBuilder {
799 fn new(parent: AuthBuilder) -> Self {
800 Self { parent }
801 }
802
803 pub fn enabled(mut self, enabled: bool) -> Self {
805 self.parent.config.audit.enabled = enabled;
806 self
807 }
808
809 pub fn log_success(mut self, enabled: bool) -> Self {
811 self.parent.config.audit.log_success = enabled;
812 self
813 }
814
815 pub fn log_failures(mut self, enabled: bool) -> Self {
817 self.parent.config.audit.log_failures = enabled;
818 self
819 }
820
821 pub fn done(self) -> AuthBuilder {
823 self.parent
824 }
825}
826
827impl Default for AuthBuilder {
828 fn default() -> Self {
829 Self::new()
830 }
831}