fars 0.2.0

An unofficial Rust client for the Firebase Auth REST API.
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
//! Authentication session for a user of the Firebase Auth.
//!
//! ## Features
//! Provides APIs that require an ID token.
//!
//! A session ([`crate::Session`]) is provided by a siging in method of config ([`crate::Config`]).
//!
//! See also [`crate::config`].  
//!
//! ## NOTE
//! ID token in a session ([`crate::Session`]) has expiration date.
//!
//! API calling through a session ([`crate::Session`]) automatically refresh an ID token by the [refresh token API](https://firebase.google.com/docs/reference/rest/auth#section-refresh-token) when the ID token has been expired.
//!
//! All APIs through session cosume session and return new session that has same ID token or refreshed one except for the [delete account API](https://firebase.google.com/docs/reference/rest/auth#section-delete-account).
//!
//! Therefore you have to **update** session every time you use APIs through a session by returned new session.
//!
//! ## Supported APIs
//! Supported APIs are as follows:
//!
//! - [Change email](`crate::Session::change_email`)
//! - [Change password](`crate::Session::change_password`)
//! - [Update profile](`crate::Session::update_profile`)
//! - [Delete profile](`crate::Session::delete_profile`)
//! - [Get user data](`crate::Session::get_user_data`)
//! - [Link with email and password](`crate::Session::link_with_email_password`)
//! - [Link with OAuth credential](`crate::Session::link_with_oauth_credential`)
//! - [Unlink provider](`crate::Session::unlink_provider`)
//! - [Send email verification](`crate::Session::send_email_verification`)
//! - [Delete account](`crate::Session::delete_account`)
//! - [Refresh token](`crate::Session::refresh_token`)
//!
//! ## Examples
//! An example to get user data through a session with [tokio](https://github.com/tokio-rs/tokio) and [anyhow](https://github.com/dtolnay/anyhow) is as follows:
//!
//! ```rust
//! use fars::Config;
//! use fars::ApiKey;
//! use fars::Email;
//! use fars::Password;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     // Create config.
//!     let config = Config::new(
//!         ApiKey::new("your-firebase-project-api-key"),
//!     );
//!
//!     // Sign in with email and password.
//!     let session = config.sign_in_with_email_password(
//!         Email::new("user@example"),
//!         Password::new("password"),
//!     ).await?;
//!
//!     // Get user data.
//!     let (new_session, user_data) = session.get_user_data().await?;
//!     
//!     // Do something with user data.
//!     println!("User data: {:?}", user_data);
//!
//!     Ok(())
//! }
//! ```

use std::collections::HashSet;

use crate::api;
use crate::ApiKey;
use crate::Client;
use crate::DeleteAttribute;
use crate::DisplayName;
use crate::Email;
use crate::Error;
use crate::ExpiresIn;
use crate::IdToken;
use crate::IdpPostBody;
use crate::LanguageCode;
use crate::OAuthRequestUri;
use crate::Password;
use crate::PhotoUrl;
use crate::ProviderId;
use crate::RefreshToken;
use crate::Result;
use crate::UserData;

/// Authentication session for a user of the Firebase Auth.
///
/// Get a session by signing in with [`crate::Config`].
///
/// See also [`crate::config`].
///
/// ## Example
/// ```
/// use fars::Config;
/// use fars::ApiKey;
/// use fars::Email;
/// use fars::Password;
///
/// let config = Config::new(
///     ApiKey::new("your-firebase-project-api-key"),
/// );
///
/// let session = config.sign_in_with_email_password(
///     Email::new("user@example"),
///     Password::new("password"),
/// ).await?;
/// ```
#[derive(Clone, Debug)]
pub struct Session {
    /// HTTP client.
    pub(crate) client: Client,
    /// Firebase project API key.
    pub(crate) api_key: ApiKey,
    /// Firebase Auth ID token.
    pub id_token: IdToken,
    /// The number of seconds in which the ID token expires.
    pub expires_in: ExpiresIn,
    /// Firebase Auth refresh token.
    pub refresh_token: RefreshToken,
}

// Defines macros for calling APIs with refreshing tokens.

