pandrs 0.3.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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
//! Enterprise Authentication Module
//!
//! This module provides enterprise-grade authentication features including:
//! - JWT (JSON Web Token) token generation and validation
//! - OAuth 2.0 support (Authorization Code and Client Credentials flows)
//! - API Key authentication
//! - Session management
//! - ReBAC (Relationship-Based Access Control)
//! - Integration with multi-tenancy
//!
//! # Example
//!
//! ```ignore
//! use pandrs::auth::{AuthManager, JwtConfig, TokenClaims};
//!
//! // Create authentication manager
//! let mut auth = AuthManager::new(JwtConfig::default());
//!
//! // Register a user
//! auth.register_user("user@example.com", "tenant_a", vec!["read", "write"])?;
//!
//! // Generate JWT token
//! let token = auth.generate_token("user@example.com")?;
//!
//! // Validate token
//! let claims = auth.validate_token(&token)?;
//! ```
//!
//! # ReBAC Example
//!
//! ```ignore
//! use pandrs::auth::rebac::RebacManager;
//!
//! let rebac = RebacManager::new();
//!
//! // Grant permission
//! rebac.grant("user:alice", "owner", "document:123")?;
//!
//! // Check permission
//! let can_access = rebac.check_access("user:alice", "owner", "document:123")?;
//! ```

pub mod api_key;
pub mod jwt;
pub mod oauth;
pub mod rebac;
pub mod session;

pub use api_key::*;
pub use jwt::*;
pub use oauth::*;
pub use rebac::*;
pub use session::*;

use crate::core::error::OptionExt;
use crate::error::{Error, Result};
use crate::multitenancy::{Permission, TenantId};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

/// Authentication result containing user identity and permissions
#[derive(Debug, Clone)]
pub struct AuthResult {
    /// User identifier
    pub user_id: String,
    /// Associated tenant
    pub tenant_id: TenantId,
    /// Granted permissions
    pub permissions: Vec<Permission>,
    /// Token expiration time (Unix timestamp)
    pub expires_at: u64,
    /// Session identifier
    pub session_id: Option<String>,
    /// Additional metadata
    pub metadata: HashMap<String, String>,
}

/// User registration information
#[derive(Debug, Clone)]
pub struct UserInfo {
    /// Unique user identifier
    pub user_id: String,
    /// Associated tenant ID
    pub tenant_id: TenantId,
    /// User email
    pub email: String,
    /// Display name
    pub display_name: Option<String>,
    /// Assigned roles
    pub roles: Vec<String>,
    /// Granted permissions
    pub permissions: Vec<Permission>,
    /// Whether the user is active
    pub active: bool,
    /// Creation timestamp
    pub created_at: SystemTime,
    /// Last login time
    pub last_login: Option<SystemTime>,
    /// Password hash (if using password auth)
    password_hash: Option<String>,
    /// API keys associated with this user
    pub api_keys: Vec<String>,
}

impl UserInfo {
    /// Create a new user info
    pub fn new(
        user_id: impl Into<String>,
        email: impl Into<String>,
        tenant_id: impl Into<String>,
    ) -> Self {
        UserInfo {
            user_id: user_id.into(),
            email: email.into(),
            tenant_id: tenant_id.into(),
            display_name: None,
            roles: Vec::new(),
            permissions: vec![Permission::Read],
            active: true,
            created_at: SystemTime::now(),
            last_login: None,
            password_hash: None,
            api_keys: Vec::new(),
        }
    }

    /// Set display name
    pub fn with_display_name(mut self, name: impl Into<String>) -> Self {
        self.display_name = Some(name.into());
        self
    }

    /// Add a role
    pub fn with_role(mut self, role: impl Into<String>) -> Self {
        self.roles.push(role.into());
        self
    }

    /// Set permissions
    pub fn with_permissions(mut self, perms: Vec<Permission>) -> Self {
        self.permissions = perms;
        self
    }

    /// Add a permission
    pub fn with_permission(mut self, perm: Permission) -> Self {
        if !self.permissions.contains(&perm) {
            self.permissions.push(perm);
        }
        self
    }

    /// Set password (will be hashed)
    pub fn with_password(mut self, password: &str) -> Self {
        self.password_hash = Some(hash_password(password));
        self
    }

