auth_framework/prelude.rs
1//! Auth Framework Prelude
2//!
3//! This module provides a convenient way to import the most commonly used types
4//! and traits from the auth framework. Instead of importing individual types,
5//! you can simply use:
6//!
7//! ```rust
8//! use auth_framework::prelude::*;
9//! ```
10//!
11//! This imports all the essential types you need to get started with authentication
12//! and authorization in your application.
13//!
14//! # What's Included
15//!
16//! ## Core Framework Types
17//! - [`AuthFramework`] - Main authentication framework
18//! - [`AuthConfig`] - Configuration builder
19//! - [`AuthError`] - Error type with detailed error variants
20//! - [`AuthFrameworkResult`] - Convenient Result type alias
21//!
22//! ## Authentication Methods
23//! - [`JwtMethod`] - JWT authentication
24//! - [`OAuth2Method`] - OAuth 2.0 authentication
25//! - [`ApiKeyMethod`] - API key authentication
26//! - [`PasswordMethod`] - Password-based authentication
27//!
28//! ## Tokens and Sessions
29//! - [`AuthToken`] - Authentication token representation
30//! - [`SessionData`] - Session data structure
31//! - [`UserProfile`] - User profile information
32//!
33//! ## Permissions and Authorization
34//! - [`Permission`] - Permission representation
35//! - [`Role`] - Role representation
36//! - [`PermissionChecker`] - Permission validation trait
37//!
38//! ## Storage Abstractions
39//! - [`AuthStorage`] - Storage trait for persistence
40//! - [`MemoryStorage`] - In-memory storage implementation
41//!
42//! ## Web Framework Integration
43//! - [`RequireAuth`] - Middleware for requiring authentication
44//! - [`AuthenticatedUser`] - Extractor for authenticated users
45//! - [`RequirePermission`] - Middleware for permission checking
46//!
47//! ## Builder Patterns and Helpers
48//! - [`AuthBuilder`] - Fluent builder for framework setup
49//! - [`SecurityPreset`] - Pre-configured security levels
50//! - [`ConfigBuilder`] - Configuration builder
51//!
52//! ## Time and Rate Limiting Helpers
53//! - Time duration helpers: [`hours`], [`minutes`], [`days`], [`weeks`]
54//! - Rate limiting helpers: [`requests`], [`per_second`], [`per_minute`], [`per_hour`]
55//!
56//! # Quick Start Example
57//!
58//! ```rust,no_run
59//! use auth_framework::prelude::*;
60//!
61//! #[tokio::main]
62//! async fn main() -> AuthFrameworkResult<()> {
63//! // Create auth framework with sensible defaults
64//! let auth = AuthFramework::quick_start()
65//! .jwt_auth_from_env()
66//! .with_postgres_from_env()
67//! .build().await?;
68//!
69//! // Create a token
70//! let token = auth.create_auth_token(
71//! "user123",
72//! vec!["read".to_string()],
73//! "jwt",
74//! None
75//! ).await?;
76//!
77//! // Validate token
78//! if auth.validate_token(&token).await? {
79//! println!("Token is valid!");
80//! }
81//!
82//! Ok(())
83//! }
84//! ```
85
86// Re-export core framework types
87pub use crate::AuthFramework;
88pub use crate::auth::{AuthStats, UserInfo};
89
90// Re-export configuration types
91pub use crate::config::app_config::{AppConfig, ConfigBuilder};
92pub use crate::config::{
93 AuditConfig, AuthConfig, CookieSameSite, JwtAlgorithm, PasswordHashAlgorithm, RateLimitConfig,
94 SecurityConfig, StorageConfig,
95};
96
97// Re-export error types
98pub use crate::errors::{
99 AuthError, DeviceFlowError, MfaError, OAuthProviderError, PermissionError, Result,
100 StorageError, TokenError,
101};
102
103// Re-export authentication methods
104pub use crate::methods::{
105 ApiKeyMethod, AuthMethod, AuthMethodEnum, JwtMethod, MethodResult, OAuth2Method, PasswordMethod,
106};
107
108// Re-export SAML if available
109#[cfg(feature = "saml")]
110pub use crate::methods::saml;
111
112// Re-export tokens and user data
113pub use crate::authentication::credentials::Credential;
114pub use crate::providers::{OAuthProvider, OAuthProviderConfig, UserProfile};
115pub use crate::tokens::{AuthToken, TokenMetadata};
116
117// Re-export permissions and roles
118pub use crate::permissions::{Permission, PermissionChecker, Role};
119
120// Re-export authorization if enhanced RBAC is enabled
121#[cfg(feature = "enhanced-rbac")]
122pub use crate::authorization::{
123 AccessCondition, AuthorizationEngine, Permission as AuthzPermission, Role as AuthzRole,
124};
125
126// Re-export storage abstractions
127pub use crate::storage::{AuthStorage, MemoryStorage, SessionData};
128
129// Re-export session management
130pub use crate::security::secure_session::{
131 DeviceFingerprint, SecureSession, SecureSessionConfig, SecureSessionManager, SecurityFlags,
132 SessionState as SecureSessionState,
133};
134pub use crate::session::manager::{
135 DeviceInfo, Session, SessionConfig, SessionManager as LegacySessionManager, SessionState,
136};
137
138// Re-export middleware and extractors for web frameworks
139#[cfg(feature = "axum-integration")]
140pub use crate::integrations::axum::{
141 AuthMiddleware, AuthenticatedUser, RequireAuth, RequirePermission,
142};
143
144#[cfg(feature = "actix-integration")]
145pub use crate::integrations::actix_web::AuthMiddleware as ActixAuthMiddleware;
146
147#[cfg(feature = "warp-integration")]
148pub use crate::integrations::warp::{with_auth, with_permission};
149
150// Re-export monitoring and observability
151pub use crate::monitoring::{
152 HealthCheckResult, HealthStatus, MonitoringManager, PerformanceMetrics, SecurityEvent,
153 SecurityEventSeverity, SecurityEventType,
154};
155
156// Re-export audit logging
157pub use crate::audit::{AuditEvent, AuditEventType, AuditLogger, EventOutcome, RiskLevel};
158
159// Re-export security utilities
160pub use crate::security::secure_jwt::{SecureJwtClaims, SecureJwtConfig, SecureJwtValidator};
161pub use crate::security::secure_utils::{SecureComparison, SecureRandomGen};
162pub use crate::security::{
163 SecurityAuditReport, SecurityAuditStatus, SecurityIssue, SecuritySeverity,
164};
165
166// Re-export rate limiting
167pub use crate::utils::rate_limit::RateLimiter;
168
169// Re-export testing utilities
170#[cfg(any(test, feature = "testing"))]
171pub use crate::testing::{MockAuthMethod, MockStorage};
172
173// Re-export CLI tools if available
174#[cfg(feature = "cli")]
175pub use crate::cli;
176
177// Re-export API server if available
178#[cfg(feature = "api-server")]
179pub use crate::api::{ApiError, ApiResponse, ApiServer, ApiState};
180
181// Re-export OIDC server components
182pub use crate::server::oidc::{
183 IdTokenClaims, Jwk, JwkSet, OidcConfig, OidcDiscoveryDocument, OidcProvider,
184 UserInfo as OidcUserInfo,
185};
186
187// Re-export OAuth2 server
188pub use crate::oauth2_server::{
189 AuthorizationRequest, GrantType, OAuth2Config, OAuth2Server, ResponseType, TokenRequest,
190 TokenResponse,
191};
192
193// Builder patterns and ergonomic helpers (to be implemented)
194pub use crate::builders::*;
195
196// Time duration helpers for ergonomic configuration
197pub mod time {
198 use std::time::Duration;
199
200 /// Create a duration representing the specified number of hours
201 pub fn hours(h: u64) -> Duration {
202 Duration::from_secs(h * 3600)
203 }
204
205 /// Create a duration representing the specified number of minutes
206 pub fn minutes(m: u64) -> Duration {
207 Duration::from_secs(m * 60)
208 }
209
210 /// Create a duration representing the specified number of days
211 pub fn days(d: u64) -> Duration {
212 Duration::from_secs(d * 86400)
213 }
214
215 /// Create a duration representing the specified number of weeks
216 pub fn weeks(w: u64) -> Duration {
217 Duration::from_secs(w * 604800)
218 }
219
220 /// Create a duration representing the specified number of seconds
221 pub fn seconds(s: u64) -> Duration {
222 Duration::from_secs(s)
223 }
224}
225
226// Rate limiting helpers for ergonomic configuration
227pub mod rate {
228 use std::time::Duration;
229
230 /// Helper for specifying request counts in rate limiting
231 pub struct RequestCount(pub u32);
232
233 /// Helper for creating request count specifications
234 pub fn requests(count: u32) -> RequestCount {
235 RequestCount(count)
236 }
237
238 impl RequestCount {
239 /// Specify rate limit as "per second"
240 pub fn per_second(self) -> (u32, Duration) {
241 (self.0, Duration::from_secs(1))
242 }
243
244 /// Specify rate limit as "per minute"
245 pub fn per_minute(self) -> (u32, Duration) {
246 (self.0, Duration::from_secs(60))
247 }
248
249 /// Specify rate limit as "per hour"
250 pub fn per_hour(self) -> (u32, Duration) {
251 (self.0, Duration::from_secs(3600))
252 }
253
254 /// Specify rate limit as "per day"
255 pub fn per_day(self) -> (u32, Duration) {
256 (self.0, Duration::from_secs(86400))
257 }
258
259 /// Specify custom rate limit window
260 pub fn per(self, duration: Duration) -> (u32, Duration) {
261 (self.0, duration)
262 }
263 }
264}
265
266// Re-export time and rate helpers at the top level for convenience
267pub use rate::{RequestCount, requests};
268pub use time::{days, hours, minutes, seconds, weeks};
269
270// Common type aliases for ergonomics
271/// Common type alias for Results with AuthError
272pub type AuthFrameworkResult<T> = Result<T, AuthError>;
273pub type AsyncAuthHandler =
274 std::pin::Pin<Box<dyn std::future::Future<Output = AuthFrameworkResult<()>> + Send>>;
275
276// Import security presets from the security module
277pub use crate::security::SecurityPreset; // Performance presets for optimization (to be implemented)
278#[derive(Debug, Clone)]
279pub enum PerformancePreset {
280 /// Optimized for high request throughput
281 HighThroughput,
282 /// Optimized for low latency responses
283 LowLatency,
284 /// Optimized for minimal memory usage
285 LowMemory,
286 /// Balanced performance settings
287 Balanced,
288}
289
290// Use case presets for common application types (to be implemented)
291#[derive(Debug, Clone)]
292pub enum UseCasePreset {
293 /// Web application with sessions and cookies
294 WebApp,
295 /// REST API service with JWT tokens
296 ApiService,
297 /// Microservices with distributed auth
298 Microservices,
299 /// Mobile app backend
300 MobileBackend,
301 /// Enterprise application with RBAC
302 Enterprise,
303}