/// Calls an API with refreshing tokens then returns new session and value.
macro_rules! call_refreshing_tokens_return_session_and_value {
    // Has arguments and returns new session and value.
    ($session:expr, $api_call:expr, $retry_count:expr, $($api_call_args:expr), *) => {{
        async move {
            let mut session = $session;
            let mut attempts = 0;
            loop {
                match $api_call(&session, $($api_call_args), *).await {
                    Ok(value) => return Ok((session, value)),
                    Err(error) => match error {
                        // NOTE: Retry for invalid ID token error.
                        Error::InvalidIdToken if attempts < $retry_count => {
                            match session.refresh_token().await {
                                Ok(new_session) => {
                                    session = new_session;
                                    attempts += 1;
                                },
                                Err(e) => return Err(e),
                            }
                        },
                        _ => return Err(error),
                    },
                }
            }
        }
    }};

    // Has no arguments and returns new session and value.
    ($session:expr, $api_call:expr, $retry_count:expr,) => {{
        call_refreshing_tokens_return_session_and_value!($session, $api_call, $retry_count, ())
    }};
}

/// Calls an API with refreshing tokens without value then returns new session.
macro_rules! call_refreshing_tokens_without_value_return_session {
    // Has arguments and returns new session.
    ($session:expr, $api_call_unit:expr, $retry_count:expr, $($api_call_args:expr), *) => {{
        async move {
            let mut session = $session;
            let mut attempts = 0;
            loop {
                match $api_call_unit(&session, $($api_call_args), *).await {
                    Ok(_) => return Ok(session),
                    Err(error) => match error {
                        // NOTE: Retry for invalid ID token error.
                        Error::InvalidIdToken if attempts < $retry_count => {
                            match session.refresh_token().await {
                                Ok(new_session) => {
                                    session = new_session;
                                    attempts += 1;
                                },
                                Err(e) => return Err(e),
                            }
                        },
                        _ => return Err(error),
                    },
                }
            }
        }
    }};

    // Has no arguments and returns new session.
    ($session:expr, $api_call_unit:expr, $retry_count:expr,) => {{
        call_refreshing_tokens_without_value_return_session!($session, $api_call_unit, $retry_count, ())
    }};
}

/// Calls an API with refreshing tokens then returns new session.
#[allow(unused_macros)]
macro_rules! call_refreshing_tokens_return_session {
    // Has arguments and returns new session.
    ($session:expr, $api_call:expr, $retry_count:expr, $($api_call_args:expr),*) => {{
        async move {
            let mut session = $session;
            let mut attempts = 0;
            loop {
                match $api_call(&session, $($api_call_args),*).await {
                    Ok(new_session) => return Ok(new_session),
                    Err(error) => match error {
                        // NOTE: Retry for invalid ID token error.
                        Error::InvalidIdToken if attempts < $retry_count => {
                            match session.refresh_token().await {
                                Ok(new_session) => {
                                    session = new_session;
                                    attempts += 1;
                                },
                                Err(e) => return Err(e),
                            }
                        },
                        _ => return Err(error),
                    },
                }
            }
        }
    }};

    // Has no arguments and returns new session.
    ($session:expr, $api_call:expr, $retry_count:expr) => {{
        call_refreshing_tokens_return_session!($session, $api_call, $retry_count, )
    }};
}

/// Calls an API with refreshing tokens then returns nothing.
macro_rules! call_refreshing_tokens_return_nothing {
    // Has arguments and returns nothing.
    ($session:expr, $api_call:expr, $retry_count:expr, $($api_call_args:expr),*) => {{
        async move {
            let mut session = $session;
            let mut attempts = 0;
            loop {
                match $api_call(&session, $($api_call_args),*).await {
                    Ok(_) => return Ok(()),
                    Err(error) => match error {
                        // NOTE: Retry for invalid ID token error.
                        Error::InvalidIdToken if attempts < $retry_count => {
                            match session.refresh_token().await {
                                Ok(new_session) => {
                                    session = new_session;
                                    attempts += 1;
                                },
                                Err(e) => return Err(e),
                            }
                        },
                        _ => return Err(error),
                    },
                }
            }
        }
    }};

    // Has no arguments and returns nothing.
    ($session:expr, $api_call:expr, $retry_count:expr) => {{
        call_refreshing_tokens_return_nothing!($session, $api_call, $retry_count, )
    }};
}