    /// Verify password
    pub fn verify_password(&self, password: &str) -> bool {
        match &self.password_hash {
            Some(hash) => verify_password(password, hash),
            None => false,
        }
    }
}

/// Authentication method types
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthMethod {
    /// JWT token authentication
    Jwt,
    /// OAuth 2.0
    OAuth,
    /// API Key authentication
    ApiKey,
    /// Password-based authentication
    Password,
    /// Service-to-service authentication
    ServiceAccount,
}

/// Authentication event for auditing
#[derive(Debug, Clone)]
pub struct AuthEvent {
    /// Event timestamp
    pub timestamp: SystemTime,
    /// Event type
    pub event_type: AuthEventType,
    /// User ID (if applicable)
    pub user_id: Option<String>,
    /// Tenant ID
    pub tenant_id: Option<TenantId>,
    /// Authentication method used
    pub auth_method: AuthMethod,
    /// Whether the event was successful
    pub success: bool,
    /// IP address (if available)
    pub ip_address: Option<String>,
    /// User agent (if available)
    pub user_agent: Option<String>,
    /// Error message (if failed)
    pub error_message: Option<String>,
}

/// Types of authentication events
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthEventType {
    /// User login attempt
    Login,
    /// User logout
    Logout,
    /// Token refresh
    TokenRefresh,
    /// Token validation
    TokenValidation,
    /// API key usage
    ApiKeyUsage,
    /// Password change
    PasswordChange,
    /// User registration
    UserRegistration,
    /// Permission denied
    PermissionDenied,
    /// Session expired
    SessionExpired,
}

/// Central authentication manager
#[derive(Debug)]
pub struct AuthManager {
    /// JWT configuration
    jwt_config: JwtConfig,
    /// OAuth configuration
    oauth_config: Option<OAuthConfig>,
    /// Registered users
    users: HashMap<String, UserInfo>,
    /// Active sessions
    sessions: HashMap<String, Session>,
    /// API keys
    api_keys: HashMap<String, ApiKeyInfo>,
    /// Refresh tokens
    refresh_tokens: HashMap<String, RefreshToken>,
    /// Authentication event log
    auth_events: Vec<AuthEvent>,
    /// Maximum events to keep
    max_events: usize,
    /// Token expiration duration
    token_expiry: Duration,
    /// Refresh token expiration duration
    refresh_token_expiry: Duration,
    /// Session timeout
    session_timeout: Duration,
}

impl AuthManager {
    /// Create a new authentication manager
    pub fn new(jwt_config: JwtConfig) -> Self {
        AuthManager {
            jwt_config,
            oauth_config: None,
            users: HashMap::new(),
            sessions: HashMap::new(),
            api_keys: HashMap::new(),
            refresh_tokens: HashMap::new(),
            auth_events: Vec::new(),
            max_events: 10000,
            token_expiry: Duration::from_secs(3600), // 1 hour
            refresh_token_expiry: Duration::from_secs(86400 * 7), // 7 days
            session_timeout: Duration::from_secs(3600), // 1 hour
        }
    }

    /// Configure OAuth
    pub fn with_oauth(mut self, config: OAuthConfig) -> Self {
        self.oauth_config = Some(config);
        self
    }

    /// Set token expiration duration
    pub fn with_token_expiry(mut self, duration: Duration) -> Self {
        self.token_expiry = duration;
        self
    }

    /// Set refresh token expiration duration
    pub fn with_refresh_token_expiry(mut self, duration: Duration) -> Self {
        self.refresh_token_expiry = duration;
        self
    }

    /// Set session timeout
    pub fn with_session_timeout(mut self, duration: Duration) -> Self {
        self.session_timeout = duration;
        self
    }

    /// Register a new user
    pub fn register_user(&mut self, user_info: UserInfo) -> Result<()> {
        if self.users.contains_key(&user_info.user_id) {
            return Err(Error::InvalidInput(format!(
                "User '{}' already exists",
                user_info.user_id
            )));
        }

        let user_id = user_info.user_id.clone();
        self.users.insert(user_id.clone(), user_info);

        self.log_event(AuthEvent {
            timestamp: SystemTime::now(),
            event_type: AuthEventType::UserRegistration,
            user_id: Some(user_id),
            tenant_id: None,
            auth_method: AuthMethod::Password,
            success: true,
            ip_address: None,
            user_agent: None,
            error_message: None,
        });

        Ok(())
    }

