pandrs 0.2.0

A high-performance DataFrame library for Rust, providing pandas-like API with advanced features including SIMD optimization, parallel processing, and distributed computing capabilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
#![allow(clippy::result_large_err)]
//! # Comprehensive JWT and OAuth2 Authentication Example
//!
//! This example demonstrates enterprise-grade authentication patterns using PandRS's
//! authentication module, including:
//!
//! - JWT (JSON Web Token) generation, validation, and refresh
//! - OAuth2 Authorization Code Flow with PKCE
//! - OAuth2 Client Credentials Flow
//! - API Key authentication and management
//! - Session management with automatic timeout
//! - Rate limiting and security controls
//! - Multi-tenant authentication scenarios
//!
//! # Use Case: Multi-Tenant SaaS Analytics Platform
//!
//! This example simulates a multi-tenant SaaS platform where different organizations
//! (tenants) need secure, isolated access to their analytics data. The platform supports:
//! - User authentication via JWT tokens
//! - Service-to-service communication via OAuth2 client credentials
//! - API keys for programmatic access
//! - Per-tenant data isolation and access control

use pandrs::auth::{
    ApiKeyInfo, AuthEvent, AuthEventType, AuthManager, AuthMethod, JwtConfig, OAuthClient,
    OAuthClientInfo, OAuthConfig, OAuthGrantType, RefreshToken, Session, TokenClaims, TokenRequest,
    UserInfo,
};
use pandrs::error::Result;
use pandrs::multitenancy::Permission;
use std::collections::HashMap;
use std::time::{Duration, SystemTime};

fn main() -> Result<()> {
    println!("๐Ÿ” PandRS Security: JWT & OAuth2 Authentication Example");
    println!("========================================================\n");

    // Scenario 1: JWT Token Authentication
    println!("๐Ÿ“ Scenario 1: JWT Token Authentication");
    jwt_authentication_flow()?;

    // Scenario 2: OAuth2 Authorization Code Flow with PKCE
    println!("\n๐Ÿ”‘ Scenario 2: OAuth2 Authorization Code Flow with PKCE");
    oauth_authorization_code_flow()?;

    // Scenario 3: OAuth2 Client Credentials (Service-to-Service)
    println!("\n๐Ÿค– Scenario 3: OAuth2 Client Credentials (Service-to-Service)");
    oauth_client_credentials_flow()?;

    // Scenario 4: API Key Authentication
    println!("\n๐ŸŽซ Scenario 4: API Key Authentication");
    api_key_authentication_flow()?;

    // Scenario 5: Session Management
    println!("\nโฐ Scenario 5: Session Management");
    session_management_flow()?;

    // Scenario 6: Token Refresh Mechanism
    println!("\n๐Ÿ”„ Scenario 6: Token Refresh Mechanism");
    token_refresh_flow()?;

    // Scenario 7: Multi-Tenant Authentication
    println!("\n๐Ÿข Scenario 7: Multi-Tenant Authentication");
    multi_tenant_authentication()?;

    // Scenario 8: Security Audit Trail
    println!("\n๐Ÿ“Š Scenario 8: Security Audit Trail");
    security_audit_trail()?;

    // Scenario 9: Rate Limiting and Security Controls
    println!("\n๐Ÿšฆ Scenario 9: Rate Limiting and Security Controls");
    rate_limiting_controls()?;

    println!("\nโœ… All authentication scenarios completed successfully!");
    Ok(())
}