// Implements public API callings for an `Session` with automatic refreshing tokens.
impl Session {
    /// Changes the email for the user.
    ///
    /// Automatically refreshes tokens if needed.
    ///
    /// ## Arguments
    /// - `new_email` - The new email address of the user.
    /// - `locale` - The optional language code corresponding to the user's locale.
    ///
    /// ## Returns
    /// New session to replace the consumed session.
    ///
    /// ## Errors
    /// - `Error::InvalidHeaderValue` - Invalid header value.
    /// - `Error::HttpRequestError` - Failed to send a request.
    /// - `Error::ReadResponseTextFailed` - Failed to read the response body as text.
    /// - `Error::DeserializeResponseJsonFailed` - Failed to deserialize the response body as JSON.
    /// - `Error::DeserializeErrorResponseJsonFailed` - Failed to deserialize the error response body as JSON.
    /// - `Error::InvalidIdToken` - Invalid ID token.
    /// - `Error::ApiError` - API error on the Firebase Auth.
    ///
    /// ## Example
    /// ```
    /// use fars::Config;
    /// use fars::ApiKey;
    /// use fars::Email;
    /// use fars::Password;
    ///
    /// let config = Config::new(
    ///     ApiKey::new("your-firebase-project-api-key"),
    /// );
    /// let session = config.sign_in_with_email_password(
    ///     Email::new("user@example"),
    ///     Password::new("password"),
    /// ).await?;
    ///
    /// let new_session = session.change_email(
    ///     Email::new("new-user@example"),
    ///     None, // locale
    /// ).await?;
    /// ```
    pub async fn change_email(
        self,
        new_email: Email,
        locale: Option<LanguageCode>,
    ) -> Result<Session> {
        call_refreshing_tokens_without_value_return_session!(
            self,
            Session::change_email_internal,
            1,
            new_email.clone(),
            locale
        )
        .await
    }

    /// Changes the password for the user.
    ///
    /// Automatically refreshes tokens if needed.
    ///
    /// ## Arguments
    /// - `new_password` - The new password of the user.
    ///
    /// ## Returns
    /// New session to replace the consumed session.
    ///
    /// ## Errors
    /// - `Error::HttpRequestError` - Failed to send a request.
    /// - `Error::ReadResponseTextFailed` - Failed to read the response body as text.
    /// - `Error::DeserializeResponseJsonFailed` - Failed to deserialize the response body as JSON.
    /// - `Error::DeserializeErrorResponseJsonFailed` - Failed to deserialize the error response body as JSON.
    /// - `Error::InvalidIdToken` - Invalid ID token.
    /// - `Error::ApiError` - API error on the Firebase Auth.
    /// - `Error::ParseExpriesInFailed` - Failed to parse the expires in value.
    ///
    /// ## Example
    /// ```
    /// use fars::Config;
    /// use fars::ApiKey;
    /// use fars::Email;
    /// use fars::Password;
    ///
    /// let config = Config::new(
    ///     ApiKey::new("your-firebase-project-api-key"),
    /// );
    /// let session = config.sign_in_with_email_password(
    ///     Email::new("user@example"),
    ///     Password::new("password"),
    /// ).await?;
    ///
    /// let new_session = session.change_password(
    ///     Password::new("new-password"),
    /// ).await?;
    /// ```
    pub async fn change_password(
        self,
        new_password: Password,
    ) -> Result<Session> {
        call_refreshing_tokens_without_value_return_session!(
            self,
            Session::change_password_internal,
            1,
            new_password.clone()
        )
        .await
    }

    /// Updates the user profile information.
    ///
    /// Automatically refreshes tokens if needed.
    ///
    /// ## Arguments
    /// - `display_name` - (Optional) The display name for the account.
    /// - `photo_url` - (Optional) The photo url of the account.
    ///
    /// ## Returns
    /// New session to replace the consumed session.
    ///
    /// ## Errors
    /// - `Error::HttpRequestError` - Failed to send a request.
    /// - `Error::ReadResponseTextFailed` - Failed to read the response body as text.
    /// - `Error::DeserializeResponseJsonFailed` - Failed to deserialize the response body as JSON.
    /// - `Error::DeserializeErrorResponseJsonFailed` - Failed to deserialize the error response body as JSON.
    /// - `Error::InvalidIdToken` - Invalid ID token.
    /// - `Error::ApiError` - API error on the Firebase Auth.
    ///
    /// ## Example
    /// ```
    /// use fars::Config;
    /// use fars::ApiKey;
    /// use fars::Email;    
    /// use fars::Password;
    /// use fars::DisplayName;
    /// use fars::PhotoUrl;
    ///
    /// let config = Config::new(
    ///     ApiKey::new("your-firebase-project-api-key"),
    /// );
    /// let session = config.sign_in_with_email_password(
    ///     Email::new("user@example"),
    ///     Password::new("password"),
    /// ).await?;
    ///
    /// let new_session = session.update_profile(
    ///     DisplayName::new("new-display-name"),
    ///     PhotoUrl::new("new-photo-url"),
    /// ).await?;
    /// ```
    pub async fn update_profile(
        self,
        display_name: Option<DisplayName>,
        photo_url: Option<PhotoUrl>,
    ) -> Result<Session> {
        call_refreshing_tokens_without_value_return_session!(
            self,
            Session::update_profile_internal,
            1,
            display_name.clone(),
            photo_url.clone()
        )
        .await
    }