    /// Get user info
    pub fn get_user(&self, user_id: &str) -> Option<&UserInfo> {
        self.users.get(user_id)
    }

    /// Update user info
    pub fn update_user(&mut self, user_info: UserInfo) -> Result<()> {
        if !self.users.contains_key(&user_info.user_id) {
            return Err(Error::InvalidInput(format!(
                "User '{}' not found",
                user_info.user_id
            )));
        }

        self.users.insert(user_info.user_id.clone(), user_info);
        Ok(())
    }

    /// Deactivate a user
    pub fn deactivate_user(&mut self, user_id: &str) -> Result<()> {
        let user = self
            .users
            .get_mut(user_id)
            .ok_or_else(|| Error::InvalidInput(format!("User '{}' not found", user_id)))?;

        user.active = false;

        // Invalidate all active sessions for this user
        self.sessions
            .retain(|_, session| session.user_id != user_id);

        Ok(())
    }

    /// Authenticate with password and get JWT token
    pub fn authenticate_password(&mut self, email: &str, password: &str) -> Result<AuthResult> {
        // Find user by email
        let user = self
            .users
            .values()
            .find(|u| u.email == email)
            .ok_or_else(|| Error::InvalidInput("Invalid credentials".to_string()))?;

        if !user.active {
            self.log_event(AuthEvent {
                timestamp: SystemTime::now(),
                event_type: AuthEventType::Login,
                user_id: Some(user.user_id.clone()),
                tenant_id: Some(user.tenant_id.clone()),
                auth_method: AuthMethod::Password,
                success: false,
                ip_address: None,
                user_agent: None,
                error_message: Some("User account is deactivated".to_string()),
            });
            return Err(Error::InvalidOperation(
                "User account is deactivated".to_string(),
            ));
        }

        if !user.verify_password(password) {
            self.log_event(AuthEvent {
                timestamp: SystemTime::now(),
                event_type: AuthEventType::Login,
                user_id: Some(user.user_id.clone()),
                tenant_id: Some(user.tenant_id.clone()),
                auth_method: AuthMethod::Password,
                success: false,
                ip_address: None,
                user_agent: None,
                error_message: Some("Invalid password".to_string()),
            });
            return Err(Error::InvalidInput("Invalid credentials".to_string()));
        }

        // Update last login
        let user_id = user.user_id.clone();
        let tenant_id = user.tenant_id.clone();
        let permissions = user.permissions.clone();

        if let Some(user_mut) = self.users.get_mut(&user_id) {
            user_mut.last_login = Some(SystemTime::now());
        }

        // Create session
        let session =
            Session::new(user_id.clone(), tenant_id.clone()).with_timeout(self.session_timeout);
        let session_id = session.session_id.clone();
        self.sessions.insert(session_id.clone(), session);

        let expires_at = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
            + self.token_expiry.as_secs();

        self.log_event(AuthEvent {
            timestamp: SystemTime::now(),
            event_type: AuthEventType::Login,
            user_id: Some(user_id.clone()),
            tenant_id: Some(tenant_id.clone()),
            auth_method: AuthMethod::Password,
            success: true,
            ip_address: None,
            user_agent: None,
            error_message: None,
        });

        Ok(AuthResult {
            user_id,
            tenant_id,
            permissions,
            expires_at,
            session_id: Some(session_id),
            metadata: HashMap::new(),
        })
    }

    /// Generate JWT token for authenticated user
    pub fn generate_token(&self, user_id: &str) -> Result<String> {
        let user = self
            .users
            .get(user_id)
            .ok_or_else(|| Error::InvalidInput(format!("User '{}' not found", user_id)))?;

        if !user.active {
            return Err(Error::InvalidOperation(
                "User account is deactivated".to_string(),
            ));
        }

        let claims = TokenClaims {
            sub: user_id.to_string(),
            tenant_id: user.tenant_id.clone(),
            roles: user.roles.clone(),
            permissions: user
                .permissions
                .iter()
                .map(|p| format!("{:?}", p))
                .collect(),
            iat: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
            exp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs()
                + self.token_expiry.as_secs(),
            iss: self.jwt_config.issuer.clone(),
            aud: self.jwt_config.audience.clone(),
            jti: generate_token_id(),
        };

        encode_jwt(&claims, &self.jwt_config)
    }

