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
93#[derive(Debug)]
95pub enum QuickStartAuth {
96 Jwt {
97 secret: String,
98 },
99 JwtFromEnv,
100 OAuth2 {
101 client_id: String,
102 client_secret: String,
103 },
104 Combined {
105 jwt_secret: String,
106 oauth_client_id: String,
107 oauth_client_secret: String,
108 },
109}
110
111#[derive(Debug)]
113pub enum QuickStartStorage {
114 Memory,
115 Postgres(String),
116 PostgresFromEnv,
117 Redis(String),
118 RedisFromEnv,
119}
120
121#[derive(Debug)]
123pub enum QuickStartFramework {
124 Axum,
125 ActixWeb,
126 Warp,
127}
128
129impl AuthFramework {
130 pub fn builder() -> AuthBuilder {
132 AuthBuilder::new()
133 }
134
135 pub fn quick_start() -> QuickStartBuilder {
137 QuickStartBuilder::new()
138 }
139
140 pub fn for_use_case(use_case: UseCasePreset) -> AuthBuilder {
142 AuthBuilder::new().use_case_preset(use_case)
143 }
144
145 pub fn preset(preset: SecurityPreset) -> AuthBuilder {
147 AuthBuilder::new().security_preset(preset)
148 }
149}
150
151impl AuthBuilder {
152 pub fn new() -> Self {
154 Self {
155 config: AuthConfig::default(),
156 security_preset: None,
157 performance_preset: None,
158 use_case_preset: None,
159 }
160 }
161
162 pub fn security_preset(mut self, preset: SecurityPreset) -> Self {
164 self.security_preset = Some(preset);
165 self
166 }
167
168 pub fn performance_preset(mut self, preset: PerformancePreset) -> Self {
170 self.performance_preset = Some(preset);
171 self
172 }
173
174 pub fn use_case_preset(mut self, preset: UseCasePreset) -> Self {
176 self.use_case_preset = Some(preset);
177 self
178 }
179
180 pub fn with_jwt(self) -> JwtBuilder {
182 JwtBuilder::new(self)
183 }
184
185 pub fn with_oauth2(self) -> OAuth2Builder {
187 OAuth2Builder::new(self)
188 }
189
190 pub fn with_storage(self) -> StorageBuilder {
192 StorageBuilder::new(self)
193 }
194
195 pub fn with_rate_limiting(self) -> RateLimitBuilder {
197 RateLimitBuilder::new(self)
198 }
199
200 pub fn with_security(self) -> SecurityBuilder {
202 SecurityBuilder::new(self)
203 }
204
205 pub fn with_audit(self) -> AuditBuilder {
207 AuditBuilder::new(self)
208 }
209
210 pub fn customize<F>(mut self, f: F) -> Self
212 where
213 F: FnOnce(&mut AuthConfig) -> &mut AuthConfig,
214 {
215 f(&mut self.config);
216 self
217 }
218
219 pub async fn build(mut self) -> Result<AuthFramework, AuthError> {
221 if let Some(preset) = self.security_preset.take() {
223 self.config.security = self.apply_security_preset(preset);
224 }
225
226 if let Some(preset) = self.performance_preset.take() {
227 self.apply_performance_preset(preset);
228 }
229
230 if let Some(preset) = self.use_case_preset.take() {
231 self.apply_use_case_preset(preset);
232 }
233
234 self.config.validate()?;
236
237 let mut framework = AuthFramework::new(self.config);
239 framework.initialize().await?;
240
241 Ok(framework)
242 }
243
244 fn apply_security_preset(&self, preset: SecurityPreset) -> SecurityConfig {
245 match preset {
246 SecurityPreset::Development => SecurityConfig::development(),
247 SecurityPreset::Balanced => SecurityConfig::default(),
248 SecurityPreset::HighSecurity | SecurityPreset::Paranoid => SecurityConfig::secure(),
249 }
250 }
251
252 fn apply_performance_preset(&mut self, preset: PerformancePreset) {
253 match preset {
254 PerformancePreset::HighThroughput => {
255 self.config.rate_limiting.max_requests = 1000;
257 self.config.rate_limiting.window = Duration::from_secs(60);
258 }
259 PerformancePreset::LowLatency => {
260 self.config.token_lifetime = hours(1);
262 self.config.rate_limiting.max_requests = 100;
263 self.config.rate_limiting.window = Duration::from_secs(60);
264 }
265 PerformancePreset::LowMemory => {
266 self.config.token_lifetime = minutes(15);
268 self.config.refresh_token_lifetime = hours(2);
269 }
270 PerformancePreset::Balanced => {
271 }
273 }
274 }
275
276 fn apply_use_case_preset(&mut self, preset: UseCasePreset) {
277 match preset {
278 UseCasePreset::WebApp => {
279 self.config.token_lifetime = hours(24);
280 self.config.refresh_token_lifetime = days(7);
281 self.config.security.secure_cookies = true;
282 self.config.security.csrf_protection = true;
283 }
284 UseCasePreset::ApiService => {
285 self.config.token_lifetime = hours(1);
286 self.config.refresh_token_lifetime = hours(24);
287 self.config.rate_limiting.enabled = true;
288 self.config.rate_limiting.max_requests = 1000;
289 }
290 UseCasePreset::Microservices => {
291 self.config.token_lifetime = minutes(15);
292 self.config.refresh_token_lifetime = hours(1);
293 self.config.audit.enabled = true;
294 }
295 UseCasePreset::MobileBackend => {
296 self.config.token_lifetime = hours(1);
297 self.config.refresh_token_lifetime = days(30);
298 self.config.security.secure_cookies = false; }
300 UseCasePreset::Enterprise => {
301 self.config.enable_multi_factor = true;
302 self.config.security = SecurityConfig::secure();
303 self.config.audit.enabled = true;
304 self.config.audit.log_success = true;
305 self.config.audit.log_failures = true;
306 }
307 }
308 }
309}
310
311impl QuickStartBuilder {
312 fn new() -> Self {
313 Self {
314 auth_method: None,
315 storage: None,
316 framework: None,
317 security_level: SecurityPreset::Balanced,
318 }
319 }
320
321 pub fn jwt_auth(mut self, secret: impl Into<String>) -> Self {
323 self.auth_method = Some(QuickStartAuth::Jwt {
324 secret: secret.into(),
325 });
326 self
327 }
328
329 pub fn jwt_auth_from_env(mut self) -> Self {
331 self.auth_method = Some(QuickStartAuth::JwtFromEnv);
332 self
333 }
334
335 pub fn oauth2_auth(
337 mut self,
338 client_id: impl Into<String>,
339 client_secret: impl Into<String>,
340 ) -> Self {
341 self.auth_method = Some(QuickStartAuth::OAuth2 {
342 client_id: client_id.into(),
343 client_secret: client_secret.into(),
344 });
345 self
346 }
347
348 pub fn combined_auth(
350 mut self,
351 jwt_secret: impl Into<String>,
352 oauth_client_id: impl Into<String>,
353 oauth_client_secret: impl Into<String>,
354 ) -> Self {
355 self.auth_method = Some(QuickStartAuth::Combined {
356 jwt_secret: jwt_secret.into(),
357 oauth_client_id: oauth_client_id.into(),
358 oauth_client_secret: oauth_client_secret.into(),
359 });
360 self
361 }
362
363 pub fn with_postgres(mut self, connection_string: impl Into<String>) -> Self {
365 self.storage = Some(QuickStartStorage::Postgres(connection_string.into()));
366 self
367 }
368
369 pub fn with_postgres_from_env(mut self) -> Self {
371 self.storage = Some(QuickStartStorage::PostgresFromEnv);
372 self
373 }
374
375 pub fn with_redis(mut self, connection_string: impl Into<String>) -> Self {
377 self.storage = Some(QuickStartStorage::Redis(connection_string.into()));
378 self
379 }
380
381 pub fn with_redis_from_env(mut self) -> Self {
383 self.storage = Some(QuickStartStorage::RedisFromEnv);
384 self
385 }
386
387 pub fn with_memory_storage(mut self) -> Self {
389 self.storage = Some(QuickStartStorage::Memory);
390 self
391 }
392
393 pub fn with_axum(mut self) -> Self {
395 self.framework = Some(QuickStartFramework::Axum);
396 self
397 }
398
399 pub fn with_actix(mut self) -> Self {
401 self.framework = Some(QuickStartFramework::ActixWeb);
402 self
403 }
404
405 pub fn with_warp(mut self) -> Self {
407 self.framework = Some(QuickStartFramework::Warp);
408 self
409 }
410
411 pub fn security_level(mut self, level: SecurityPreset) -> Self {
413 self.security_level = level;
414 self
415 }
416
417 pub async fn build(self) -> Result<AuthFramework, AuthError> {
419 let mut builder = AuthBuilder::new().security_preset(self.security_level);
420
421 match self.auth_method {
423 Some(QuickStartAuth::Jwt { secret }) => {
424 builder = builder.with_jwt().secret(secret).done();
425 }
426 Some(QuickStartAuth::JwtFromEnv) => {
427 let secret = std::env::var("JWT_SECRET").map_err(|_| {
428 AuthError::config("JWT_SECRET environment variable is required")
429 })?;
430 builder = builder.with_jwt().secret(secret).done();
431 }
432 Some(QuickStartAuth::OAuth2 {
433 client_id,
434 client_secret,
435 }) => {
436 builder = builder
437 .with_oauth2()
438 .client_id(client_id)
439 .client_secret(client_secret)
440 .done();
441 }
442 Some(QuickStartAuth::Combined {
443 jwt_secret,
444 oauth_client_id,
445 oauth_client_secret,
446 }) => {
447 builder = builder
448 .with_jwt()
449 .secret(jwt_secret)
450 .done()
451 .with_oauth2()
452 .client_id(oauth_client_id)
453 .client_secret(oauth_client_secret)
454 .done();
455 }
456 None => {
457 return Err(AuthError::config("Authentication method is required"));
458 }
459 }
460
461 match self.storage {
463 Some(QuickStartStorage::Memory) => {
464 builder = builder.with_storage().memory().done();
465 }
466 Some(QuickStartStorage::Postgres(conn_str)) => {
467 builder = builder.with_storage().postgres(conn_str).done();
468 }
469 Some(QuickStartStorage::PostgresFromEnv) => {
470 let conn_str = std::env::var("DATABASE_URL").map_err(|_| {
471 AuthError::config("DATABASE_URL environment variable is required")
472 })?;
473 builder = builder.with_storage().postgres(conn_str).done();
474 }
475 Some(QuickStartStorage::Redis(_conn_str)) => {
476 builder = builder.with_storage().memory().done();
478 }
479 Some(QuickStartStorage::RedisFromEnv) => {
480 builder = builder.with_storage().memory().done();
482 }
483 None => {
484 builder = builder.with_storage().memory().done();
486 }
487 }
488
489 builder.build().await
490 }
491}
492
493pub struct JwtBuilder {
495 parent: AuthBuilder,
496 secret: Option<String>,
497 issuer: Option<String>,
498 audience: Option<String>,
499 token_lifetime: Option<Duration>,
500}
501
502impl JwtBuilder {
503 fn new(parent: AuthBuilder) -> Self {
504 Self {
505 parent,
506 secret: None,
507 issuer: None,
508 audience: None,
509 token_lifetime: None,
510 }
511 }
512
513 pub fn secret(mut self, secret: impl Into<String>) -> Self {
515 self.secret = Some(secret.into());
516 self
517 }
518
519 pub fn secret_from_env(mut self, env_var: &str) -> Self {
521 if let Ok(secret) = std::env::var(env_var) {
522 self.secret = Some(secret);
523 }
524 self
525 }
526
527 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
529 self.issuer = Some(issuer.into());
530 self
531 }
532
533 pub fn audience(mut self, audience: impl Into<String>) -> Self {
535 self.audience = Some(audience.into());
536 self
537 }
538
539 pub fn token_lifetime(mut self, lifetime: Duration) -> Self {
541 self.token_lifetime = Some(lifetime);
542 self
543 }
544
545 pub fn done(mut self) -> AuthBuilder {
547 if let Some(secret) = self.secret {
548 self.parent.config.secret = Some(secret);
549 }
550 if let Some(issuer) = self.issuer {
551 self.parent.config.issuer = issuer;
552 }
553 if let Some(audience) = self.audience {
554 self.parent.config.audience = audience;
555 }
556 if let Some(lifetime) = self.token_lifetime {
557 self.parent.config.token_lifetime = lifetime;
558 }
559 self.parent
560 }
561}
562
563pub struct OAuth2Builder {
565 parent: AuthBuilder,
566 client_id: Option<String>,
567 client_secret: Option<String>,
568 redirect_uri: Option<String>,
569}
570
571impl OAuth2Builder {
572 fn new(parent: AuthBuilder) -> Self {
573 Self {
574 parent,
575 client_id: None,
576 client_secret: None,
577 redirect_uri: None,
578 }
579 }
580
581 pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
583 self.client_id = Some(client_id.into());
584 self
585 }
586
587 pub fn client_secret(mut self, client_secret: impl Into<String>) -> Self {
589 self.client_secret = Some(client_secret.into());
590 self
591 }
592
593 pub fn redirect_uri(mut self, redirect_uri: impl Into<String>) -> Self {
595 self.redirect_uri = Some(redirect_uri.into());
596 self
597 }
598
599 pub fn google_client_id(self, client_id: impl Into<String>) -> Self {
601 self.client_id(client_id)
602 }
603
604 pub fn github_client_id(self, client_id: impl Into<String>) -> Self {
606 self.client_id(client_id)
607 }
608
609 pub fn done(self) -> AuthBuilder {
611 self.parent
614 }
615}
616
617pub struct StorageBuilder {
619 parent: AuthBuilder,
620}
621
622impl StorageBuilder {
623 fn new(parent: AuthBuilder) -> Self {
624 Self { parent }
625 }
626
627 pub fn memory(mut self) -> Self {
629 self.parent.config.storage = StorageConfig::Memory;
630 self
631 }
632
633 #[cfg(feature = "postgres-storage")]
635 pub fn postgres(mut self, connection_string: impl Into<String>) -> Self {
636 self.parent.config.storage = StorageConfig::Postgres {
637 connection_string: connection_string.into(),
638 table_prefix: "auth_".to_string(),
639 };
640 self
641 }
642
643 #[cfg(feature = "postgres-storage")]
645 pub fn postgres_from_env(mut self) -> Self {
646 if let Ok(conn_str) = std::env::var("DATABASE_URL") {
647 self = self.postgres(conn_str);
648 }
649 self
650 }
651
652 #[cfg(feature = "redis-storage")]
654 pub fn redis(mut self, url: impl Into<String>) -> Self {
655 self.parent.config.storage = StorageConfig::Redis {
656 url: url.into(),
657 key_prefix: "auth:".to_string(),
658 };
659 self
660 }
661
662 #[cfg(feature = "redis-storage")]
664 pub fn redis_from_env(mut self) -> Self {
665 if let Ok(url) = std::env::var("REDIS_URL") {
666 self = self.redis(url);
667 }
668 self
669 }
670
671 pub fn connection_pool_size(self, _size: u32) -> Self {
673 self
675 }
676
677 pub fn done(self) -> AuthBuilder {
679 self.parent
680 }
681}
682
683pub struct RateLimitBuilder {
685 parent: AuthBuilder,
686}
687
688impl RateLimitBuilder {
689 fn new(parent: AuthBuilder) -> Self {
690 Self { parent }
691 }
692
693 pub fn per_ip(mut self, (requests, window): (u32, Duration)) -> Self {
695 self.parent.config.rate_limiting = RateLimitConfig {
696 enabled: true,
697 max_requests: requests,
698 window,
699 burst: requests / 10,
700 };
701 self
702 }
703
704 pub fn disabled(mut self) -> Self {
706 self.parent.config.rate_limiting.enabled = false;
707 self
708 }
709
710 pub fn done(self) -> AuthBuilder {
712 self.parent
713 }
714}
715
716pub struct SecurityBuilder {
718 parent: AuthBuilder,
719}
720
721impl SecurityBuilder {
722 fn new(parent: AuthBuilder) -> Self {
723 Self { parent }
724 }
725
726 pub fn min_password_length(mut self, length: usize) -> Self {
728 self.parent.config.security.min_password_length = length;
729 self
730 }
731
732 pub fn require_password_complexity(mut self, required: bool) -> Self {
734 self.parent.config.security.require_password_complexity = required;
735 self
736 }
737
738 pub fn secure_cookies(mut self, enabled: bool) -> Self {
740 self.parent.config.security.secure_cookies = enabled;
741 self
742 }
743
744 pub fn done(self) -> AuthBuilder {
746 self.parent
747 }
748}
749
750pub struct AuditBuilder {
752 parent: AuthBuilder,
753}
754
755impl AuditBuilder {
756 fn new(parent: AuthBuilder) -> Self {
757 Self { parent }
758 }
759
760 pub fn enabled(mut self, enabled: bool) -> Self {
762 self.parent.config.audit.enabled = enabled;
763 self
764 }
765
766 pub fn log_success(mut self, enabled: bool) -> Self {
768 self.parent.config.audit.log_success = enabled;
769 self
770 }
771
772 pub fn log_failures(mut self, enabled: bool) -> Self {
774 self.parent.config.audit.log_failures = enabled;
775 self
776 }
777
778 pub fn done(self) -> AuthBuilder {
780 self.parent
781 }
782}
783
784impl Default for AuthBuilder {
785 fn default() -> Self {
786 Self::new()
787 }
788}