    /// Deletes the user profile information.
    ///
    /// Automatically refreshes tokens if needed.
    ///
    /// ## Arguments
    /// - `delete_attribute` - The attributes that should be deleted from the account.
    ///
    /// ## Returns
    /// New session to replace the consumed session.
    ///
    /// ## Errors
    /// - `Error::HttpRequestError` - Failed to send a request.
    /// - `Error::ReadResponseTextFailed` - Failed to read the response body as text.
    /// - `Error::DeserializeResponseJsonFailed` - Failed to deserialize the response body as JSON.
    /// - `Error::DeserializeErrorResponseJsonFailed` - Failed to deserialize the error response body as JSON.
    /// - `Error::InvalidIdToken` - Invalid ID token.
    /// - `Error::ApiError` - API error on the Firebase Auth.
    ///
    /// ## Example
    /// ```
    /// use fars::Config;
    /// use fars::ApiKey;
    /// use fars::Email;
    /// use fars::Password;
    /// use fars::DeleteAttribute;
    ///
    /// let config = Config::new(
    ///     ApiKey::new("your-firebase-project-api-key"),
    /// );
    /// let session = config.sign_in_with_email_password(
    ///     Email::new("user@example"),
    ///     Password::new("password"),
    /// ).await?;
    ///
    /// let new_session = session.delete_profile(
    ///     [DeleteAttribute::DisplayName, DeleteAttribute::PhotoUrl]
    ///         .iter()
    ///         .cloned()
    ///         .collect(),
    /// ).await?;
    /// ```
    pub async fn delete_profile(
        self,
        delete_attribute: HashSet<DeleteAttribute>,
    ) -> Result<Session> {
        call_refreshing_tokens_without_value_return_session!(
            self,
            Session::delete_profile_internal,
            1,
            delete_attribute.clone()
        )
        .await
    }

    /// Gets the user data.
    ///
    /// Automatically refreshes tokens if needed.
    ///
    /// ## Returns
    /// 1. New session to replace the consumed session.
    /// 2. The user data.
    ///
    /// ## Errors
    /// - `Error::InvalidHeaderValue` - Invalid header value.
    /// - `Error::HttpRequestError` - Failed to send a request.
    /// - `Error::ReadResponseTextFailed` - Failed to read the response body as text.
    /// - `Error::DeserializeResponseJsonFailed` - Failed to deserialize the response body as JSON.
    /// - `Error::DeserializeErrorResponseJsonFailed` - Failed to deserialize the error response body as JSON.
    /// - `Error::InvalidIdToken` - Invalid ID token.
    /// - `Error::ApiError` - API error on the Firebase Auth.
    /// - `Error::NotFoundAnyUserData` - Not found any user data.
    ///
    /// ## Example
    /// ```
    /// use fars::Config;
    /// use fars::ApiKey;
    /// use fars::Email;
    /// use fars::Password;
    ///
    /// let config = Config::new(
    ///     ApiKey::new("your-firebase-project-api-key"),
    /// );
    /// let session = config.sign_in_with_email_password(
    ///     Email::new("user@example"),
    ///     Password::new("password"),
    /// ).await?;
    ///
    /// let (new_session, user_data) = session.get_user_data().await?;
    /// ```
    pub async fn get_user_data(self) -> Result<(Session, UserData)> {
        call_refreshing_tokens_return_session_and_value!(
            self,
            Session::get_user_data_internal,
            1,
        )
        .await
    }