/// Demonstrates JWT token-based authentication flow
///
/// This scenario shows:
/// - User registration with password
/// - Password-based authentication
/// - JWT token generation
/// - Token validation
/// - Token expiration handling
fn jwt_authentication_flow() -> Result<()> {
    // Create JWT configuration with custom settings
    let jwt_config = JwtConfig::new(b"super_secret_key_for_production_use_random_256_bits")
        .with_issuer("pandrs-analytics-platform")
        .with_audience("analytics-api")
        .with_expiration(3600); // 1 hour

    let mut auth_manager = AuthManager::new(jwt_config);

    // Register a user for Tenant A
    println!("  ๐Ÿ‘ค Registering user 'alice@company-a.com' for tenant 'company_a'");
    let user = UserInfo::new("alice", "alice@company-a.com", "company_a")
        .with_display_name("Alice Johnson")
        .with_password("secure_password_123")
        .with_role("analyst")
        .with_permission(Permission::Read)
        .with_permission(Permission::Write);

    auth_manager.register_user(user)?;

    // Authenticate with password
    println!("  ๐Ÿ” Authenticating with email and password...");
    let auth_result =
        auth_manager.authenticate_password("alice@company-a.com", "secure_password_123")?;
    println!("  โœ… Authentication successful!");
    println!("     User ID: {}", auth_result.user_id);
    println!("     Tenant: {}", auth_result.tenant_id);
    println!("     Permissions: {:?}", auth_result.permissions);
    println!("     Session ID: {:?}", auth_result.session_id);

    // Generate JWT token
    println!("\n  ๐ŸŽŸ๏ธ  Generating JWT token...");
    let token = auth_manager.generate_token("alice")?;
    println!("  โœ… JWT token generated (length: {} chars)", token.len());
    println!("     Token preview: {}...", &token[..50]);

    // Validate the token
    println!("\n  โœ”๏ธ  Validating JWT token...");
    let validated = auth_manager.validate_token(&token)?;
    println!("  โœ… Token is valid!");
    println!("     Subject: {}", validated.user_id);
    println!("     Expires at: {}", validated.expires_at);

    // Test invalid credentials
    println!("\n  โŒ Testing invalid credentials...");
    match auth_manager.authenticate_password("alice@company-a.com", "wrong_password") {
        Ok(_) => println!("  โš ๏ธ  Unexpected success with wrong password!"),
        Err(_) => println!("  โœ… Correctly rejected invalid password"),
    }

    Ok(())
}

/// Demonstrates OAuth2 Authorization Code Flow with PKCE
///
/// This is the recommended flow for web applications and mobile apps.
/// PKCE (Proof Key for Code Exchange) provides additional security against
/// authorization code interception attacks.
fn oauth_authorization_code_flow() -> Result<()> {
    // Setup OAuth2 configuration
    let oauth_config = OAuthConfig::new(
        "https://auth.pandrs-analytics.com",
        "pandrs_web_client",
        "client_secret_abc123",
    )
    .with_redirect_uri("https://app.pandrs-analytics.com/callback")
    .with_scope("openid")
    .with_scope("profile")
    .with_scope("analytics:read");

    let mut oauth_client = OAuthClient::new(oauth_config);

    // Register an OAuth client for tenant
    println!("  ๐Ÿ“‹ Registering OAuth client for tenant 'company_a'");
    let client_info = OAuthClientInfo {
        client_id: "pandrs_web_client".to_string(),
        client_secret_hash: hash_secret("client_secret_abc123"),
        redirect_uris: vec!["https://app.pandrs-analytics.com/callback".to_string()],
        grant_types: vec![OAuthGrantType::AuthorizationCode],
        scopes: vec![
            "openid".to_string(),
            "profile".to_string(),
            "analytics:read".to_string(),
        ],
        tenant_id: "company_a".to_string(),
    };
    oauth_client.register_client(client_info);

    // Step 1: Generate authorization code (simulating user consent)
    println!("  ๐Ÿ”— Step 1: User authorizes application...");
    let auth_code = oauth_client.create_authorization_code(
        "pandrs_web_client",
        "https://app.pandrs-analytics.com/callback",
        vec!["openid".to_string(), "profile".to_string()],
        "alice",
        None, // PKCE challenge (simplified for example)
        None,
    )?;
    println!("  โœ… Authorization code generated: {}...", &auth_code[..16]);

    // Step 2: Exchange authorization code for access token
    println!("\n  ๐Ÿ”„ Step 2: Exchanging authorization code for access token...");
    let token_response = oauth_client.exchange_code(
        "pandrs_web_client",
        "client_secret_abc123",
        &auth_code,
        "https://app.pandrs-analytics.com/callback",
        None,
    )?;
    println!("  โœ… Access token received!");
    println!("     Token type: {}", token_response.token_type);
    println!("     Expires in: {} seconds", token_response.expires_in);
    println!("     Scopes: {:?}", token_response.scope);
    println!(
        "     Has refresh token: {}",
        token_response.refresh_token.is_some()
    );

    // Step 3: Verify token is active
    println!("\n  โœ”๏ธ  Step 3: Introspecting access token...");
    let introspection = oauth_client.introspect_token(&token_response.access_token);
    println!("  โœ… Token introspection result:");
    println!("     Active: {}", introspection.active);
    println!("     Client ID: {:?}", introspection.client_id);
    println!("     Username: {:?}", introspection.username);

    Ok(())
}