    /// Generate refresh token
    pub fn generate_refresh_token(&mut self, user_id: &str) -> Result<String> {
        let user = self
            .users
            .get(user_id)
            .ok_or_else(|| Error::InvalidInput(format!("User '{}' not found", user_id)))?;

        if !user.active {
            return Err(Error::InvalidOperation(
                "User account is deactivated".to_string(),
            ));
        }

        let token_id = generate_token_id();
        let refresh_token = RefreshToken {
            token_id: token_id.clone(),
            user_id: user_id.to_string(),
            tenant_id: user.tenant_id.clone(),
            created_at: SystemTime::now(),
            expires_at: SystemTime::now() + self.refresh_token_expiry,
            revoked: false,
        };

        self.refresh_tokens.insert(token_id.clone(), refresh_token);

        Ok(token_id)
    }

    /// Refresh access token using refresh token
    pub fn refresh_access_token(&mut self, refresh_token_id: &str) -> Result<String> {
        let refresh_token = self
            .refresh_tokens
            .get(refresh_token_id)
            .ok_or_else(|| Error::InvalidInput("Invalid refresh token".to_string()))?;

        if refresh_token.revoked {
            return Err(Error::InvalidOperation(
                "Refresh token has been revoked".to_string(),
            ));
        }

        if refresh_token.expires_at < SystemTime::now() {
            return Err(Error::InvalidOperation(
                "Refresh token has expired".to_string(),
            ));
        }

        let user_id = refresh_token.user_id.clone();

        self.log_event(AuthEvent {
            timestamp: SystemTime::now(),
            event_type: AuthEventType::TokenRefresh,
            user_id: Some(user_id.clone()),
            tenant_id: Some(refresh_token.tenant_id.clone()),
            auth_method: AuthMethod::Jwt,
            success: true,
            ip_address: None,
            user_agent: None,
            error_message: None,
        });

        self.generate_token(&user_id)
    }

    /// Validate JWT token
    pub fn validate_token(&mut self, token: &str) -> Result<AuthResult> {
        let claims = decode_jwt(token, &self.jwt_config)?;

        // Check if user still exists and is active, clone needed data
        let (user_permissions, user_active) = {
            let user = self
                .users
                .get(&claims.sub)
                .ok_or_else(|| Error::InvalidInput("User not found".to_string()))?;
            (user.permissions.clone(), user.active)
        };

        if !user_active {
            return Err(Error::InvalidOperation(
                "User account is deactivated".to_string(),
            ));
        }

        self.log_event(AuthEvent {
            timestamp: SystemTime::now(),
            event_type: AuthEventType::TokenValidation,
            user_id: Some(claims.sub.clone()),
            tenant_id: Some(claims.tenant_id.clone()),
            auth_method: AuthMethod::Jwt,
            success: true,
            ip_address: None,
            user_agent: None,
            error_message: None,
        });

        Ok(AuthResult {
            user_id: claims.sub,
            tenant_id: claims.tenant_id,
            permissions: user_permissions,
            expires_at: claims.exp,
            session_id: None,
            metadata: HashMap::new(),
        })
    }

    /// Authenticate with API key
    pub fn authenticate_api_key(&mut self, key: &str) -> Result<AuthResult> {
        // Clone all needed data from api_key_info first
        let (key_active, key_expires_at, key_user_id, key_tenant_id, key_permissions) = {
            let api_key_info = self
                .api_keys
                .get(key)
                .ok_or_else(|| Error::InvalidInput("Invalid API key".to_string()))?;
            (
                api_key_info.active,
                api_key_info.expires_at,
                api_key_info.user_id.clone(),
                api_key_info.tenant_id.clone(),
                api_key_info.permissions.clone(),
            )
        };

        if !key_active {
            return Err(Error::InvalidOperation(
                "API key is deactivated".to_string(),
            ));
        }

        if let Some(expires_at) = key_expires_at {
            if expires_at < SystemTime::now() {
                return Err(Error::InvalidOperation("API key has expired".to_string()));
            }
        }

        // Check user is active
        let user_active = {
            let user = self
                .users
                .get(&key_user_id)
                .ok_or_else(|| Error::InvalidInput("User not found".to_string()))?;
            user.active
        };

        if !user_active {
            return Err(Error::InvalidOperation(
                "User account is deactivated".to_string(),
            ));
        }

        // Update usage count
        if let Some(key_info) = self.api_keys.get_mut(key) {
            key_info.usage_count += 1;
            key_info.last_used = Some(SystemTime::now());
        }

        self.log_event(AuthEvent {
            timestamp: SystemTime::now(),
            event_type: AuthEventType::ApiKeyUsage,
            user_id: Some(key_user_id.clone()),
            tenant_id: Some(key_tenant_id.clone()),
            auth_method: AuthMethod::ApiKey,
            success: true,
            ip_address: None,
            user_agent: None,
            error_message: None,
        });

        let expires_at = key_expires_at
            .map(|t| t.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs())
            .unwrap_or(u64::MAX);

        Ok(AuthResult {
            user_id: key_user_id,
            tenant_id: key_tenant_id,
            permissions: key_permissions,
            expires_at,
            session_id: None,
            metadata: HashMap::new(),
        })
    }