    /// Links the user with the given email and password.
    ///
    /// Automatically refreshes tokens if needed.
    ///
    /// ## Arguments
    /// - `email` - The email of the user to link.
    /// - `password` - The password of the user to link.
    ///
    /// ## Returns
    /// New session to replace the consumed session.
    ///
    /// ## Errors
    /// - `Error::HttpRequestError` - Failed to send a request.
    /// - `Error::ReadResponseTextFailed` - Failed to read the response body as text.
    /// - `Error::DeserializeResponseJsonFailed` - Failed to deserialize the response body as JSON.
    /// - `Error::DeserializeErrorResponseJsonFailed` - Failed to deserialize the error response body as JSON.
    /// - `Error::InvalidIdToken` - Invalid ID token.
    /// - `Error::ApiError` - API error on the Firebase Auth.
    /// - `Error::ParseExpriesInFailed` - Failed to parse the expires in value.
    ///
    /// ## Example
    /// ```
    /// use fars::Config;
    /// use fars::ApiKey;
    /// use fars::OAuthRequestUri;
    /// use fars::IdpPostBody;
    /// use fars::Email;
    /// use fars::Password;
    ///
    /// let config = Config::new(
    ///     ApiKey::new("your-firebase-project-api-key"),
    /// );
    /// let session = config.sign_in_oauth_credencial(
    ///     OAuthRequestUri::new("https://your-app.com/redirect/path/auth/handler"),
    ///     IdpPostBody::Google {
    ///         id_token: "user-google-oauth-open-id-token".to_string(),
    ///     },
    /// ).await?;
    ///
    /// let new_session = session.link_with_email_password(
    ///    Email::new("new-user@example"),
    ///    Password::new("new-password"),
    /// ).await?;
    /// ```
    pub async fn link_with_email_password(
        self,
        email: Email,
        password: Password,
    ) -> Result<Session> {
        call_refreshing_tokens_without_value_return_session!(
            self,
            Session::link_with_email_password_internal,
            1,
            email.clone(),
            password.clone()
        )
        .await
    }

    /// Links the user with the given OAuth credential.
    ///
    /// Automatically refreshes tokens if needed.
    ///
    /// ## Arguments
    /// - `request_uri` - The URI to which the IDP redirects the user back.
    /// - `post_body` - The POST body passed to the IDP containing the OAuth credential and provider ID.
    ///
    /// ## Returns
    /// New session to replace the consumed session.
    ///
    /// ## Errors
    /// - `Error::InvalidHeaderValue` - Invalid header value.
    /// - `Error::HttpRequestError` - Failed to send a request.
    /// - `Error::ReadResponseTextFailed` - Failed to read the response body as text.
    /// - `Error::DeserializeResponseJsonFailed` - Failed to deserialize the response body as JSON.
    /// - `Error::DeserializeErrorResponseJsonFailed` - Failed to deserialize the error response body as JSON.
    /// - `Error::InvalidIdToken` - Invalid ID token.
    /// - `Error::ApiError` - API error on the Firebase Auth.
    /// - `Error::ParseExpriesInFailed` - Failed to parse the expires in value.
    ///
    /// ## Example
    /// ```
    /// use fars::Config;
    /// use fars::ApiKey;
    /// use fars::Email;
    /// use fars::Password;
    /// use fars::OAuthRequestUri;
    /// use fars::IdpPostBody;
    ///
    /// let config = Config::new(
    ///     ApiKey::new("your-firebase-project-api-key"),
    /// );
    /// let session = config.sign_in_with_email_password(
    ///     Email::new("user@example"),
    ///     Password::new("password"),
    /// ).await?;
    ///
    /// let new_session = session.link_with_oauth_credential(
    ///     OAuthRequestUri::new("https://your-app.com/redirect/path/auth/handler"),
    ///     IdpPostBody::Google {
    ///         id_token: "user-google-id-token-got-from-google-oauth-api".to_string(),
    ///     },
    /// ).await?;
    /// ```
    pub async fn link_with_oauth_credential(
        self,
        request_uri: OAuthRequestUri,
        post_body: IdpPostBody,
    ) -> Result<Session> {
        call_refreshing_tokens_without_value_return_session!(
            self,
            Session::link_with_oauth_credential_internal,
            1,
            request_uri.clone(),
            post_body.clone()
        )
        .await
    }