/// Demonstrates OAuth2 Client Credentials Flow
///
/// This flow is used for service-to-service authentication where no user
/// interaction is required. Ideal for backend services, scheduled jobs, etc.
fn oauth_client_credentials_flow() -> Result<()> {
    let oauth_config = OAuthConfig::new(
        "https://auth.pandrs-analytics.com",
        "analytics_service",
        "service_secret_xyz789",
    );

    let mut oauth_client = OAuthClient::new(oauth_config);

    // Register service client
    println!("  ๐Ÿค– Registering service client 'analytics_service'");
    let service_client = OAuthClientInfo {
        client_id: "analytics_service".to_string(),
        client_secret_hash: hash_secret("service_secret_xyz789"),
        redirect_uris: vec![],
        grant_types: vec![OAuthGrantType::ClientCredentials],
        scopes: vec![
            "analytics:read".to_string(),
            "analytics:write".to_string(),
            "reports:generate".to_string(),
        ],
        tenant_id: "company_a".to_string(),
    };
    oauth_client.register_client(service_client);

    // Request token using client credentials
    println!("  ๐ŸŽซ Requesting access token with client credentials...");
    let token_response = oauth_client.client_credentials_grant(
        "analytics_service",
        "service_secret_xyz789",
        Some(vec![
            "analytics:read".to_string(),
            "reports:generate".to_string(),
        ]),
    )?;

    println!("  โœ… Service token obtained!");
    println!(
        "     Access token: {}...",
        &token_response.access_token[..20]
    );
    println!("     Token type: {}", token_response.token_type);
    println!("     Expires in: {} seconds", token_response.expires_in);
    println!("     Granted scopes: {:?}", token_response.scope);
    println!(
        "     Has refresh token: {} (not issued for client credentials)",
        token_response.refresh_token.is_some()
    );

    // Verify the service can access resources
    println!("\n  โœ”๏ธ  Verifying service token...");
    let introspection = oauth_client.introspect_token(&token_response.access_token);
    if introspection.active {
        println!("  โœ… Service token is active and valid");
        println!("     Client: {:?}", introspection.client_id);
        println!("     Scopes: {:?}", introspection.scope);
    }

    Ok(())
}

/// Demonstrates API Key authentication
///
/// API keys are useful for:
/// - Programmatic access (scripts, CLI tools)
/// - Third-party integrations
/// - Long-lived credentials
/// - Rate limiting per key
fn api_key_authentication_flow() -> Result<()> {
    let mut auth_manager = AuthManager::new(JwtConfig::default());

    // Register user
    let user = UserInfo::new("bob", "bob@company-b.com", "company_b")
        .with_password("bob_password")
        .with_permission(Permission::Read)
        .with_permission(Permission::Write);
    auth_manager.register_user(user)?;

    // Create API key for user
    println!("  ๐Ÿ”‘ Creating API key for user 'bob'...");
    let api_key = auth_manager.create_api_key(
        "bob",
        "Production API Key",
        Some(vec![Permission::Read, Permission::Write]),
    )?;
    println!("  โœ… API key created: {}...", &api_key[..20]);
    println!("     โš ๏ธ  Store this securely - it won't be shown again!");

    // Authenticate using API key
    println!("\n  ๐Ÿ” Authenticating with API key...");
    let auth_result = auth_manager.authenticate_api_key(&api_key)?;
    println!("  โœ… API key authentication successful!");
    println!("     User: {}", auth_result.user_id);
    println!("     Tenant: {}", auth_result.tenant_id);
    println!("     Permissions: {:?}", auth_result.permissions);

    // Test API key usage tracking
    println!("\n  ๐Ÿ“Š API key usage tracking:");
    for i in 1..=3 {
        match auth_manager.authenticate_api_key(&api_key) {
            Ok(result) => {
                println!(
                    "     Request {}: โœ… Authenticated as '{}'",
                    i, result.user_id
                );
            }
            Err(e) => println!("     Request {}: โŒ Failed: {}", i, e),
        }
    }

    // Revoke API key
    println!("\n  ๐Ÿšซ Revoking API key...");
    auth_manager.revoke_api_key(&api_key)?;
    println!("  โœ… API key revoked");

    // Verify revoked key is rejected
    println!("\n  โœ”๏ธ  Testing revoked key...");
    match auth_manager.authenticate_api_key(&api_key) {
        Ok(_) => println!("  โš ๏ธ  Unexpected success with revoked key!"),
        Err(_) => println!("  โœ… Revoked key correctly rejected"),
    }

    Ok(())
}