    /// Create API key for a user
    pub fn create_api_key(
        &mut self,
        user_id: &str,
        name: &str,
        permissions: Option<Vec<Permission>>,
    ) -> Result<String> {
        // Clone user data before any mutations
        let (user_tenant_id, user_permissions, user_active) = {
            let user = self
                .users
                .get(user_id)
                .ok_or_else(|| Error::InvalidInput(format!("User '{}' not found", user_id)))?;
            (
                user.tenant_id.clone(),
                user.permissions.clone(),
                user.active,
            )
        };

        if !user_active {
            return Err(Error::InvalidOperation(
                "User account is deactivated".to_string(),
            ));
        }

        let api_key = generate_api_key();
        let api_key_info = ApiKeyInfo {
            key_id: generate_token_id(),
            name: name.to_string(),
            key_hash: hash_api_key(&api_key),
            user_id: user_id.to_string(),
            tenant_id: user_tenant_id,
            permissions: permissions.unwrap_or(user_permissions),
            created_at: SystemTime::now(),
            expires_at: None,
            last_used: None,
            usage_count: 0,
            active: true,
            rate_limit: None,
            rate_limit_counter: 0,
            rate_limit_window_start: None,
            ip_whitelist: Vec::new(),
            metadata: HashMap::new(),
        };

        // Store API key info (using hash as lookup key for security)
        self.api_keys.insert(api_key.clone(), api_key_info);

        // Add key reference to user
        if let Some(user_mut) = self.users.get_mut(user_id) {
            user_mut.api_keys.push(api_key.clone());
        }

        Ok(api_key)
    }

    /// Revoke an API key
    pub fn revoke_api_key(&mut self, key: &str) -> Result<()> {
        let api_key_info = self
            .api_keys
            .get_mut(key)
            .ok_or_else(|| Error::InvalidInput("API key not found".to_string()))?;

        api_key_info.active = false;

        // Remove from user's key list
        if let Some(user) = self.users.get_mut(&api_key_info.user_id) {
            user.api_keys.retain(|k| k != key);
        }

        Ok(())
    }

    /// Revoke refresh token
    pub fn revoke_refresh_token(&mut self, token_id: &str) -> Result<()> {
        let refresh_token = self
            .refresh_tokens
            .get_mut(token_id)
            .ok_or_else(|| Error::InvalidInput("Refresh token not found".to_string()))?;

        refresh_token.revoked = true;
        Ok(())
    }

    /// Revoke all refresh tokens for a user
    pub fn revoke_all_refresh_tokens(&mut self, user_id: &str) {
        for token in self.refresh_tokens.values_mut() {
            if token.user_id == user_id {
                token.revoked = true;
            }
        }
    }

    /// Get session by ID
    pub fn get_session(&self, session_id: &str) -> Option<&Session> {
        self.sessions.get(session_id)
    }

