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
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
//! Firebase Authentication
//!
//! # C++ Reference
//! - `auth/src/auth.cc:65` - GetAuth implementation with global map
//! - `auth/src/include/firebase/auth.h:128` - Auth class
use crate::auth::types::{User, AuthResult};
use crate::error::{FirebaseError, AuthError};
use crate::app::App;
use async_stream::stream;
use futures::Stream;
use once_cell::sync::Lazy;
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{RwLock, broadcast};
/// Global map of App names to Auth instances
///
/// C++ equivalent: `std::map<App*, Auth*> g_auths` at auth/src/auth.cc:62
static AUTH_INSTANCES: Lazy<RwLock<HashMap<String, Auth>>> =
Lazy::new(|| RwLock::new(HashMap::new()));
/// Firebase Authentication instance
///
/// # C++ Reference
/// - `auth/src/include/firebase/auth.h:128`
///
/// Each App has at most one Auth instance (singleton pattern).
/// Use `Auth::get_auth(app)` to obtain or create an instance.
#[derive(Clone)]
pub struct Auth {
pub(crate) inner: Arc<AuthInner>,
}
pub(crate) struct AuthInner {
pub(crate) api_key: String,
pub(crate) current_user: RwLock<Option<Arc<User>>>,
pub(crate) http_client: reqwest::Client,
pub(crate) state_tx: broadcast::Sender<Option<Arc<User>>>,
app: App,
}
impl Auth {
/// Get or create Auth instance for the given App
///
/// # C++ Reference
/// - `auth/src/auth.cc:65` - Auth::GetAuth(app)
///
/// Returns existing Auth if one exists for this App, otherwise creates new.
/// Thread-safe singleton pattern following C++ implementation.
///
/// # Example
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use firebase_rust_sdk::{App, AppOptions, Auth};
///
/// let app = App::create(AppOptions {
/// api_key: "YOUR_API_KEY".to_string(),
/// project_id: "your-project".to_string(),
/// app_name: None,
/// }).await?;
/// let auth = Auth::get_auth(&app).await?;
/// # Ok(())
/// # }
/// ```
pub async fn get_auth(app: &App) -> Result<Self, FirebaseError> {
let app_name = app.name().to_string();
let mut instances = AUTH_INSTANCES.write().await;
// Check if instance already exists
if let Some(auth) = instances.get(&app_name) {
return Ok(auth.clone());
}
// Create new Auth instance
let http_client = match reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
{
Err(e) => return Err(FirebaseError::Internal(format!("Failed to create HTTP client: {}", e))),
Ok(client) => client,
};
// Create broadcast channel for auth state changes (capacity: 16)
let (state_tx, _) = broadcast::channel(16);
let auth = Auth {
inner: Arc::new(AuthInner {
api_key: app.options().api_key.clone(),
current_user: RwLock::new(None),
http_client,
state_tx,
app: app.clone(),
}),
};
// Register this Auth with the App
app.register_auth(Arc::downgrade(&auth.inner)).await;
instances.insert(app_name, auth.clone());
Ok(auth)
}
/// Get the current signed-in user
///
/// # C++ Reference
/// - `auth/src/include/firebase/auth.h:148` - current_user()
///
/// Returns None if no user is currently signed in.
pub async fn current_user(&self) -> Option<Arc<User>> {
self.inner.current_user.read().await.clone()
}
/// Sign out the current user
///
/// # C++ Reference
/// - `auth/src/include/firebase/auth.h:357` - SignOut()
///
/// Always succeeds and clears the current user.
pub async fn sign_out(&self) -> Result<(), FirebaseError> {
self.set_current_user(None).await;
Ok(())
}
/// Get the API key for this Auth instance
pub fn api_key(&self) -> &str {
&self.inner.api_key
}
/// Get the App this Auth instance is connected to
///
/// # C++ Reference
/// - `auth/src/include/firebase/auth.h:674` - app()
pub fn app(&self) -> &App {
&self.inner.app
}
/// Internal: Get HTTP client
#[allow(dead_code)]
pub(crate) fn http_client(&self) -> &reqwest::Client {
&self.inner.http_client
}
/// Internal: Set current user
pub(crate) async fn set_current_user(&self, user: Option<Arc<User>>) {
let mut current = self.inner.current_user.write().await;
*current = user.clone();
// Broadcast state change (ignore error if no listeners)
let _ = self.inner.state_tx.send(user);
}
/// Get the current language code
///
/// # C++ Reference
/// - `auth/src/include/firebase/auth.h:155` - language_code()
///
/// Returns the language code for auth operations (e.g., "en", "ja").
/// Returns empty string if using app default language.
pub fn language_code(&self) -> &str {
// TODO: Implement language code storage
todo!("Language code support not yet implemented")
}
/// Set the language code for auth operations
///
/// # C++ Reference
/// - `auth/src/include/firebase/auth.h:161` - set_language_code()
///
/// Sets the language code for internationalized auth emails and UI.
/// Should be a BCP 47 language code (e.g., "en", "ja", "en-US").
pub fn set_language_code(&self, _language_code: &str) {
// TODO: Implement language code storage
todo!("Language code support not yet implemented")
}
/// Use the app's default language
///
/// # C++ Reference
/// - `auth/src/include/firebase/auth.h:167` - UseAppLanguage()
///
/// Sets auth to use the device's locale language.
pub fn use_app_language(&self) {
// TODO: Implement language code from system locale
todo!("App language detection not yet implemented")
}
/// Use the Firebase Auth emulator
///
/// # C++ Reference
/// - Desktop implementation for emulator support
///
/// Configures Auth to connect to the local emulator instead of production.
/// Must be called before any auth operations.
pub fn use_emulator(&self, _host: &str, _port: u16) {
// TODO: Implement emulator URL configuration
todo!("Emulator support not yet implemented")
}
/// Subscribe to authentication state changes
///
/// # C++ Reference
/// - `auth/src/include/firebase/auth.h:610` - AuthStateListener
///
/// Returns a stream that yields the current user whenever:
/// - A user signs in
/// - A user signs out
/// - The current user changes
///
/// The stream immediately yields the current user state upon subscription.
///
/// # Example
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use firebase_rust_sdk::Auth;
/// use futures::StreamExt;
///
/// let auth = Auth::get_auth("YOUR_API_KEY").await?;
/// let mut stream = auth.auth_state_changes().await;
///
/// while let Some(user) = stream.next().await {
/// match user {
/// Some(u) => println!("User signed in: {}", u.uid),
/// None => println!("User signed out"),
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn auth_state_changes(&self) -> std::pin::Pin<Box<dyn Stream<Item = Option<Arc<User>>> + Send>> {
// Get current user immediately
let initial_user = self.current_user().await;
// Subscribe to state changes
let mut rx = self.inner.state_tx.subscribe();
Box::pin(stream! {
// Yield initial state first
yield initial_user;
// Then yield all future state changes
loop {
let user = match rx.recv().await {
Err(_) => break, // Channel closed
Ok(u) => u,
};
yield user;
}
})
}
/// Sign in with email and password
///
/// # C++ Reference
/// - `auth/src/desktop/auth_desktop.cc:405` - SignInWithEmailAndPassword
///
/// # Example
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use firebase_rust_sdk::Auth;
///
/// let auth = Auth::get_auth("YOUR_API_KEY").await?;
/// let result = auth.sign_in_with_email_and_password("user@example.com", "password").await?;
/// println!("Signed in: {}", result.user.uid);
/// # Ok(())
/// # }
/// ```
pub async fn sign_in_with_email_and_password(
&self,
email: impl AsRef<str>,
password: impl AsRef<str>,
) -> Result<AuthResult, FirebaseError> {
let email = email.as_ref();
let password = password.as_ref();
// Validate email (error case first)
if email.is_empty() {
return Err(AuthError::InvalidEmail.into());
}
// Validate password (error case first)
if password.is_empty() {
return Err(AuthError::InvalidPassword.into());
}
// Call Firebase Auth REST API
let url = format!(
"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={}",
self.inner.api_key
);
let response = self.inner.http_client
.post(&url)
.json(&serde_json::json!({
"email": email,
"password": password,
"returnSecureToken": true
}))
.send()
.await?;
// Handle error responses first
if !response.status().is_success() {
let error_body: serde_json::Value = response.json().await?;
let error_message = error_body["error"]["message"]
.as_str()
.unwrap_or("UNKNOWN_ERROR");
return Err(AuthError::from_error_code(error_message).into());
}
// Parse successful response
let user_data: SignInResponse = response.json().await?;
let user = Arc::new(user_data.into_user(self.inner.api_key.clone()));
// Update current user
self.set_current_user(Some(Arc::clone(&user))).await;
Ok(AuthResult {
user,
additional_user_info: Some(crate::auth::types::AdditionalUserInfo {
provider_id: "password".to_string(),
is_new_user: false,
profile: None,
}),
})
}
/// Create new user with email and password
///
/// # C++ Reference
/// - `auth/src/desktop/auth_desktop.cc:422` - CreateUserWithEmailAndPassword
///
/// # Example
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use firebase_rust_sdk::Auth;
///
/// let auth = Auth::get_auth("YOUR_API_KEY").await?;
/// let result = auth.create_user_with_email_and_password("newuser@example.com", "password123").await?;
/// println!("Created user: {}", result.user.uid);
/// # Ok(())
/// # }
/// ```
pub async fn create_user_with_email_and_password(
&self,
email: impl AsRef<str>,
password: impl AsRef<str>,
) -> Result<AuthResult, FirebaseError> {
let email = email.as_ref();
let password = password.as_ref();
// Validate email (error case first)
if email.is_empty() {
return Err(AuthError::InvalidEmail.into());
}
// Validate password (error case first)
if password.is_empty() {
return Err(AuthError::InvalidPassword.into());
}
// Call Firebase Auth REST API
let url = format!(
"https://identitytoolkit.googleapis.com/v1/accounts:signUp?key={}",
self.inner.api_key
);
let response = self.inner.http_client
.post(&url)
.json(&serde_json::json!({
"email": email,
"password": password,
"returnSecureToken": true
}))
.send()
.await?;
// Handle error responses first
if !response.status().is_success() {
let error_body: serde_json::Value = response.json().await?;
let error_message = error_body["error"]["message"]
.as_str()
.unwrap_or("UNKNOWN_ERROR");
return Err(AuthError::from_error_code(error_message).into());
}
// Parse successful response
let user_data: SignInResponse = response.json().await?;
let user = Arc::new(user_data.into_user(self.inner.api_key.clone()));
// Update current user
self.set_current_user(Some(Arc::clone(&user))).await;
Ok(AuthResult {
user,
additional_user_info: Some(crate::auth::types::AdditionalUserInfo {
provider_id: "password".to_string(),
is_new_user: true,
profile: None,
}),
})
}
/// Sign in anonymously
///
/// # C++ Reference
/// - `auth/src/desktop/auth_desktop.cc:439` - SignInAnonymously
///
/// Creates an anonymous user account. Anonymous accounts are temporary and can be
/// linked to permanent accounts later.
///
/// # Example
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use firebase_rust_sdk::Auth;
///
/// let auth = Auth::get_auth("YOUR_API_KEY").await?;
/// let result = auth.sign_in_anonymously().await?;
/// println!("Anonymous user: {}", result.user.uid);
/// # Ok(())
/// # }
/// ```
pub async fn sign_in_anonymously(&self) -> Result<AuthResult, FirebaseError> {
// Call Firebase Auth REST API - signUp with no email/password creates anonymous user
let url = format!(
"https://identitytoolkit.googleapis.com/v1/accounts:signUp?key={}",
self.inner.api_key
);
let response = match self.inner.http_client
.post(&url)
.json(&serde_json::json!({
"returnSecureToken": true
}))
.send()
.await {
Err(e) => return Err(FirebaseError::Internal(format!("Request failed: {}", e))),
Ok(resp) => resp,
};
// Handle error responses first
if !response.status().is_success() {
let error_body = match response.json::<serde_json::Value>().await {
Err(e) => return Err(FirebaseError::Internal(format!("Parse error: {}", e))),
Ok(body) => body,
};
let error_message = error_body["error"]["message"]
.as_str()
.unwrap_or("UNKNOWN_ERROR");
return Err(AuthError::from_error_code(error_message).into());
}
// Parse successful response
let user_data: SignInResponse = response.json().await?;
let user = Arc::new(user_data.into_user(self.inner.api_key.clone()));
// Update current user
self.set_current_user(Some(Arc::clone(&user))).await;
Ok(AuthResult {
user,
additional_user_info: Some(crate::auth::types::AdditionalUserInfo {
provider_id: "anonymous".to_string(),
is_new_user: true,
profile: None,
}),
})
}
/// Sign in with OAuth credential
///
/// # C++ Reference
/// - `auth/src/desktop/auth_desktop.cc:439` - SignInAndRetrieveDataWithCredential
/// - `auth/src/desktop/credential_impl.cc` - Credential implementation
///
/// Signs in using a credential from an OAuth provider (Google, Facebook, GitHub, etc.)
///
/// # Arguments
/// * `credential` - OAuth credential from provider
///
/// # Example
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use firebase_rust_sdk::Auth;
/// use firebase_rust_sdk::auth::types::Credential;
///
/// let auth = Auth::get_auth("YOUR_API_KEY").await?;
///
/// // Google Sign-In
/// let credential = Credential::Google {
/// id_token: Some("google_id_token".to_string()),
/// access_token: Some("google_access_token".to_string()),
/// };
/// let result = auth.sign_in_with_credential(credential).await?;
/// println!("Signed in: {}", result.user.uid);
/// # Ok(())
/// # }
/// ```
pub async fn sign_in_with_credential(&self, credential: crate::auth::types::Credential) -> Result<AuthResult, FirebaseError> {
use crate::auth::types::Credential;
use crate::error::AuthError;
// Build request based on credential type
let url = format!(
"https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key={}",
self.inner.api_key
);
let (provider_id, _token, id_token, access_token): (String, Option<String>, Option<String>, Option<String>) = match credential {
// Error-first: unsupported credential types
Credential::EmailPassword { .. } => {
return Err(FirebaseError::Auth(
AuthError::InvalidCredential("Use sign_in_with_email_and_password() for email/password auth".to_string())
));
}
Credential::Anonymous => {
return Err(FirebaseError::Auth(
AuthError::InvalidCredential("Use sign_in_anonymously() for anonymous auth".to_string())
));
}
Credential::CustomToken { token } => {
return Err(FirebaseError::Auth(
AuthError::InvalidCredential(format!(
"Use sign_in_with_custom_token() for custom token auth. Token: {}",
if token.len() > 20 { &token[..20] } else { &token }
))
));
}
// OAuth providers
Credential::Google { id_token, access_token } => {
// Error-first: validate at least one token provided
if id_token.is_none() && access_token.is_none() {
return Err(FirebaseError::Auth(
AuthError::InvalidCredential("Google credential requires id_token or access_token".to_string())
));
}
("google.com".to_string(), access_token.clone(), id_token, access_token)
}
Credential::Facebook { access_token } => {
("facebook.com".to_string(), Some(access_token.clone()), None, Some(access_token))
}
Credential::GitHub { token } => {
("github.com".to_string(), Some(token.clone()), None, Some(token))
}
Credential::OAuth { provider_id, id_token, access_token, .. } => {
// Error-first: validate at least one token provided
if id_token.is_none() && access_token.is_none() {
return Err(FirebaseError::Auth(
AuthError::InvalidCredential("OAuth credential requires id_token or access_token".to_string())
));
}
(provider_id.clone(), access_token.clone(), id_token, access_token)
}
};
let mut post_body = format!("providerId={}", provider_id);
if let Some(id_token_val) = id_token {
post_body.push_str(&format!("&id_token={}", id_token_val));
}
if let Some(access_token_val) = access_token {
post_body.push_str(&format!("&access_token={}", access_token_val));
}
let response = self.inner.http_client
.post(&url)
.json(&serde_json::json!({
"postBody": post_body,
"requestUri": "http://localhost",
"returnSecureToken": true,
"returnIdpCredential": true
}))
.send()
.await?;
// Error-first: handle error responses
if !response.status().is_success() {
let error_body: serde_json::Value = response.json().await?;
let error_message = error_body["error"]["message"]
.as_str()
.unwrap_or("UNKNOWN_ERROR");
return Err(AuthError::from_error_code(error_message).into());
}
// Parse successful response
let user_data: SignInResponse = response.json().await?;
let user = Arc::new(user_data.into_user(self.inner.api_key.clone()));
// Update current user
self.set_current_user(Some(Arc::clone(&user))).await;
Ok(AuthResult {
user,
additional_user_info: Some(crate::auth::types::AdditionalUserInfo {
provider_id: provider_id.to_string(),
is_new_user: false, // Would need to check providerUserInfo to determine
profile: None,
}),
})
}
/// Sign in with custom token
///
/// # C++ Reference
/// - `auth/src/desktop/auth_desktop.cc:338` - SignInWithCustomToken
/// - `auth/src/desktop/rpcs/verify_custom_token_request.cc:27` - VerifyCustomTokenRequest
///
/// Signs in using a custom token generated by your own server. This is useful for
/// integrating with existing authentication systems or for server-side authentication.
///
/// # Arguments
/// * `token` - The custom token string generated by your server
///
/// # Example
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use firebase_rust_sdk::Auth;
///
/// let auth = Auth::get_auth("YOUR_API_KEY").await?;
/// let result = auth.sign_in_with_custom_token("custom_token_from_server").await?;
/// println!("Signed in: {}", result.user.uid);
/// # Ok(())
/// # }
/// ```
pub async fn sign_in_with_custom_token(&self, token: &str) -> Result<AuthResult, FirebaseError> {
// Error-first: validate token
if token.is_empty() {
return Err(AuthError::InvalidCredential("Custom token cannot be empty".to_string()).into());
}
let url = format!(
"https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key={}",
self.inner.api_key
);
let response = self
.inner
.http_client
.post(&url)
.json(&serde_json::json!({
"token": token,
"returnSecureToken": true
}))
.send()
.await?;
// Error-first: handle error responses
if !response.status().is_success() {
let error_body: serde_json::Value = response.json().await?;
let error_message = error_body["error"]["message"]
.as_str()
.unwrap_or("UNKNOWN_ERROR");
return Err(AuthError::from_error_code(error_message).into());
}
// Parse successful response
let user_data: SignInResponse = response.json().await?;
let user = Arc::new(user_data.into_user(self.inner.api_key.clone()));
// Update current user
self.set_current_user(Some(Arc::clone(&user))).await;
Ok(AuthResult {
user,
additional_user_info: Some(crate::auth::types::AdditionalUserInfo {
provider_id: "custom".to_string(),
is_new_user: false,
profile: None,
}),
})
}
/// Send password reset email
///
/// # C++ Reference
/// - `auth/src/desktop/auth_desktop.cc:474` - SendPasswordResetEmail
/// - `auth/src/desktop/rpcs/get_oob_confirmation_code_request.cc:70` - CreateSendPasswordResetEmailRequest
///
/// Sends a password reset email to the given email address. If the email is not
/// registered, the operation still succeeds to prevent email enumeration.
///
/// # Arguments
/// * `email` - The email address to send the password reset to
///
/// # Example
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use firebase_rust_sdk::Auth;
///
/// let auth = Auth::get_auth("YOUR_API_KEY").await?;
/// auth.send_password_reset_email("user@example.com").await?;
/// println!("Password reset email sent");
/// # Ok(())
/// # }
/// ```
pub async fn send_password_reset_email(&self, email: impl AsRef<str>) -> Result<(), FirebaseError> {
let email = email.as_ref();
// Validate email (error case first)
if email.is_empty() {
return Err(AuthError::InvalidEmail.into());
}
// Call Firebase Auth REST API - getOobConfirmationCode with PASSWORD_RESET
let url = format!(
"https://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key={}",
self.inner.api_key
);
let response = self.inner.http_client
.post(&url)
.json(&serde_json::json!({
"requestType": "PASSWORD_RESET",
"email": email
}))
.send()
.await?;
// Handle error responses first
if !response.status().is_success() {
let error_body: serde_json::Value = response.json().await?;
let error_message = error_body["error"]["message"]
.as_str()
.unwrap_or("UNKNOWN_ERROR");
return Err(AuthError::from_error_code(error_message).into());
}
// Success - password reset email sent
Ok(())
}
/// Fetch sign-in methods for an email address
///
/// # C++ Reference
/// - `auth/src/desktop/auth_desktop.cc:462` - FetchProvidersForEmail
///
/// Returns list of provider IDs (e.g., "password", "google.com") that can be used
/// to sign in with the given email address.
///
/// # Example
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use firebase_rust_sdk::Auth;
///
/// let auth = Auth::get_auth("YOUR_API_KEY").await?;
/// let providers = auth.fetch_providers_for_email("user@example.com").await?;
/// println!("Available providers: {:?}", providers);
/// # Ok(())
/// # }
/// ```
pub async fn fetch_providers_for_email(&self, email: impl AsRef<str>) -> Result<Vec<String>, FirebaseError> {
let email = email.as_ref();
// Validate email (error case first)
if email.is_empty() {
return Err(AuthError::InvalidEmail.into());
}
// Call Firebase Auth REST API - createAuthUri
let url = format!(
"https://identitytoolkit.googleapis.com/v1/accounts:createAuthUri?key={}",
self.inner.api_key
);
let response = match self.inner.http_client
.post(&url)
.json(&serde_json::json!({
"identifier": email,
"continueUri": "http://localhost" // Required but not used for fetching providers
}))
.send()
.await
{
Err(err) => return Err(FirebaseError::Internal(format!("Request failed: {}", err))),
Ok(resp) => resp,
};
// Handle error responses first
if !response.status().is_success() {
let error_body = match response.json::<serde_json::Value>().await {
Err(err) => return Err(FirebaseError::Internal(format!("Failed to parse error response: {}", err))),
Ok(body) => body,
};
let error_message = error_body["error"]["message"]
.as_str()
.unwrap_or("UNKNOWN_ERROR");
return Err(AuthError::from_error_code(error_message).into());
}
// Parse successful response
let data = match response.json::<serde_json::Value>().await {
Err(err) => return Err(FirebaseError::Internal(format!("Failed to parse response: {}", err))),
Ok(d) => d,
};
// Extract provider IDs (allProviders field)
let providers = data["allProviders"]
.as_array()
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
Ok(providers)
}
}
/// Firebase Auth REST API response
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SignInResponse {
local_id: String,
email: Option<String>,
display_name: Option<String>,
id_token: String,
refresh_token: String,
expires_in: Option<String>,
#[allow(dead_code)]
registered: Option<bool>,
}
impl SignInResponse {
fn into_user(self, api_key: String) -> User {
// Calculate token expiration (expires_in is in seconds)
let token_expiration = if let Some(expires_in_str) = &self.expires_in {
expires_in_str.parse::<i64>().ok().map(|seconds| {
chrono::Utc::now().timestamp() + seconds
})
} else {
// Default: 1 hour expiration
Some(chrono::Utc::now().timestamp() + 3600)
};
User {
uid: self.local_id,
email: self.email,
display_name: self.display_name,
photo_url: None,
phone_number: None,
email_verified: false,
is_anonymous: false,
metadata: crate::auth::types::UserMetadata {
creation_timestamp: chrono::Utc::now().timestamp_millis(),
last_sign_in_timestamp: chrono::Utc::now().timestamp_millis(),
},
provider_data: vec![],
id_token: Some(self.id_token),
refresh_token: Some(self.refresh_token),
token_expiration,
api_key: Some(api_key),
}
}
}
impl std::fmt::Debug for Auth {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Auth")
.field("api_key", &"<redacted>")
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
// Helper to create test App with unique name to avoid singleton collisions
async fn test_app(api_key: &str, project_id: &str, app_name: &str) -> App {
use crate::app::AppOptions;
App::create(AppOptions {
api_key: api_key.to_string(),
project_id: project_id.to_string(),
app_name: Some(app_name.to_string()),
}).await.unwrap()
}
#[tokio::test]
async fn test_get_auth_creates_instance() {
let app = test_app("test_api_key_1", "project1", "test_app_1").await;
let auth = Auth::get_auth(&app).await.unwrap();
assert_eq!(auth.api_key(), "test_api_key_1");
}
#[tokio::test]
async fn test_get_auth_returns_same_instance() {
let app = test_app("test_api_key_2", "project2", "test_app_2").await;
let auth1 = Auth::get_auth(&app).await.unwrap();
let auth2 = Auth::get_auth(&app).await.unwrap();
// Should return same instance (same Arc pointer)
assert!(Arc::ptr_eq(&auth1.inner, &auth2.inner));
}
#[tokio::test]
async fn test_get_auth_empty_key_error() {
// Empty API key should be caught at App creation, not Auth creation
let result = App::create(crate::app::AppOptions {
api_key: String::new(),
project_id: "test".to_string(),
app_name: Some("empty_key_test".to_string()),
}).await;
assert!(matches!(result, Err(FirebaseError::ApiKeyNotConfigured)));
}
#[tokio::test]
async fn test_current_user_initially_none() {
let auth = Auth::get_auth(&test_app("test_api_key_3", "project3", "test_app_3").await).await.unwrap();
assert!(auth.current_user().await.is_none());
}
#[tokio::test]
async fn test_sign_out_clears_user() {
let auth = Auth::get_auth(&test_app("test_api_key_4", "project4", "test_app_4").await).await.unwrap();
// Set a user manually for testing
use crate::auth::types::UserMetadata;
let user = Arc::new(User {
uid: "test_uid".to_string(),
email: Some("test@example.com".to_string()),
display_name: None,
photo_url: None,
phone_number: None,
email_verified: false,
is_anonymous: false,
metadata: UserMetadata {
creation_timestamp: 0,
last_sign_in_timestamp: 0,
},
provider_data: vec![],
id_token: None,
refresh_token: None,
token_expiration: None,
api_key: None,
});
auth.set_current_user(Some(user)).await;
assert!(auth.current_user().await.is_some());
auth.sign_out().await.unwrap();
assert!(auth.current_user().await.is_none());
}
#[tokio::test]
async fn test_different_api_keys_different_instances() {
let auth1 = Auth::get_auth(&test_app("key_a", "project_a", "test_app_a").await).await.unwrap();
let auth2 = Auth::get_auth(&test_app("key_b", "project_b", "test_app_b").await).await.unwrap();
// Should be different instances
assert!(!Arc::ptr_eq(&auth1.inner, &auth2.inner));
assert_eq!(auth1.api_key(), "key_a");
assert_eq!(auth2.api_key(), "key_b");
}
#[tokio::test]
async fn test_sign_in_validates_email() {
let auth = Auth::get_auth(&test_app("test_key", "project", "test_app_key").await).await.unwrap();
let result = auth.sign_in_with_email_and_password("", "password").await;
assert!(matches!(result, Err(FirebaseError::Auth(AuthError::InvalidEmail))));
}
#[tokio::test]
async fn test_sign_in_validates_password() {
let auth = Auth::get_auth(&test_app("test_key", "project", "test_app_key").await).await.unwrap();
let result = auth.sign_in_with_email_and_password("test@example.com", "").await;
assert!(matches!(result, Err(FirebaseError::Auth(AuthError::InvalidPassword))));
}
#[tokio::test]
async fn test_create_user_validates_email() {
let auth = Auth::get_auth(&test_app("test_key", "project", "test_app_key").await).await.unwrap();
let result = auth.create_user_with_email_and_password("", "password123").await;
assert!(matches!(result, Err(FirebaseError::Auth(AuthError::InvalidEmail))));
}
#[tokio::test]
async fn test_create_user_validates_password() {
let auth = Auth::get_auth(&test_app("test_key", "project", "test_app_key").await).await.unwrap();
let result = auth.create_user_with_email_and_password("new@example.com", "").await;
assert!(matches!(result, Err(FirebaseError::Auth(AuthError::InvalidPassword))));
}
#[tokio::test]
async fn test_sign_in_anonymously_returns_user() {
let auth = Auth::get_auth(&test_app("test_anon_key", "project_anon", "test_app_anon").await).await.unwrap();
// This will fail without real Firebase, but validates the structure
// In real usage, this would create an anonymous user
let result = auth.sign_in_anonymously().await;
// We expect network error since no real Firebase backend
assert!(result.is_err());
}
#[tokio::test]
async fn test_anonymous_user_updates_current_user() {
use crate::auth::types::UserMetadata;
let auth = Auth::get_auth(&test_app("test_anon_key2", "project_anon2", "test_app_anon2").await).await.unwrap();
// Initially no user
assert!(auth.current_user().await.is_none());
// Manually set an anonymous user (simulating successful sign in)
let anon_user = Arc::new(User {
uid: "anon123".to_string(),
email: None,
display_name: None,
photo_url: None,
phone_number: None,
email_verified: false,
is_anonymous: true,
metadata: UserMetadata {
creation_timestamp: 0,
last_sign_in_timestamp: 0,
},
provider_data: vec![],
id_token: None,
refresh_token: None,
token_expiration: None,
api_key: None,
});
auth.set_current_user(Some(anon_user.clone())).await;
let current = auth.current_user().await;
assert!(current.is_some());
let user = current.unwrap();
assert_eq!(user.uid, "anon123");
assert!(user.is_anonymous);
}
#[tokio::test]
async fn test_password_reset_validates_email() {
let auth = Auth::get_auth(&test_app("test_password_reset_key", "project_reset", "test_app_reset").await).await.unwrap();
let result = auth.send_password_reset_email("").await;
assert!(matches!(result, Err(FirebaseError::Auth(AuthError::InvalidEmail))));
}
#[tokio::test]
async fn test_password_reset_does_not_affect_current_user() {
use crate::auth::types::UserMetadata;
let auth = Auth::get_auth(&test_app("test_password_reset_key2", "project_reset2", "test_app_reset2").await).await.unwrap();
// Sign in a user
let user = Arc::new(User {
uid: "user123".to_string(),
email: Some("test@example.com".to_string()),
display_name: None,
photo_url: None,
phone_number: None,
email_verified: false,
is_anonymous: false,
metadata: UserMetadata {
creation_timestamp: 0,
last_sign_in_timestamp: 0,
},
provider_data: vec![],
id_token: None,
refresh_token: None,
token_expiration: None,
api_key: None,
});
auth.set_current_user(Some(user.clone())).await;
// Password reset should not change current user
// (This will fail with network error, but that's expected in tests)
let _ = auth.send_password_reset_email("other@example.com").await;
let current = auth.current_user().await;
assert!(current.is_some());
assert_eq!(current.unwrap().uid, "user123");
}
#[tokio::test]
async fn test_auth_state_changes_initial() {
use futures::StreamExt;
let auth = Auth::get_auth(&test_app("test_key_state1", "project_state1", "test_app_state1").await).await.unwrap();
let mut stream = auth.auth_state_changes().await;
// Should immediately yield None (no user signed in)
let initial = stream.next().await;
assert!(initial.is_some());
assert!(initial.unwrap().is_none());
}
#[tokio::test]
async fn test_auth_state_changes_on_sign_in() {
use futures::StreamExt;
use crate::auth::types::UserMetadata;
let auth = Auth::get_auth(&test_app("test_key_state2", "project_state2", "test_app_state2").await).await.unwrap();
let mut stream = auth.auth_state_changes().await;
// Get initial state (None)
let _ = stream.next().await;
// Sign in a user
let user = Arc::new(User {
uid: "test123".to_string(),
email: Some("test@example.com".to_string()),
display_name: None,
photo_url: None,
phone_number: None,
email_verified: false,
is_anonymous: false,
metadata: UserMetadata {
creation_timestamp: 0,
last_sign_in_timestamp: 0,
},
provider_data: vec![],
id_token: None,
refresh_token: None,
token_expiration: None,
api_key: None,
});
auth.set_current_user(Some(user.clone())).await;
// Should receive the new user
let next = stream.next().await;
assert!(next.is_some());
let received_user = next.unwrap();
assert!(received_user.is_some());
assert_eq!(received_user.as_ref().unwrap().uid, "test123");
}
#[tokio::test]
async fn test_auth_state_changes_on_sign_out() {
use futures::StreamExt;
use crate::auth::types::UserMetadata;
let auth = Auth::get_auth(&test_app("test_key_state3", "project_state3", "test_app_state3").await).await.unwrap();
// Set initial user
let user = Arc::new(User {
uid: "test456".to_string(),
email: Some("test2@example.com".to_string()),
display_name: None,
photo_url: None,
phone_number: None,
email_verified: false,
is_anonymous: false,
metadata: UserMetadata {
creation_timestamp: 0,
last_sign_in_timestamp: 0,
},
provider_data: vec![],
id_token: None,
refresh_token: None,
token_expiration: None,
api_key: None,
});
auth.set_current_user(Some(user)).await;
let mut stream = auth.auth_state_changes().await;
// Get initial state (with user)
let initial = stream.next().await;
assert!(initial.unwrap().is_some());
// Sign out
auth.sign_out().await.unwrap();
// Should receive None
let next = stream.next().await;
assert!(next.is_some());
assert!(next.unwrap().is_none());
}
#[tokio::test]
async fn test_sign_in_with_google_credential() {
use crate::auth::types::Credential;
use crate::error::AuthError;
let auth = Auth::get_auth(&test_app("test_google_key", "project_google", "test_app_google").await).await.unwrap();
// Test with invalid credential (no tokens)
let invalid_cred = Credential::Google {
id_token: None,
access_token: None,
};
let result = auth.sign_in_with_credential(invalid_cred).await;
assert!(matches!(result, Err(FirebaseError::Auth(AuthError::InvalidCredential(_)))));
// Test with valid credential (would fail without real Firebase project, but validates structure)
let valid_cred = Credential::Google {
id_token: Some("test_id_token".to_string()),
access_token: Some("test_access_token".to_string()),
};
assert_eq!(valid_cred.provider_id(), "google.com");
}
#[tokio::test]
async fn test_sign_in_with_facebook_credential() {
use crate::auth::types::Credential;
let cred = Credential::Facebook {
access_token: "test_facebook_token".to_string(),
};
assert_eq!(cred.provider_id(), "facebook.com");
}
#[tokio::test]
async fn test_sign_in_with_github_credential() {
use crate::auth::types::Credential;
let cred = Credential::GitHub {
token: "test_github_token".to_string(),
};
assert_eq!(cred.provider_id(), "github.com");
}
#[tokio::test]
async fn test_sign_in_with_oauth_credential() {
use crate::auth::types::Credential;
use crate::error::AuthError;
let auth = Auth::get_auth(&test_app("test_oauth_key", "project_oauth", "test_app_oauth").await).await.unwrap();
// Test with invalid OAuth credential (no tokens)
let invalid_cred = Credential::OAuth {
provider_id: "apple.com".to_string(),
id_token: None,
access_token: None,
raw_nonce: None,
};
let result = auth.sign_in_with_credential(invalid_cred).await;
assert!(matches!(result, Err(FirebaseError::Auth(AuthError::InvalidCredential(_)))));
// Test with valid OAuth credential
let valid_cred = Credential::OAuth {
provider_id: "apple.com".to_string(),
id_token: Some("test_id_token".to_string()),
access_token: None,
raw_nonce: None,
};
assert_eq!(valid_cred.provider_id(), "apple.com");
}
#[tokio::test]
async fn test_credential_type_validation() {
use crate::auth::types::Credential;
use crate::error::AuthError;
let auth = Auth::get_auth(&test_app("test_validation_key", "project_validation", "test_app_validation").await).await.unwrap();
// Email/password should use dedicated method
let email_cred = Credential::EmailPassword {
email: "test@example.com".to_string(),
password: "password".to_string(),
};
let result = auth.sign_in_with_credential(email_cred).await;
assert!(matches!(result, Err(FirebaseError::Auth(AuthError::InvalidCredential(_)))));
// Anonymous should use dedicated method
let anon_cred = Credential::Anonymous;
let result = auth.sign_in_with_credential(anon_cred).await;
assert!(matches!(result, Err(FirebaseError::Auth(AuthError::InvalidCredential(_)))));
// CustomToken should use dedicated method
let custom_cred = Credential::CustomToken {
token: "custom_token".to_string(),
};
let result = auth.sign_in_with_credential(custom_cred).await;
assert!(matches!(result, Err(FirebaseError::Auth(AuthError::InvalidCredential(_)))));
}
#[tokio::test]
async fn test_sign_in_with_custom_token_validates_empty() {
use crate::error::AuthError;
let auth = Auth::get_auth(&test_app("test_custom_token_key", "project_custom", "test_app_custom").await).await.unwrap();
let result = auth.sign_in_with_custom_token("").await;
assert!(matches!(result, Err(FirebaseError::Auth(AuthError::InvalidCredential(_)))));
}
#[tokio::test]
async fn test_custom_token_credential() {
use crate::auth::types::Credential;
let cred = Credential::CustomToken {
token: "server_generated_token".to_string(),
};
assert_eq!(cred.provider_id(), "custom");
}
}