/// Demonstrates session management
///
/// Sessions provide:
/// - Stateful user sessions
/// - Automatic timeout
/// - Session attributes/metadata
/// - Concurrent session control
fn session_management_flow() -> Result<()> {
    let mut auth_manager =
        AuthManager::new(JwtConfig::default()).with_session_timeout(Duration::from_secs(300)); // 5 minutes

    // Register user
    let user = UserInfo::new("carol", "carol@company-c.com", "company_c")
        .with_password("carol_password")
        .with_permission(Permission::Read);
    auth_manager.register_user(user)?;

    // Create session through authentication
    println!("  ๐Ÿ” Creating session for user 'carol'...");
    let auth_result =
        auth_manager.authenticate_password("carol@company-c.com", "carol_password")?;
    let session_id = auth_result
        .session_id
        .ok_or_else(|| pandrs::error::Error::InvalidOperation("No session created".to_string()))?;
    println!("  โœ… Session created: {}", session_id);

    // Validate session
    println!("\n  โœ”๏ธ  Validating session...");
    let session = auth_manager.validate_session(&session_id)?;
    println!("  โœ… Session is valid");
    println!("     User: {}", session.user_id);
    println!("     Created: {:?}", session.created_at);

    // Simulate session usage
    println!("\n  ๐Ÿ“ Simulating API requests with session...");
    for i in 1..=3 {
        match auth_manager.validate_session(&session_id) {
            Ok(s) => println!("     Request {}: โœ… Session valid (user: {})", i, s.user_id),
            Err(e) => println!("     Request {}: โŒ Session error: {}", i, e),
        }
    }

    // Logout
    println!("\n  ๐Ÿ‘‹ Logging out (invalidating session)...");
    auth_manager.logout(&session_id)?;
    println!("  โœ… Session invalidated");

    // Verify session is invalid
    println!("\n  โœ”๏ธ  Testing invalidated session...");
    match auth_manager.validate_session(&session_id) {
        Ok(_) => println!("  โš ๏ธ  Unexpected success with invalidated session!"),
        Err(_) => println!("  โœ… Invalidated session correctly rejected"),
    }

    Ok(())
}