    /// Validate and refresh session
    pub fn validate_session(&mut self, session_id: &str) -> Result<&Session> {
        // Check if session exists and if expired
        let (is_expired, user_id, tenant_id) = {
            let session = self
                .sessions
                .get(session_id)
                .ok_or_else(|| Error::InvalidInput("Session not found".to_string()))?;
            (
                session.is_expired(),
                session.user_id.clone(),
                session.tenant_id.clone(),
            )
        };

        if is_expired {
            self.log_event(AuthEvent {
                timestamp: SystemTime::now(),
                event_type: AuthEventType::SessionExpired,
                user_id: Some(user_id),
                tenant_id: Some(tenant_id),
                auth_method: AuthMethod::Password,
                success: false,
                ip_address: None,
                user_agent: None,
                error_message: Some("Session expired".to_string()),
            });
            return Err(Error::InvalidOperation("Session has expired".to_string()));
        }

        // Refresh the session
        if let Some(session) = self.sessions.get_mut(session_id) {
            session.refresh();
        }

        self.sessions
            .get(session_id)
            .ok_or_else(|| Error::InvalidInput("Session not found".to_string()))
    }

    /// Logout and invalidate session
    pub fn logout(&mut self, session_id: &str) -> Result<()> {
        let session = self
            .sessions
            .remove(session_id)
            .ok_or_else(|| Error::InvalidInput("Session not found".to_string()))?;

        self.log_event(AuthEvent {
            timestamp: SystemTime::now(),
            event_type: AuthEventType::Logout,
            user_id: Some(session.user_id),
            tenant_id: Some(session.tenant_id),
            auth_method: AuthMethod::Password,
            success: true,
            ip_address: None,
            user_agent: None,
            error_message: None,
        });

        Ok(())
    }

    /// Clean up expired sessions and tokens
    pub fn cleanup_expired(&mut self) {
        // Remove expired sessions
        self.sessions.retain(|_, session| !session.is_expired());

        // Remove expired refresh tokens
        let now = SystemTime::now();
        self.refresh_tokens
            .retain(|_, token| token.expires_at > now && !token.revoked);

        // Remove expired API keys
        self.api_keys
            .retain(|_, key| key.active && key.expires_at.map(|t| t > now).unwrap_or(true));
    }

    /// Get authentication events for a user
    pub fn get_user_events(&self, user_id: &str) -> Vec<&AuthEvent> {
        self.auth_events
            .iter()
            .filter(|e| e.user_id.as_ref().map(|id| id == user_id).unwrap_or(false))
            .collect()
    }

    /// Get all authentication events
    pub fn get_all_events(&self) -> &[AuthEvent] {
        &self.auth_events
    }

    /// Change user password
    pub fn change_password(
        &mut self,
        user_id: &str,
        old_password: &str,
        new_password: &str,
    ) -> Result<()> {
        let user = self
            .users
            .get(user_id)
            .ok_or_else(|| Error::InvalidInput(format!("User '{}' not found", user_id)))?;

        if !user.verify_password(old_password) {
            self.log_event(AuthEvent {
                timestamp: SystemTime::now(),
                event_type: AuthEventType::PasswordChange,
                user_id: Some(user_id.to_string()),
                tenant_id: Some(user.tenant_id.clone()),
                auth_method: AuthMethod::Password,
                success: false,
                ip_address: None,
                user_agent: None,
                error_message: Some("Invalid current password".to_string()),
            });
            return Err(Error::InvalidInput("Invalid current password".to_string()));
        }

        let tenant_id = user.tenant_id.clone();

        // Update password
        if let Some(user_mut) = self.users.get_mut(user_id) {
            user_mut.password_hash = Some(hash_password(new_password));
        }

        // Revoke all existing refresh tokens
        self.revoke_all_refresh_tokens(user_id);

        self.log_event(AuthEvent {
            timestamp: SystemTime::now(),
            event_type: AuthEventType::PasswordChange,
            user_id: Some(user_id.to_string()),
            tenant_id: Some(tenant_id),
            auth_method: AuthMethod::Password,
            success: true,
            ip_address: None,
            user_agent: None,
            error_message: None,
        });

        Ok(())
    }

    /// Log an authentication event
    fn log_event(&mut self, event: AuthEvent) {
        self.auth_events.push(event);

        // Trim events if needed
        if self.auth_events.len() > self.max_events {
            let excess = self.auth_events.len() - self.max_events;
            self.auth_events.drain(0..excess);
        }
    }
}

impl Default for AuthManager {
    fn default() -> Self {
        Self::new(JwtConfig::default())
    }
}

/// Thread-safe authentication manager
pub type SharedAuthManager = Arc<RwLock<AuthManager>>;