    /// Unlinks the user with the given provider.
    ///
    /// Automatically refreshes tokens if needed.
    ///
    /// ## Arguments
    /// - `delete_provider` - The provider IDs to unlink.
    ///
    /// ## Returns
    /// New session to replace the consumed session.
    ///
    /// ## Errors
    /// - `Error::HttpRequestError` - Failed to send a request.
    /// - `Error::ReadResponseTextFailed` - Failed to read the response body as text.
    /// - `Error::DeserializeResponseJsonFailed` - Failed to deserialize the response body as JSON.
    /// - `Error::DeserializeErrorResponseJsonFailed` - Failed to deserialize the error response body as JSON.
    /// - `Error::InvalidIdToken` - Invalid ID token.
    /// - `Error::ApiError` - API error on the Firebase Auth.
    ///
    /// ## Example
    /// ```
    /// use fars::Config;
    /// use fars::ApiKey;
    /// use fars::Email;
    /// use fars::Password;
    /// use fars::ProviderId;
    ///
    /// let config = Config::new(
    ///     ApiKey::new("your-firebase-project-api-key"),
    /// );
    /// let session = config.sign_in_with_email_password(
    ///     Email::new("user@example"),
    ///     Password::new("password"),
    /// ).await?;
    ///
    /// let new_session = session.unlink_provider(
    ///    [ProviderId::Google].iter().cloned().collect(),
    /// ).await?;
    /// ```
    pub async fn unlink_provider(
        self,
        delete_provider: HashSet<ProviderId>,
    ) -> Result<Session> {
        call_refreshing_tokens_without_value_return_session!(
            self,
            Session::unlink_provider_internal,
            1,
            delete_provider.clone()
        )
        .await
    }

    /// Sends an email verification to the user.
    ///
    /// Automatically refreshes tokens if needed.
    ///
    /// ## Arguments
    /// - `locale` - The optional language code corresponding to the user's locale.
    ///
    /// ## Returns
    /// New session to replace the consumed session.
    ///
    /// ## Errors
    /// - `Error::InvalidHeaderValue` - Invalid header value.
    /// - `Error::HttpRequestError` - Failed to send a request.
    /// - `Error::ReadResponseTextFailed` - Failed to read the response body as text.
    /// - `Error::DeserializeResponseJsonFailed` - Failed to deserialize the response body as JSON.
    /// - `Error::DeserializeErrorResponseJsonFailed` - Failed to deserialize the error response body as JSON.
    /// - `Error::InvalidIdToken` - Invalid ID token.
    /// - `Error::ApiError` - API error on the Firebase Auth.
    ///
    /// ## Example
    /// ```
    /// use fars::Config;
    /// use fars::ApiKey;
    /// use fars::Email;
    /// use fars::Password;
    ///
    /// let config = Config::new(
    ///     ApiKey::new("your-firebase-project-api-key"),
    /// );
    /// let session = config.sign_in_with_email_password(
    ///     Email::new("user@example"),
    ///     Password::new("password"),
    /// ).await?;
    ///
    /// let new_session = session.send_email_verification(
    ///     None, // locale
    /// ).await?;
    /// ```
    pub async fn send_email_verification(
        self,
        locale: Option<LanguageCode>,
    ) -> Result<Session> {
        call_refreshing_tokens_without_value_return_session!(
            self,
            Session::send_email_verification_internal,
            1,
            locale
        )
        .await
    }

    /// Deletes the user account.
    ///
    /// Automatically refreshes tokens if needed.
    ///
    /// ## Errors
    /// - `Error::HttpRequestError` - Failed to send a request.
    /// - `Error::ReadResponseTextFailed` - Failed to read the response body as text.
    /// - `Error::DeserializeResponseJsonFailed` - Failed to deserialize the response body as JSON.
    /// - `Error::DeserializeErrorResponseJsonFailed` - Failed to deserialize the error response body as JSON.
    /// - `Error::InvalidIdToken` - Invalid ID token.
    /// - `Error::ApiError` - API error on the Firebase Auth.
    ///
    /// ## Example
    /// ```
    /// use fars::Config;
    /// use fars::ApiKey;
    /// use fars::Email;
    /// use fars::Password;
    ///
    /// let config = Config::new(
    ///     ApiKey::new("your-firebase-project-api-key"),
    /// );
    /// let session = config.sign_in_with_email_password(
    ///     Email::new("user@example"),
    ///     Password::new("password"),
    /// ).await?;
    ///
    /// session.delete_account().await?;
    /// ```
    pub async fn delete_account(self) -> Result<()> {
        call_refreshing_tokens_return_nothing!(
            self,
            Session::delete_account_internal,
            1,
        )
        .await
    }