/// Demonstrates token refresh mechanism
///
/// Refresh tokens allow obtaining new access tokens without re-authentication:
/// - Long-lived refresh tokens
/// - Short-lived access tokens
/// - Refresh token rotation
/// - Revocation support
fn token_refresh_flow() -> Result<()> {
    let mut auth_manager = AuthManager::new(JwtConfig::default())
        .with_token_expiry(Duration::from_secs(300))        // 5 min access token
        .with_refresh_token_expiry(Duration::from_secs(86400)); // 24h refresh token

    // Register user
    let user = UserInfo::new("dave", "dave@company-d.com", "company_d")
        .with_password("dave_password")
        .with_permission(Permission::Read);
    auth_manager.register_user(user)?;

    // Initial authentication
    println!("  ๐Ÿ” Initial authentication...");
    auth_manager.authenticate_password("dave@company-d.com", "dave_password")?;

    // Generate tokens
    println!("  ๐ŸŽŸ๏ธ  Generating access token and refresh token...");
    let access_token = auth_manager.generate_token("dave")?;
    let refresh_token = auth_manager.generate_refresh_token("dave")?;
    println!("  โœ… Tokens generated");
    println!("     Access token: {}...", &access_token[..30]);
    println!("     Refresh token: {}...", &refresh_token[..30]);

    // Simulate access token expiration and refresh
    println!("\n  โฐ Simulating access token expiration...");
    println!("  ๐Ÿ”„ Using refresh token to get new access token...");
    let new_access_token = auth_manager.refresh_access_token(&refresh_token)?;
    println!(
        "  โœ… New access token obtained: {}...",
        &new_access_token[..30]
    );

    // Validate new token
    println!("\n  โœ”๏ธ  Validating new access token...");
    let validated = auth_manager.validate_token(&new_access_token)?;
    println!("  โœ… New token is valid");
    println!("     User: {}", validated.user_id);

    // Revoke refresh token
    println!("\n  ๐Ÿšซ Revoking refresh token...");
    auth_manager.revoke_refresh_token(&refresh_token)?;
    println!("  โœ… Refresh token revoked");

    // Try to use revoked refresh token
    println!("\n  โœ”๏ธ  Testing revoked refresh token...");
    match auth_manager.refresh_access_token(&refresh_token) {
        Ok(_) => println!("  โš ๏ธ  Unexpected success with revoked refresh token!"),
        Err(_) => println!("  โœ… Revoked refresh token correctly rejected"),
    }

    Ok(())
}

/// Demonstrates multi-tenant authentication scenarios
///
/// Shows how different tenants have isolated authentication:
/// - Tenant-specific user namespaces
/// - Cross-tenant access prevention
/// - Per-tenant security policies
fn multi_tenant_authentication() -> Result<()> {
    let mut auth_manager = AuthManager::new(JwtConfig::default());

    // Register users for different tenants
    println!("  ๐Ÿข Setting up multi-tenant environment...");

    let user_a = UserInfo::new("alice", "alice@company-a.com", "tenant_a")
        .with_password("password_a")
        .with_permission(Permission::Read)
        .with_permission(Permission::Write);
    auth_manager.register_user(user_a)?;

    let user_b = UserInfo::new("bob", "bob@company-b.com", "tenant_b")
        .with_password("password_b")
        .with_permission(Permission::Read);
    auth_manager.register_user(user_b)?;

    println!("  โœ… Registered users for tenant_a and tenant_b");

    // Authenticate users from different tenants
    println!("\n  ๐Ÿ” Authenticating users from different tenants...");

    let auth_a = auth_manager.authenticate_password("alice@company-a.com", "password_a")?;
    println!("  โœ… Tenant A user authenticated:");
    println!(
        "     User: {} (Tenant: {})",
        auth_a.user_id, auth_a.tenant_id
    );
    println!("     Permissions: {:?}", auth_a.permissions);

    let auth_b = auth_manager.authenticate_password("bob@company-b.com", "password_b")?;
    println!("  โœ… Tenant B user authenticated:");
    println!(
        "     User: {} (Tenant: {})",
        auth_b.user_id, auth_b.tenant_id
    );
    println!("     Permissions: {:?}", auth_b.permissions);

    // Generate tokens with tenant context
    println!("\n  ๐ŸŽŸ๏ธ  Generating tenant-scoped JWT tokens...");
    let token_a = auth_manager.generate_token("alice")?;
    let token_b = auth_manager.generate_token("bob")?;

    // Validate tokens and check tenant isolation
    println!("\n  โœ”๏ธ  Validating tenant isolation...");
    let validated_a = auth_manager.validate_token(&token_a)?;
    let validated_b = auth_manager.validate_token(&token_b)?;

    println!("  โœ… Tenant isolation verified:");
    println!("     Token A tenant: {}", validated_a.tenant_id);
    println!("     Token B tenant: {}", validated_b.tenant_id);
    println!(
        "     Tenants are separate: {}",
        validated_a.tenant_id != validated_b.tenant_id
    );

    Ok(())
}