/// Create a new shared authentication manager
pub fn create_shared_auth_manager(config: JwtConfig) -> SharedAuthManager {
    Arc::new(RwLock::new(AuthManager::new(config)))
}

/// Refresh token information
#[derive(Debug, Clone)]
pub struct RefreshToken {
    /// Token identifier
    pub token_id: String,
    /// Associated user
    pub user_id: String,
    /// Associated tenant
    pub tenant_id: TenantId,
    /// Creation time
    pub created_at: SystemTime,
    /// Expiration time
    pub expires_at: SystemTime,
    /// Whether the token has been revoked
    pub revoked: bool,
}

// Helper functions

/// Generate a unique token ID
fn generate_token_id() -> String {
    use rand::Rng;
    let mut bytes = [0u8; 32];
    rand::rng().fill_bytes(&mut bytes);
    bytes.iter().map(|b| format!("{:02x}", b)).collect()
}

/// Generate an API key
fn generate_api_key() -> String {
    use rand::Rng;
    let mut bytes = [0u8; 32];
    rand::rng().fill_bytes(&mut bytes);
    format!(
        "pk_{}",
        bytes
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect::<String>()
    )
}

/// Hash password using PBKDF2
fn hash_password(password: &str) -> String {
    use pbkdf2::pbkdf2_hmac;
    use rand::Rng;
    use sha2::Sha256;

    let mut salt = [0u8; 16];
    rand::rng().fill_bytes(&mut salt);

    let mut hash = [0u8; 32];
    pbkdf2_hmac::<Sha256>(password.as_bytes(), &salt, 100_000, &mut hash);

    // Format: iterations$salt_hex$hash_hex
    format!(
        "100000${}${}",
        salt.iter()
            .map(|b| format!("{:02x}", b))
            .collect::<String>(),
        hash.iter()
            .map(|b| format!("{:02x}", b))
            .collect::<String>()
    )
}

/// Verify password against hash
fn verify_password(password: &str, stored_hash: &str) -> bool {
    use pbkdf2::pbkdf2_hmac;
    use sha2::Sha256;

    let parts: Vec<&str> = stored_hash.split('$').collect();
    if parts.len() != 3 {
        return false;
    }

    let iterations: u32 = match parts[0].parse() {
        Ok(i) => i,
        Err(_) => return false,
    };

    let salt: Vec<u8> = match hex_decode(parts[1]) {
        Some(s) => s,
        None => return false,
    };

    let stored_hash_bytes: Vec<u8> = match hex_decode(parts[2]) {
        Some(h) => h,
        None => return false,
    };

    let mut computed_hash = vec![0u8; stored_hash_bytes.len()];
    pbkdf2_hmac::<Sha256>(password.as_bytes(), &salt, iterations, &mut computed_hash);

    // Constant-time comparison
    computed_hash == stored_hash_bytes
}

/// Hash API key for storage
fn hash_api_key(key: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(key.as_bytes());
    let result = hasher.finalize();
    result.iter().map(|b| format!("{:02x}", b)).collect()
}