    /// Refreshes the ID token.
    ///
    /// See also [API reference](https://firebase.google.com/docs/reference/rest/auth#section-refresh-token).
    ///
    /// ## Returns
    /// New session with refreshed ID token.
    ///
    /// ## Errors
    /// - `Error::HttpRequestError` - Failed to send a request.
    /// - `Error::ReadResponseTextFailed` - Failed to read the response body as text.
    /// - `Error::DeserializeResponseJsonFailed` - Failed to deserialize the response body as JSON.
    /// - `Error::DeserializeErrorResponseJsonFailed` - Failed to deserialize the error response body as JSON.
    /// - `Error::ApiError` - API error on the Firebase Auth.
    /// - `Error::ParseExpriesInFailed` - Failed to parse the expires in value.
    ///
    /// ## Example
    /// ```
    /// use fars::Config;
    /// use fars::ApiKey;
    /// use fars::Email;
    /// use fars::Password;
    ///
    /// let config = Config::new(
    ///     ApiKey::new("your-firebase-project-api-key"),
    /// );
    ///
    /// let session = config.sign_in_with_email_password(
    ///     Email::new("user@example"),
    ///     Password::new("password"),
    /// ).await?;
    ///
    /// // Expire the ID token.
    ///
    /// let new_session = session.refresh_token().await?;
    /// ```
    pub async fn refresh_token(self) -> Result<Self> {
        // Create request payload.
        let request_payload = api::ExchangeRefreshTokenRequestBodyPayload::new(
            self.refresh_token
                .inner()
                .to_string(),
        );

        // Send request.
        let response_payload = api::exchange_refresh_token(
            &self.client,
            &self.api_key,
            request_payload,
        )
        .await?;

        // Create tokens.
        Ok(Self {
            client: self.client.clone(),
            api_key: self.api_key.clone(),
            id_token: IdToken::new(response_payload.id_token),
            expires_in: ExpiresIn::parse(response_payload.expires_in)?,
            refresh_token: RefreshToken::new(response_payload.refresh_token),
        })
    }
}

// Implements internal API callings for an `Session`.
impl Session {
    async fn change_email_internal(
        &self,
        new_email: Email,
        locale: Option<LanguageCode>,
    ) -> Result<()> {
        // Create request payload.
        let request_payload = api::ChangeEmailRequestBodyPayload::new(
            self.id_token
                .inner()
                .to_string(),
            new_email.inner().to_string(),
            false,
        );

        // Send request.
        api::change_email(
            &self.client,
            &self.api_key,
            request_payload,
            locale,
        )
        .await?;

        Ok(())
    }

    async fn change_password_internal(
        &self,
        new_password: Password,
    ) -> Result<()> {
        // Create request payload.
        let request_payload = api::ChangePasswordRequestBodyPayload::new(
            self.id_token
                .inner()
                .to_string(),
            new_password
                .inner()
                .to_string(),
            false,
        );

        // Send request.
        api::change_password(
            &self.client,
            &self.api_key,
            request_payload,
        )
        .await?;

        Ok(())
    }

    async fn update_profile_internal(
        &self,
        display_name: Option<DisplayName>,
        photo_url: Option<PhotoUrl>,
    ) -> Result<()> {
        // Create request payload.
        let request_payload = api::UpdateProfileRequestBodyPayload::new(
            self.id_token
                .inner()
                .to_string(),
            display_name.map(|display_name| {
                display_name
                    .inner()
                    .to_string()
            }),
            photo_url.map(|photo_url| photo_url.inner().to_string()),
            None,
            false,
        );

        // Send request.
        api::update_profile(
            &self.client,
            &self.api_key,
            request_payload,
        )
        .await?;

        Ok(())
    }

    async fn delete_profile_internal(
        &self,
        delete_attribute: HashSet<DeleteAttribute>,
    ) -> Result<()> {
        // Format delete attributes.
        let delete_attribute = delete_attribute
            .iter()
            .copied()
            .collect();

        // Create request payload.
        let request_payload = api::UpdateProfileRequestBodyPayload::new(
            self.id_token
                .inner()
                .to_string(),
            None,
            None,
            Some(delete_attribute),
            false,
        );

        // Send request.
        api::update_profile(
            &self.client,
            &self.api_key,
            request_payload,
        )
        .await?;

        Ok(())
    }