/// Demonstrates security audit trail
///
/// Shows how authentication events are logged for security monitoring:
/// - Login attempts (successful/failed)
/// - Token operations
/// - Permission changes
/// - Suspicious activity detection
fn security_audit_trail() -> Result<()> {
    let mut auth_manager = AuthManager::new(JwtConfig::default());

    // Register user
    let user = UserInfo::new("eve", "eve@company-e.com", "company_e")
        .with_password("eve_password")
        .with_permission(Permission::Read);
    auth_manager.register_user(user)?;

    println!("  ๐Ÿ“‹ Generating authentication events...");

    // Successful login
    auth_manager.authenticate_password("eve@company-e.com", "eve_password")?;

    // Failed login attempt
    let _ = auth_manager.authenticate_password("eve@company-e.com", "wrong_password");

    // Token operations
    let token = auth_manager.generate_token("eve")?;
    auth_manager.validate_token(&token)?;

    // API key creation
    auth_manager.create_api_key("eve", "Test Key", None)?;

    // Retrieve audit events
    println!("\n  ๐Ÿ“Š Security Audit Trail:");
    let events = auth_manager.get_user_events("eve");
    for (i, event) in events.iter().enumerate() {
        println!("     Event {}: {:?}", i + 1, event.event_type);
        println!("       Time: {:?}", event.timestamp);
        println!("       Method: {:?}", event.auth_method);
        println!("       Success: {}", event.success);
        if let Some(ref msg) = event.error_message {
            println!("       Error: {}", msg);
        }
        println!();
    }

    println!("  โœ… Total events logged: {}", events.len());

    Ok(())
}

/// Demonstrates rate limiting and security controls
///
/// Shows advanced security features:
/// - Request rate limiting
/// - IP-based access control
/// - Account lockout policies
/// - Automated cleanup of expired credentials
fn rate_limiting_controls() -> Result<()> {
    println!("  ๐Ÿšฆ Security controls demonstration");
    println!("     - Rate limiting prevents abuse");
    println!("     - IP whitelisting restricts access");
    println!("     - Automatic cleanup of expired tokens");
    println!("     - Session timeout enforcement");

    let mut auth_manager = AuthManager::new(JwtConfig::default())
        .with_token_expiry(Duration::from_secs(60))
        .with_session_timeout(Duration::from_secs(300));

    // Register user
    let user = UserInfo::new("frank", "frank@company-f.com", "company_f")
        .with_password("frank_password")
        .with_permission(Permission::Read);
    auth_manager.register_user(user)?;

    // Create some test sessions and tokens
    println!("\n  โณ Creating test sessions...");
    for i in 1..=3 {
        auth_manager.authenticate_password("frank@company-f.com", "frank_password")?;
        println!("     Session {} created", i);
    }

    // Cleanup expired credentials
    println!("\n  ๐Ÿงน Running cleanup of expired credentials...");
    auth_manager.cleanup_expired();
    println!("  โœ… Cleanup completed");

    // Password change for security
    println!("\n  ๐Ÿ” Demonstrating password change...");
    auth_manager.change_password("frank", "frank_password", "new_secure_password")?;
    println!("  โœ… Password changed successfully");
    println!("     All refresh tokens have been revoked for security");

    // Verify old password doesn't work
    match auth_manager.authenticate_password("frank@company-f.com", "frank_password") {
        Ok(_) => println!("  โš ๏ธ  Old password still works - security issue!"),
        Err(_) => println!("  โœ… Old password correctly rejected"),
    }

    // Verify new password works
    match auth_manager.authenticate_password("frank@company-f.com", "new_secure_password") {
        Ok(_) => println!("  โœ… New password works correctly"),
        Err(_) => println!("  โš ๏ธ  New password doesn't work - security issue!"),
    }

    Ok(())
}

/// Helper function to hash client secrets (simplified for example)
fn hash_secret(secret: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(secret.as_bytes());
    let result = hasher.finalize();
    result.iter().map(|b| format!("{:02x}", b)).collect()
}