/// Decode hex string to bytes
fn hex_decode(s: &str) -> Option<Vec<u8>> {
    let mut bytes = Vec::with_capacity(s.len() / 2);
    let mut chars = s.chars();

    while let (Some(a), Some(b)) = (chars.next(), chars.next()) {
        let high = a.to_digit(16)?;
        let low = b.to_digit(16)?;
        bytes.push((high * 16 + low) as u8);
    }

    if chars.next().is_some() {
        // Odd number of characters
        return None;
    }

    Some(bytes)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_user_registration() {
        let mut auth = AuthManager::default();

        let user = UserInfo::new("user1", "user@example.com", "tenant_a")
            .with_password("secret123")
            .with_permission(Permission::Read)
            .with_permission(Permission::Write);

        auth.register_user(user).expect("operation should succeed");

        assert!(auth.get_user("user1").is_some());
    }

    #[test]
    fn test_password_authentication() {
        let mut auth = AuthManager::default();

        let user =
            UserInfo::new("user1", "user@example.com", "tenant_a").with_password("secret123");

        auth.register_user(user).expect("operation should succeed");

        // Valid credentials
        let result = auth.authenticate_password("user@example.com", "secret123");
        assert!(result.is_ok());

        // Invalid password
        let result = auth.authenticate_password("user@example.com", "wrong");
        assert!(result.is_err());

        // Invalid email
        let result = auth.authenticate_password("wrong@example.com", "secret123");
        assert!(result.is_err());
    }

    #[test]
    fn test_token_generation() {
        let auth = AuthManager::default();
        let mut auth = auth;

        let user =
            UserInfo::new("user1", "user@example.com", "tenant_a").with_password("secret123");

        auth.register_user(user).expect("operation should succeed");

        let token = auth
            .generate_token("user1")
            .expect("operation should succeed");
        assert!(!token.is_empty());

        // Validate token
        let result = auth.validate_token(&token);
        assert!(result.is_ok());
    }

    #[test]
    fn test_api_key_authentication() {
        let mut auth = AuthManager::default();

        let user = UserInfo::new("user1", "user@example.com", "tenant_a")
            .with_password("secret123")
            .with_permission(Permission::Read);

        auth.register_user(user).expect("operation should succeed");

        let api_key = auth
            .create_api_key("user1", "test-key", None)
            .expect("operation should succeed");
        assert!(api_key.starts_with("pk_"));

        let result = auth.authenticate_api_key(&api_key);
        assert!(result.is_ok());

        let auth_result = result.expect("operation should succeed");
        assert_eq!(auth_result.user_id, "user1");
        assert_eq!(auth_result.tenant_id, "tenant_a");
    }

    #[test]
    fn test_refresh_token() {
        let mut auth = AuthManager::default();

        let user =
            UserInfo::new("user1", "user@example.com", "tenant_a").with_password("secret123");

        auth.register_user(user).expect("operation should succeed");

        let refresh_token = auth
            .generate_refresh_token("user1")
            .expect("operation should succeed");
        let new_token = auth.refresh_access_token(&refresh_token);
        assert!(new_token.is_ok());

        // Revoke and try again
        auth.revoke_refresh_token(&refresh_token)
            .expect("operation should succeed");
        let result = auth.refresh_access_token(&refresh_token);
        assert!(result.is_err());
    }

    #[test]
    fn test_session_management() {
        let mut auth = AuthManager::default();

        let user =
            UserInfo::new("user1", "user@example.com", "tenant_a").with_password("secret123");

        auth.register_user(user).expect("operation should succeed");

        let result = auth
            .authenticate_password("user@example.com", "secret123")
            .expect("operation should succeed");
        let session_id = result.session_id.expect("operation should succeed");

        // Validate session
        assert!(auth.validate_session(&session_id).is_ok());

        // Logout
        auth.logout(&session_id).expect("operation should succeed");

        // Session should be invalid now
        assert!(auth.validate_session(&session_id).is_err());
    }

    #[test]
    fn test_password_change() {
        let mut auth = AuthManager::default();

        let user = UserInfo::new("user1", "user@example.com", "tenant_a").with_password("oldpass");

        auth.register_user(user).expect("operation should succeed");

        // Change password
        auth.change_password("user1", "oldpass", "newpass")
            .expect("operation should succeed");

        // Old password should fail
        let result = auth.authenticate_password("user@example.com", "oldpass");
        assert!(result.is_err());

        // New password should work
        let result = auth.authenticate_password("user@example.com", "newpass");
        assert!(result.is_ok());
    }

    #[test]
    fn test_user_deactivation() {
        let mut auth = AuthManager::default();

        let user =
            UserInfo::new("user1", "user@example.com", "tenant_a").with_password("secret123");

        auth.register_user(user).expect("operation should succeed");

        // Login should work
        assert!(auth
            .authenticate_password("user@example.com", "secret123")
            .is_ok());

        // Deactivate user
        auth.deactivate_user("user1")
            .expect("operation should succeed");

        // Login should fail
        let result = auth.authenticate_password("user@example.com", "secret123");
        assert!(result.is_err());
    }

    #[test]
    fn test_password_hashing() {
        let password = "test_password_123";
        let hash = hash_password(password);

        // Hash should contain iterations, salt, and hash
        let parts: Vec<&str> = hash.split('$').collect();
        assert_eq!(parts.len(), 3);

        // Verify should work
        assert!(verify_password(password, &hash));

        // Wrong password should fail
        assert!(!verify_password("wrong_password", &hash));
    }
}