    async fn get_user_data_internal(&self) -> Result<UserData> {
        // Create request payload.
        let request_payload = api::GetUserDataRequestBodyPayload::new(
            self.id_token
                .inner()
                .to_string(),
        );

        // Send request.
        let response_payload = api::get_user_data(
            &self.client,
            &self.api_key,
            request_payload,
        )
        .await?;

        // Take the first user from vector.
        let user = response_payload
            .users
            .first()
            .ok_or(Error::NotFoundAnyUserData)?;

        Ok(UserData {
            local_id: user.local_id.clone(),
            email: user.email.clone(),
            email_verified: user.email_verified,
            display_name: user.display_name.clone(),
            photo_url: user.photo_url.clone(),
            provider_user_info: user
                .provider_user_info
                .clone(),
            password_hash: user.password_hash.clone(),
            password_updated_at: user.password_updated_at,
            valid_since: user.valid_since.clone(),
            disabled: user.disabled,
            last_login_at: user.last_login_at.clone(),
            created_at: user.created_at.clone(),
            last_refresh_at: user.last_refresh_at.clone(),
            custom_auth: user.custom_auth,
        })
    }

    async fn link_with_email_password_internal(
        &self,
        email: Email,
        password: Password,
    ) -> Result<Self> {
        // Create request payload.
        let request_payload = api::LinkWithEmailPasswordRequestBodyPayload::new(
            self.id_token
                .inner()
                .to_string(),
            email.inner().to_string(),
            password.inner().to_string(),
        );

        // Send request.
        let response_payload = api::link_with_email_password(
            &self.client,
            &self.api_key,
            request_payload,
        )
        .await?;

        // Update tokens.
        Ok(Self {
            client: self.client.clone(),
            api_key: self.api_key.clone(),
            id_token: IdToken::new(response_payload.id_token),
            expires_in: ExpiresIn::parse(response_payload.expires_in)?,
            refresh_token: RefreshToken::new(response_payload.refresh_token),
        })
    }

    async fn link_with_oauth_credential_internal(
        &self,
        request_uri: OAuthRequestUri,
        post_body: IdpPostBody,
    ) -> Result<Self> {
        // Create request payload.
        let request_payload =
            api::LinkWithOAuthCredentialRequestBodyPayload::new(
                self.id_token
                    .inner()
                    .to_string(),
                request_uri
                    .inner()
                    .to_string(),
                post_body,
                false,
            );

        // Send request.
        let response_payload = api::link_with_oauth_credential(
            &self.client,
            &self.api_key,
            request_payload,
        )
        .await?;

        // Update tokens.
        Ok(Self {
            client: self.client.clone(),
            api_key: self.api_key.clone(),
            id_token: IdToken::new(response_payload.id_token),
            expires_in: ExpiresIn::parse(response_payload.expires_in)?,
            refresh_token: RefreshToken::new(response_payload.refresh_token),
        })
    }

    async fn unlink_provider_internal(
        &self,
        delete_provider: HashSet<ProviderId>,
    ) -> Result<()> {
        // Create request payload.
        let request_payload = api::UnlinkProviderRequestBodyPayload::new(
            self.id_token
                .inner()
                .to_string(),
            delete_provider,
        );

        // Send request.
        api::unlink_provider(
            &self.client,
            &self.api_key,
            request_payload,
        )
        .await?;

        Ok(())
    }

    async fn send_email_verification_internal(
        &self,
        locale: Option<LanguageCode>,
    ) -> Result<()> {
        // Create request payload.
        let request_payload = api::SendEmailVerificationRequestBodyPayload::new(
            self.id_token
                .inner()
                .to_string(),
        );

        // Send request.
        api::send_email_verification(
            &self.client,
            &self.api_key,
            request_payload,
            locale,
        )
        .await?;

        Ok(())
    }

    async fn delete_account_internal(&self) -> Result<()> {
        // Create request payload.
        let request_payload = api::DeleteAccountRequestBodyPayload::new(
            self.id_token
                .inner()
                .to_string(),
        );

        // Send request.
        api::delete_account(
            &self.client,
            &self.api_key,
            request_payload,
        )
        .await?;

        Ok(())
    }
}