forked from firebase/firebase-admin-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractFirebaseAuth.java
More file actions
1847 lines (1715 loc) · 84.6 KB
/
AbstractFirebaseAuth.java
File metadata and controls
1847 lines (1715 loc) · 84.6 KB
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
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.auth;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.firebase.auth.internal.Utils.isEmulatorMode;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.Clock;
import com.google.api.core.ApiFuture;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseUserManager.EmailLinkType;
import com.google.firebase.auth.FirebaseUserManager.UserImportRequest;
import com.google.firebase.auth.ListProviderConfigsPage.DefaultOidcProviderConfigSource;
import com.google.firebase.auth.ListProviderConfigsPage.DefaultSamlProviderConfigSource;
import com.google.firebase.auth.ListUsersPage.DefaultUserSource;
import com.google.firebase.auth.internal.FirebaseTokenFactory;
import com.google.firebase.internal.CallableOperation;
import com.google.firebase.internal.NonNull;
import com.google.firebase.internal.Nullable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* This is the abstract class for server-side Firebase Authentication actions.
*/
public abstract class AbstractFirebaseAuth {
private final Object lock = new Object();
private final AtomicBoolean destroyed = new AtomicBoolean(false);
private final FirebaseApp firebaseApp;
private final Supplier<FirebaseTokenFactory> tokenFactory;
private final Supplier<? extends FirebaseTokenVerifier> idTokenVerifier;
private final Supplier<? extends FirebaseTokenVerifier> cookieVerifier;
private final Supplier<? extends FirebaseUserManager> userManager;
private final JsonFactory jsonFactory;
protected AbstractFirebaseAuth(Builder<?> builder) {
this.firebaseApp = checkNotNull(builder.firebaseApp);
this.tokenFactory = threadSafeMemoize(builder.tokenFactory);
this.idTokenVerifier = threadSafeMemoize(builder.idTokenVerifier);
this.cookieVerifier = threadSafeMemoize(builder.cookieVerifier);
this.userManager = threadSafeMemoize(builder.userManager);
this.jsonFactory = firebaseApp.getOptions().getJsonFactory();
}
/**
* Creates a Firebase custom token for the given UID. This token can then be sent back to a client
* application to be used with the <a
* href="/docs/auth/admin/create-custom-tokens#sign_in_using_custom_tokens_on_clients">signInWithCustomToken</a>
* authentication API.
*
* <p>{@link FirebaseApp} must have been initialized with service account credentials to use call
* this method.
*
* @param uid The UID to store in the token. This identifies the user to other Firebase services
* (Realtime Database, Firebase Auth, etc.). Should be less than 128 characters.
* @return A Firebase custom token string.
* @throws IllegalArgumentException If the specified uid is null or empty, or if the app has not
* been initialized with service account credentials.
* @throws FirebaseAuthException If an error occurs while generating the custom token.
*/
public String createCustomToken(@NonNull String uid) throws FirebaseAuthException {
return createCustomToken(uid, null);
}
/**
* Creates a Firebase custom token for the given UID, containing the specified additional claims.
* This token can then be sent back to a client application to be used with the <a
* href="/docs/auth/admin/create-custom-tokens#sign_in_using_custom_tokens_on_clients">signInWithCustomToken</a>
* authentication API.
*
* <p>This method attempts to generate a token using:
*
* <ol>
* <li>the private key of {@link FirebaseApp}'s service account credentials, if provided at
* initialization.
* <li>the <a
* href="https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/signBlob">IAM
* service</a> if a service account email was specified via {@link
* com.google.firebase.FirebaseOptions.Builder#setServiceAccountId(String)}.
* <li>the <a href="https://cloud.google.com/appengine/docs/standard/java/appidentity/">App
* Identity service</a> if the code is deployed in the Google App Engine standard
* environment.
* <li>the <a href="https://cloud.google.com/compute/docs/storing-retrieving-metadata">local
* Metadata server</a> if the code is deployed in a different GCP-managed environment like
* Google Compute Engine.
* </ol>
*
* <p>This method throws an exception when all the above fail.
*
* @param uid The UID to store in the token. This identifies the user to other Firebase services
* (Realtime Database, Firebase Auth, etc.). Should be less than 128 characters.
* @param developerClaims Additional claims to be stored in the token (and made available to
* security rules in Database, Storage, etc.). These must be able to be serialized to JSON
* (e.g. contain only Maps, Arrays, Strings, Booleans, Numbers, etc.)
* @return A Firebase custom token string.
* @throws IllegalArgumentException If the specified uid is null or empty.
* @throws IllegalStateException If the SDK fails to discover a viable approach for signing
* tokens.
* @throws FirebaseAuthException If an error occurs while generating the custom token.
*/
public String createCustomToken(
@NonNull String uid, @Nullable Map<String, Object> developerClaims)
throws FirebaseAuthException {
return createCustomTokenOp(uid, developerClaims).call();
}
/**
* Similar to {@link #createCustomToken(String)} but performs the operation asynchronously.
*
* @param uid The UID to store in the token. This identifies the user to other Firebase services
* (Realtime Database, Firebase Auth, etc.). Should be less than 128 characters.
* @return An {@code ApiFuture} which will complete successfully with the created Firebase custom
* token, or unsuccessfully with the failure Exception.
* @throws IllegalArgumentException If the specified uid is null or empty, or if the app has not
* been initialized with service account credentials.
*/
public ApiFuture<String> createCustomTokenAsync(@NonNull String uid) {
return createCustomTokenAsync(uid, null);
}
/**
* Similar to {@link #createCustomToken(String, Map)} but performs the operation asynchronously.
*
* @param uid The UID to store in the token. This identifies the user to other Firebase services
* (Realtime Database, Storage, etc.). Should be less than 128 characters.
* @param developerClaims Additional claims to be stored in the token (and made available to
* security rules in Database, Storage, etc.). These must be able to be serialized to JSON
* (e.g. contain only Maps, Arrays, Strings, Booleans, Numbers, etc.)
* @return An {@code ApiFuture} which will complete successfully with the created Firebase custom
* token, or unsuccessfully with the failure Exception.
* @throws IllegalArgumentException If the specified uid is null or empty, or if the app has not
* been initialized with service account credentials.
*/
public ApiFuture<String> createCustomTokenAsync(
@NonNull String uid, @Nullable Map<String, Object> developerClaims) {
return createCustomTokenOp(uid, developerClaims).callAsync(firebaseApp);
}
private CallableOperation<String, FirebaseAuthException> createCustomTokenOp(
final String uid, final Map<String, Object> developerClaims) {
checkArgument(!Strings.isNullOrEmpty(uid), "uid must not be null or empty");
final FirebaseTokenFactory tokenFactory = this.tokenFactory.get();
return new CallableOperation<String, FirebaseAuthException>() {
@Override
public String execute() throws FirebaseAuthException {
return tokenFactory.createSignedCustomAuthTokenForUser(uid, developerClaims);
}
};
}
/**
* Creates a new Firebase session cookie from the given ID token and options. The returned JWT can
* be set as a server-side session cookie with a custom cookie policy.
*
* @param idToken The Firebase ID token to exchange for a session cookie.
* @param options Additional options required to create the cookie.
* @return A Firebase session cookie string.
* @throws IllegalArgumentException If the ID token is null or empty, or if options is null.
* @throws FirebaseAuthException If an error occurs while generating the session cookie.
*/
public String createSessionCookie(@NonNull String idToken, @NonNull SessionCookieOptions options)
throws FirebaseAuthException {
return createSessionCookieOp(idToken, options).call();
}
/**
* Similar to {@link #createSessionCookie(String, SessionCookieOptions)} but performs the
* operation asynchronously.
*
* @param idToken The Firebase ID token to exchange for a session cookie.
* @param options Additional options required to create the cookie.
* @return An {@code ApiFuture} which will complete successfully with a session cookie string. If
* an error occurs while generating the cookie or if the specified ID token is invalid, the
* future throws a {@link FirebaseAuthException}.
* @throws IllegalArgumentException If the ID token is null or empty, or if options is null.
*/
public ApiFuture<String> createSessionCookieAsync(
@NonNull String idToken, @NonNull SessionCookieOptions options) {
return createSessionCookieOp(idToken, options).callAsync(firebaseApp);
}
private CallableOperation<String, FirebaseAuthException> createSessionCookieOp(
final String idToken, final SessionCookieOptions options) {
checkArgument(!Strings.isNullOrEmpty(idToken), "idToken must not be null or empty");
checkNotNull(options, "options must not be null");
final FirebaseUserManager userManager = getUserManager();
return new CallableOperation<String, FirebaseAuthException>() {
@Override
protected String execute() throws FirebaseAuthException {
return userManager.createSessionCookie(idToken, options);
}
};
}
/**
* Parses and verifies a Firebase ID Token.
*
* <p>A Firebase application can identify itself to a trusted backend server by sending its
* Firebase ID Token (accessible via the {@code getToken} API in the Firebase Authentication
* client) with its requests. The backend server can then use the {@code verifyIdToken()} method
* to verify that the token is valid. This method ensures that the token is correctly signed, has
* not expired, and it was issued to the Firebase project associated with this {@link
* FirebaseAuth} instance.
*
* <p>This method does not check whether a token has been revoked. Use {@link
* #verifyIdToken(String, boolean)} to perform an additional revocation check.
*
* @param idToken A Firebase ID token string to parse and verify.
* @return A {@link FirebaseToken} representing the verified and decoded token.
* @throws IllegalArgumentException If the token is null, empty, or if the {@link FirebaseApp}
* instance does not have a project ID associated with it.
* @throws FirebaseAuthException If an error occurs while parsing or validating the token.
*/
public FirebaseToken verifyIdToken(@NonNull String idToken) throws FirebaseAuthException {
return verifyIdToken(idToken, false);
}
/**
* Parses and verifies a Firebase ID Token.
*
* <p>A Firebase application can identify itself to a trusted backend server by sending its
* Firebase ID Token (accessible via the {@code getToken} API in the Firebase Authentication
* client) with its requests. The backend server can then use the {@code verifyIdToken()} method
* to verify that the token is valid. This method ensures that the token is correctly signed, has
* not expired, and it was issued to the Firebase project associated with this {@link
* FirebaseAuth} instance.
*
* <p>If {@code checkRevoked} is set to true, this method performs an additional check to see if
* the ID token has been revoked since it was issues. This requires making an additional remote
* API call.
*
* @param idToken A Firebase ID token string to parse and verify.
* @param checkRevoked A boolean denoting whether to check if the tokens were revoked or if
* the user is disabled.
* @return A {@link FirebaseToken} representing the verified and decoded token.
* @throws IllegalArgumentException If the token is null, empty, or if the {@link FirebaseApp}
* instance does not have a project ID associated with it.
* @throws FirebaseAuthException If an error occurs while parsing or validating the token, or if
* the user is disabled.
*/
public FirebaseToken verifyIdToken(@NonNull String idToken, boolean checkRevoked)
throws FirebaseAuthException {
return verifyIdTokenOp(idToken, checkRevoked).call();
}
/**
* Similar to {@link #verifyIdToken(String)} but performs the operation asynchronously.
*
* @param idToken A Firebase ID Token to verify and parse.
* @return An {@code ApiFuture} which will complete successfully with the parsed token, or
* unsuccessfully with a {@link FirebaseAuthException}.
* @throws IllegalArgumentException If the token is null, empty, or if the {@link FirebaseApp}
* instance does not have a project ID associated with it.
*/
public ApiFuture<FirebaseToken> verifyIdTokenAsync(@NonNull String idToken) {
return verifyIdTokenAsync(idToken, false);
}
/**
* Similar to {@link #verifyIdToken(String, boolean)} but performs the operation asynchronously.
*
* @param idToken A Firebase ID Token to verify and parse.
* @param checkRevoked A boolean denoting whether to check if the tokens were revoked.
* @return An {@code ApiFuture} which will complete successfully with the parsed token, or
* unsuccessfully with a {@link FirebaseAuthException}.
* @throws IllegalArgumentException If the token is null, empty, or if the {@link FirebaseApp}
* instance does not have a project ID associated with it.
*/
public ApiFuture<FirebaseToken>
verifyIdTokenAsync(@NonNull String idToken, boolean checkRevoked) {
return verifyIdTokenOp(idToken, checkRevoked).callAsync(firebaseApp);
}
private CallableOperation<FirebaseToken, FirebaseAuthException> verifyIdTokenOp(
final String idToken, final boolean checkRevoked) {
checkArgument(!Strings.isNullOrEmpty(idToken), "ID token must not be null or empty");
final FirebaseTokenVerifier verifier = getIdTokenVerifier(checkRevoked);
return new CallableOperation<FirebaseToken, FirebaseAuthException>() {
@Override
protected FirebaseToken execute() throws FirebaseAuthException {
return verifier.verifyToken(idToken);
}
};
}
@VisibleForTesting
FirebaseTokenVerifier getIdTokenVerifier(boolean checkRevoked) {
FirebaseTokenVerifier verifier = idTokenVerifier.get();
if (checkRevoked || isEmulatorMode()) {
FirebaseUserManager userManager = getUserManager();
verifier = RevocationCheckDecorator.decorateIdTokenVerifier(verifier, userManager);
}
return verifier;
}
/**
* Parses and verifies a Firebase session cookie.
*
* <p>If verified successfully, returns a parsed version of the cookie from which the UID and the
* other claims can be read. If the cookie is invalid, throws a {@link FirebaseAuthException}.
*
* <p>This method does not check whether the cookie has been revoked. See {@link
* #verifySessionCookie(String, boolean)}.
*
* @param cookie A Firebase session cookie string to verify and parse.
* @return A {@link FirebaseToken} representing the verified and decoded cookie.
*/
public FirebaseToken verifySessionCookie(String cookie) throws FirebaseAuthException {
return verifySessionCookie(cookie, false);
}
/**
* Parses and verifies a Firebase session cookie.
*
* <p>If {@code checkRevoked} is true, additionally verifies that the cookie has not been revoked.
*
* <p>If verified successfully, returns a parsed version of the cookie from which the UID and the
* other claims can be read. If the cookie is invalid or has been revoked while {@code
* checkRevoked} is true, throws a {@link FirebaseAuthException}.
*
* @param cookie A Firebase session cookie string to verify and parse.
* @param checkRevoked A boolean indicating whether to check if the cookie was explicitly revoked
* or if the user is disabled.
* @return A {@link FirebaseToken} representing the verified and decoded cookie.
* @throws FirebaseAuthException If an error occurs while parsing or validating the token, or if
* the user is disabled.
*/
public FirebaseToken verifySessionCookie(String cookie, boolean checkRevoked)
throws FirebaseAuthException {
return verifySessionCookieOp(cookie, checkRevoked).call();
}
/**
* Similar to {@link #verifySessionCookie(String)} but performs the operation asynchronously.
*
* @param cookie A Firebase session cookie string to verify and parse.
* @return An {@code ApiFuture} which will complete successfully with the parsed cookie, or
* unsuccessfully with the failure Exception.
*/
public ApiFuture<FirebaseToken> verifySessionCookieAsync(String cookie) {
return verifySessionCookieAsync(cookie, false);
}
/**
* Similar to {@link #verifySessionCookie(String, boolean)} but performs the operation
* asynchronously.
*
* @param cookie A Firebase session cookie string to verify and parse.
* @param checkRevoked A boolean indicating whether to check if the cookie was explicitly revoked.
* @return An {@code ApiFuture} which will complete successfully with the parsed cookie, or
* unsuccessfully with the failure Exception.
*/
public ApiFuture<FirebaseToken> verifySessionCookieAsync(String cookie, boolean checkRevoked) {
return verifySessionCookieOp(cookie, checkRevoked).callAsync(firebaseApp);
}
private CallableOperation<FirebaseToken, FirebaseAuthException> verifySessionCookieOp(
final String cookie, final boolean checkRevoked) {
checkArgument(!Strings.isNullOrEmpty(cookie), "Session cookie must not be null or empty");
final FirebaseTokenVerifier sessionCookieVerifier = getSessionCookieVerifier(checkRevoked);
return new CallableOperation<FirebaseToken, FirebaseAuthException>() {
@Override
public FirebaseToken execute() throws FirebaseAuthException {
return sessionCookieVerifier.verifyToken(cookie);
}
};
}
@VisibleForTesting
FirebaseTokenVerifier getSessionCookieVerifier(boolean checkRevoked) {
FirebaseTokenVerifier verifier = cookieVerifier.get();
if (checkRevoked || isEmulatorMode()) {
FirebaseUserManager userManager = getUserManager();
verifier = RevocationCheckDecorator.decorateSessionCookieVerifier(verifier, userManager);
}
return verifier;
}
/**
* Revokes all refresh tokens for the specified user.
*
* <p>Updates the user's tokensValidAfterTimestamp to the current UTC time expressed in
* milliseconds since the epoch and truncated to 1 second accuracy. It is important that the
* server on which this is called has its clock set correctly and synchronized.
*
* <p>While this will revoke all sessions for a specified user and disable any new ID tokens for
* existing sessions from getting minted, existing ID tokens may remain active until their natural
* expiration (one hour). To verify that ID tokens are revoked, use {@link
* #verifyIdTokenAsync(String, boolean)}.
*
* @param uid The user id for which tokens are revoked.
* @throws IllegalArgumentException If the user ID is null or empty.
* @throws FirebaseAuthException If an error occurs while revoking tokens.
*/
public void revokeRefreshTokens(@NonNull String uid) throws FirebaseAuthException {
revokeRefreshTokensOp(uid).call();
}
/**
* Similar to {@link #revokeRefreshTokens(String)} but performs the operation asynchronously.
*
* @param uid The user id for which tokens are revoked.
* @return An {@code ApiFuture} which will complete successfully or fail with a {@link
* FirebaseAuthException} in the event of an error.
* @throws IllegalArgumentException If the user ID is null or empty.
*/
public ApiFuture<Void> revokeRefreshTokensAsync(@NonNull String uid) {
return revokeRefreshTokensOp(uid).callAsync(firebaseApp);
}
private CallableOperation<Void, FirebaseAuthException> revokeRefreshTokensOp(final String uid) {
checkArgument(!Strings.isNullOrEmpty(uid), "uid must not be null or empty");
final FirebaseUserManager userManager = getUserManager();
return new CallableOperation<Void, FirebaseAuthException>() {
@Override
protected Void execute() throws FirebaseAuthException {
int currentTimeSeconds = (int) (System.currentTimeMillis() / 1000);
UserRecord.UpdateRequest request =
new UserRecord.UpdateRequest(uid).setValidSince(currentTimeSeconds);
userManager.updateUser(request, jsonFactory);
return null;
}
};
}
/**
* Gets the user data corresponding to the specified user ID.
*
* @param uid A user ID string.
* @return A {@link UserRecord} instance.
* @throws IllegalArgumentException If the user ID string is null or empty.
* @throws FirebaseAuthException If an error occurs while retrieving user data.
*/
public UserRecord getUser(@NonNull String uid) throws FirebaseAuthException {
return getUserOp(uid).call();
}
/**
* Similar to {@link #getUser(String)} but performs the operation asynchronously.
*
* @param uid A user ID string.
* @return An {@code ApiFuture} which will complete successfully with a {@link UserRecord}
* instance. If an error occurs while retrieving user data or if the specified user ID does
* not exist, the future throws a {@link FirebaseAuthException}.
* @throws IllegalArgumentException If the user ID string is null or empty.
*/
public ApiFuture<UserRecord> getUserAsync(@NonNull String uid) {
return getUserOp(uid).callAsync(firebaseApp);
}
private CallableOperation<UserRecord, FirebaseAuthException> getUserOp(final String uid) {
checkArgument(!Strings.isNullOrEmpty(uid), "uid must not be null or empty");
final FirebaseUserManager userManager = getUserManager();
return new CallableOperation<UserRecord, FirebaseAuthException>() {
@Override
protected UserRecord execute() throws FirebaseAuthException {
return userManager.getUserById(uid);
}
};
}
/**
* Gets the user data corresponding to the specified user email.
*
* @param email A user email address string.
* @return A {@link UserRecord} instance.
* @throws IllegalArgumentException If the email is null or empty.
* @throws FirebaseAuthException If an error occurs while retrieving user data.
*/
public UserRecord getUserByEmail(@NonNull String email) throws FirebaseAuthException {
return getUserByEmailOp(email).call();
}
/**
* Similar to {@link #getUserByEmail(String)} but performs the operation asynchronously.
*
* @param email A user email address string.
* @return An {@code ApiFuture} which will complete successfully with a {@link UserRecord}
* instance. If an error occurs while retrieving user data or if the email address does not
* correspond to a user, the future throws a {@link FirebaseAuthException}.
* @throws IllegalArgumentException If the email is null or empty.
*/
public ApiFuture<UserRecord> getUserByEmailAsync(@NonNull String email) {
return getUserByEmailOp(email).callAsync(firebaseApp);
}
private CallableOperation<UserRecord, FirebaseAuthException> getUserByEmailOp(
final String email) {
checkArgument(!Strings.isNullOrEmpty(email), "email must not be null or empty");
final FirebaseUserManager userManager = getUserManager();
return new CallableOperation<UserRecord, FirebaseAuthException>() {
@Override
protected UserRecord execute() throws FirebaseAuthException {
return userManager.getUserByEmail(email);
}
};
}
/**
* Gets the user data corresponding to the specified user phone number.
*
* @param phoneNumber A user phone number string.
* @return A a {@link UserRecord} instance.
* @throws IllegalArgumentException If the phone number is null or empty.
* @throws FirebaseAuthException If an error occurs while retrieving user data.
*/
public UserRecord getUserByPhoneNumber(@NonNull String phoneNumber) throws FirebaseAuthException {
return getUserByPhoneNumberOp(phoneNumber).call();
}
/**
* Gets the user data corresponding to the specified user phone number.
*
* @param phoneNumber A user phone number string.
* @return An {@code ApiFuture} which will complete successfully with a {@link UserRecord}
* instance. If an error occurs while retrieving user data or if the phone number does not
* correspond to a user, the future throws a {@link FirebaseAuthException}.
* @throws IllegalArgumentException If the phone number is null or empty.
*/
public ApiFuture<UserRecord> getUserByPhoneNumberAsync(@NonNull String phoneNumber) {
return getUserByPhoneNumberOp(phoneNumber).callAsync(firebaseApp);
}
private CallableOperation<UserRecord, FirebaseAuthException> getUserByPhoneNumberOp(
final String phoneNumber) {
checkArgument(!Strings.isNullOrEmpty(phoneNumber), "phone number must not be null or empty");
final FirebaseUserManager userManager = getUserManager();
return new CallableOperation<UserRecord, FirebaseAuthException>() {
@Override
protected UserRecord execute() throws FirebaseAuthException {
return userManager.getUserByPhoneNumber(phoneNumber);
}
};
}
/**
* Gets the user data for the user corresponding to a given provider ID.
*
* @param providerId Identifier for the given federated provider: for example,
* "google.com" for the Google provider.
* @param uid The user identifier with the given provider.
* @return A {@link UserRecord} instance.
* @throws IllegalArgumentException If the uid is null or empty, or if
* the providerId is null, empty, or does not belong to a federated provider.
* @throws FirebaseAuthException If an error occurs while retrieving user data.
*/
public UserRecord getUserByProviderUid(
@NonNull String providerId, @NonNull String uid) throws FirebaseAuthException {
return getUserByProviderUidOp(providerId, uid).call();
}
/**
* Gets the user data for the user corresponding to a given provider ID.
*
* @param providerId Identifer for the given federated provider: for example,
* "google.com" for the Google provider.
* @param uid The user identifier with the given provider.
* @return An {@code ApiFuture} which will complete successfully with a {@link UserRecord}
* instance. If an error occurs while retrieving user data or if the provider ID and uid
* do not correspond to a user, the future throws a {@link FirebaseAuthException}.
* @throws IllegalArgumentException If the uid is null or empty, or if
* the provider ID is null, empty, or does not belong to a federated provider.
*/
public ApiFuture<UserRecord> getUserByProviderUidAsync(
@NonNull String providerId, @NonNull String uid) {
return getUserByProviderUidOp(providerId, uid).callAsync(firebaseApp);
}
private CallableOperation<UserRecord, FirebaseAuthException> getUserByProviderUidOp(
final String providerId, final String uid) {
checkArgument(!Strings.isNullOrEmpty(providerId), "providerId must not be null or empty");
checkArgument(!Strings.isNullOrEmpty(uid), "uid must not be null or empty");
// Although we don't really advertise it, we want to also handle
// non-federated idps with this call. So if we detect one of them, we'll
// reroute this request appropriately.
if ("phone".equals(providerId)) {
return this.getUserByPhoneNumberOp(uid);
}
if ("email".equals(providerId)) {
return this.getUserByEmailOp(uid);
}
checkArgument(!providerId.equals("password")
&& !providerId.equals("anonymous"), "providerId must belong to a federated provider");
final FirebaseUserManager userManager = getUserManager();
return new CallableOperation<UserRecord, FirebaseAuthException>() {
@Override
protected UserRecord execute() throws FirebaseAuthException {
return userManager.getUserByProviderUid(providerId, uid);
}
};
}
/**
* Gets a page of users starting from the specified {@code pageToken}. Page size is limited to
* 1000 users.
*
* @param pageToken A non-empty page token string, or null to retrieve the first page of users.
* @return A {@link ListUsersPage} instance.
* @throws IllegalArgumentException If the specified page token is empty.
* @throws FirebaseAuthException If an error occurs while retrieving user data.
*/
public ListUsersPage listUsers(@Nullable String pageToken) throws FirebaseAuthException {
return listUsers(pageToken, FirebaseUserManager.MAX_LIST_USERS_RESULTS);
}
/**
* Gets a page of users starting from the specified {@code pageToken}.
*
* @param pageToken A non-empty page token string, or null to retrieve the first page of users.
* @param maxResults Maximum number of users to include in the returned page. This may not exceed
* 1000.
* @return A {@link ListUsersPage} instance.
* @throws IllegalArgumentException If the specified page token is empty, or max results value is
* invalid.
* @throws FirebaseAuthException If an error occurs while retrieving user data.
*/
public ListUsersPage listUsers(@Nullable String pageToken, int maxResults)
throws FirebaseAuthException {
return listUsersOp(pageToken, maxResults).call();
}
/**
* Similar to {@link #listUsers(String)} but performs the operation asynchronously.
*
* @param pageToken A non-empty page token string, or null to retrieve the first page of users.
* @return An {@code ApiFuture} which will complete successfully with a {@link ListUsersPage}
* instance. If an error occurs while retrieving user data, the future throws an exception.
* @throws IllegalArgumentException If the specified page token is empty.
*/
public ApiFuture<ListUsersPage> listUsersAsync(@Nullable String pageToken) {
return listUsersAsync(pageToken, FirebaseUserManager.MAX_LIST_USERS_RESULTS);
}
/**
* Similar to {@link #listUsers(String, int)} but performs the operation asynchronously.
*
* @param pageToken A non-empty page token string, or null to retrieve the first page of users.
* @param maxResults Maximum number of users to include in the returned page. This may not exceed
* 1000.
* @return An {@code ApiFuture} which will complete successfully with a {@link ListUsersPage}
* instance. If an error occurs while retrieving user data, the future throws an exception.
* @throws IllegalArgumentException If the specified page token is empty, or max results value is
* invalid.
*/
public ApiFuture<ListUsersPage> listUsersAsync(@Nullable String pageToken, int maxResults) {
return listUsersOp(pageToken, maxResults).callAsync(firebaseApp);
}
private CallableOperation<ListUsersPage, FirebaseAuthException> listUsersOp(
@Nullable final String pageToken, final int maxResults) {
final FirebaseUserManager userManager = getUserManager();
final DefaultUserSource source = new DefaultUserSource(userManager, jsonFactory);
final ListUsersPage.Factory factory = new ListUsersPage.Factory(source, maxResults, pageToken);
return new CallableOperation<ListUsersPage, FirebaseAuthException>() {
@Override
protected ListUsersPage execute() throws FirebaseAuthException {
return factory.create();
}
};
}
/**
* Creates a new user account with the attributes contained in the specified {@link
* UserRecord.CreateRequest}.
*
* @param request A non-null {@link UserRecord.CreateRequest} instance.
* @return A {@link UserRecord} instance corresponding to the newly created account.
* @throws NullPointerException if the provided request is null.
* @throws FirebaseAuthException if an error occurs while creating the user account.
*/
public UserRecord createUser(@NonNull UserRecord.CreateRequest request)
throws FirebaseAuthException {
return createUserOp(request).call();
}
/**
* Similar to {@link #createUser} but performs the operation asynchronously.
*
* @param request A non-null {@link UserRecord.CreateRequest} instance.
* @return An {@code ApiFuture} which will complete successfully with a {@link UserRecord}
* instance corresponding to the newly created account. If an error occurs while creating the
* user account, the future throws a {@link FirebaseAuthException}.
* @throws NullPointerException if the provided request is null.
*/
public ApiFuture<UserRecord> createUserAsync(@NonNull UserRecord.CreateRequest request) {
return createUserOp(request).callAsync(firebaseApp);
}
private CallableOperation<UserRecord, FirebaseAuthException> createUserOp(
final UserRecord.CreateRequest request) {
checkNotNull(request, "create request must not be null");
final FirebaseUserManager userManager = getUserManager();
return new CallableOperation<UserRecord, FirebaseAuthException>() {
@Override
protected UserRecord execute() throws FirebaseAuthException {
String uid = userManager.createUser(request);
return userManager.getUserById(uid);
}
};
}
/**
* Updates an existing user account with the attributes contained in the specified {@link
* UserRecord.UpdateRequest}.
*
* @param request A non-null {@link UserRecord.UpdateRequest} instance.
* @return A {@link UserRecord} instance corresponding to the updated user account.
* @throws NullPointerException if the provided update request is null.
* @throws FirebaseAuthException if an error occurs while updating the user account.
*/
public UserRecord updateUser(@NonNull UserRecord.UpdateRequest request)
throws FirebaseAuthException {
return updateUserOp(request).call();
}
/**
* Similar to {@link #updateUser} but performs the operation asynchronously.
*
* @param request A non-null {@link UserRecord.UpdateRequest} instance.
* @return An {@code ApiFuture} which will complete successfully with a {@link UserRecord}
* instance corresponding to the updated user account. If an error occurs while updating the
* user account, the future throws a {@link FirebaseAuthException}.
*/
public ApiFuture<UserRecord> updateUserAsync(@NonNull UserRecord.UpdateRequest request) {
return updateUserOp(request).callAsync(firebaseApp);
}
private CallableOperation<UserRecord, FirebaseAuthException> updateUserOp(
final UserRecord.UpdateRequest request) {
checkNotNull(request, "update request must not be null");
final FirebaseUserManager userManager = getUserManager();
return new CallableOperation<UserRecord, FirebaseAuthException>() {
@Override
protected UserRecord execute() throws FirebaseAuthException {
userManager.updateUser(request, jsonFactory);
return userManager.getUserById(request.getUid());
}
};
}
/**
* Sets the specified custom claims on an existing user account. A null claims value removes any
* claims currently set on the user account. The claims should serialize into a valid JSON string.
* The serialized claims must not be larger than 1000 characters.
*
* @param uid A user ID string.
* @param claims A map of custom claims or null.
* @throws FirebaseAuthException If an error occurs while updating custom claims.
* @throws IllegalArgumentException If the user ID string is null or empty, or the claims payload
* is invalid or too large.
*/
public void setCustomUserClaims(@NonNull String uid, @Nullable Map<String, Object> claims)
throws FirebaseAuthException {
setCustomUserClaimsOp(uid, claims).call();
}
/**
* @deprecated Use {@link #setCustomUserClaims(String, Map)} instead.
*/
public void setCustomClaims(@NonNull String uid, @Nullable Map<String, Object> claims)
throws FirebaseAuthException {
setCustomUserClaims(uid, claims);
}
/**
* Similar to {@link #setCustomUserClaims(String, Map)} but performs the operation asynchronously.
*
* @param uid A user ID string.
* @param claims A map of custom claims or null.
* @return An {@code ApiFuture} which will complete successfully when the user account has been
* updated. If an error occurs while deleting the user account, the future throws a {@link
* FirebaseAuthException}.
* @throws IllegalArgumentException If the user ID string is null or empty.
*/
public ApiFuture<Void> setCustomUserClaimsAsync(
@NonNull String uid, @Nullable Map<String, Object> claims) {
return setCustomUserClaimsOp(uid, claims).callAsync(firebaseApp);
}
private CallableOperation<Void, FirebaseAuthException> setCustomUserClaimsOp(
final String uid, final Map<String, Object> claims) {
checkArgument(!Strings.isNullOrEmpty(uid), "uid must not be null or empty");
final FirebaseUserManager userManager = getUserManager();
return new CallableOperation<Void, FirebaseAuthException>() {
@Override
protected Void execute() throws FirebaseAuthException {
final UserRecord.UpdateRequest request =
new UserRecord.UpdateRequest(uid).setCustomClaims(claims);
userManager.updateUser(request, jsonFactory);
return null;
}
};
}
/**
* Deletes the user identified by the specified user ID.
*
* @param uid A user ID string.
* @throws IllegalArgumentException If the user ID string is null or empty.
* @throws FirebaseAuthException If an error occurs while deleting the user.
*/
public void deleteUser(@NonNull String uid) throws FirebaseAuthException {
deleteUserOp(uid).call();
}
/**
* Similar to {@link #deleteUser(String)} but performs the operation asynchronously.
*
* @param uid A user ID string.
* @return An {@code ApiFuture} which will complete successfully when the specified user account
* has been deleted. If an error occurs while deleting the user account, the future throws a
* {@link FirebaseAuthException}.
* @throws IllegalArgumentException If the user ID string is null or empty.
*/
public ApiFuture<Void> deleteUserAsync(String uid) {
return deleteUserOp(uid).callAsync(firebaseApp);
}
private CallableOperation<Void, FirebaseAuthException> deleteUserOp(final String uid) {
checkArgument(!Strings.isNullOrEmpty(uid), "uid must not be null or empty");
final FirebaseUserManager userManager = getUserManager();
return new CallableOperation<Void, FirebaseAuthException>() {
@Override
protected Void execute() throws FirebaseAuthException {
userManager.deleteUser(uid);
return null;
}
};
}
/**
* Imports the provided list of users into Firebase Auth. At most 1000 users can be imported at a
* time. This operation is optimized for bulk imports and will ignore checks on identifier
* uniqueness which could result in duplications.
*
* <p>{@link UserImportOptions} is required to import users with passwords. See {@link
* #importUsers(List, UserImportOptions)}.
*
* @param users A non-empty list of users to be imported. Length must not exceed 1000.
* @return A {@link UserImportResult} instance.
* @throws IllegalArgumentException If the users list is null, empty or has more than 1000
* elements. Or if at least one user specifies a password.
* @throws FirebaseAuthException If an error occurs while importing users.
*/
public UserImportResult importUsers(List<ImportUserRecord> users) throws FirebaseAuthException {
return importUsers(users, null);
}
/**
* Imports the provided list of users into Firebase Auth. At most 1000 users can be imported at a
* time. This operation is optimized for bulk imports and will ignore checks on identifier
* uniqueness which could result in duplications.
*
* @param users A non-empty list of users to be imported. Length must not exceed 1000.
* @param options a {@link UserImportOptions} instance or null. Required when importing users with
* passwords.
* @return A {@link UserImportResult} instance.
* @throws IllegalArgumentException If the users list is null, empty or has more than 1000
* elements. Or if at least one user specifies a password, and options is null.
* @throws FirebaseAuthException If an error occurs while importing users.
*/
public UserImportResult importUsers(
List<ImportUserRecord> users, @Nullable UserImportOptions options)
throws FirebaseAuthException {
return importUsersOp(users, options).call();
}
/**
* Similar to {@link #importUsers(List)} but performs the operation asynchronously.
*
* @param users A non-empty list of users to be imported. Length must not exceed 1000.
* @return An {@code ApiFuture} which will complete successfully when the user accounts are
* imported. If an error occurs while importing the users, the future throws a {@link
* FirebaseAuthException}.
* @throws IllegalArgumentException If the users list is null, empty or has more than 1000
* elements. Or if at least one user specifies a password.
*/
public ApiFuture<UserImportResult> importUsersAsync(List<ImportUserRecord> users) {
return importUsersAsync(users, null);
}
/**
* Similar to {@link #importUsers(List, UserImportOptions)} but performs the operation
* asynchronously.
*
* @param users A non-empty list of users to be imported. Length must not exceed 1000.
* @param options a {@link UserImportOptions} instance or null. Required when importing users with
* passwords.
* @return An {@code ApiFuture} which will complete successfully when the user accounts are
* imported. If an error occurs while importing the users, the future throws a {@link
* FirebaseAuthException}.
* @throws IllegalArgumentException If the users list is null, empty or has more than 1000
* elements. Or if at least one user specifies a password, and options is null.
*/
public ApiFuture<UserImportResult> importUsersAsync(
List<ImportUserRecord> users, @Nullable UserImportOptions options) {
return importUsersOp(users, options).callAsync(firebaseApp);
}
private CallableOperation<UserImportResult, FirebaseAuthException> importUsersOp(
final List<ImportUserRecord> users, final UserImportOptions options) {
final UserImportRequest request = new UserImportRequest(users, options, jsonFactory);
final FirebaseUserManager userManager = getUserManager();
return new CallableOperation<UserImportResult, FirebaseAuthException>() {
@Override
protected UserImportResult execute() throws FirebaseAuthException {
return userManager.importUsers(request);
}
};
}
/**
* Gets the user data corresponding to the specified identifiers.
*
* <p>There are no ordering guarantees; in particular, the nth entry in the users result list is
* not guaranteed to correspond to the nth entry in the input parameters list.
*
* <p>A maximum of 100 identifiers may be specified. If more than 100 identifiers are
* supplied, this method throws an {@code IllegalArgumentException}.
*
* @param identifiers The identifiers used to indicate which user records should be returned. Must
* have 100 or fewer entries.
* @return The corresponding user records.
* @throws IllegalArgumentException If any of the identifiers are invalid or if more than 100
* identifiers are specified.
* @throws NullPointerException If the identifiers parameter is null.
* @throws FirebaseAuthException If an error occurs while retrieving user data.
*/
public GetUsersResult getUsers(@NonNull Collection<UserIdentifier> identifiers)
throws FirebaseAuthException {
return getUsersOp(identifiers).call();
}
/**
* Gets the user data corresponding to the specified identifiers.
*
* <p>There are no ordering guarantees; in particular, the nth entry in the users result list is
* not guaranteed to correspond to the nth entry in the input parameters list.
*
* <p>A maximum of 100 identifiers may be specified. If more than 100 identifiers are
* supplied, this method throws an {@code IllegalArgumentException}.
*
* @param identifiers The identifiers used to indicate which user records should be returned.
* Must have 100 or fewer entries.
* @return An {@code ApiFuture} that resolves to the corresponding user records.
* @throws IllegalArgumentException If any of the identifiers are invalid or if more than 100
* identifiers are specified.
* @throws NullPointerException If the identifiers parameter is null.
*/
public ApiFuture<GetUsersResult> getUsersAsync(@NonNull Collection<UserIdentifier> identifiers) {
return getUsersOp(identifiers).callAsync(firebaseApp);
}
private CallableOperation<GetUsersResult, FirebaseAuthException> getUsersOp(
@NonNull final Collection<UserIdentifier> identifiers) {
checkNotNull(identifiers, "identifiers must not be null");
checkArgument(identifiers.size() <= FirebaseUserManager.MAX_GET_ACCOUNTS_BATCH_SIZE,
"identifiers parameter must have <= " + FirebaseUserManager.MAX_GET_ACCOUNTS_BATCH_SIZE
+ " entries.");
final FirebaseUserManager userManager = getUserManager();
return new CallableOperation<GetUsersResult, FirebaseAuthException>() {
@Override
protected GetUsersResult execute() throws FirebaseAuthException {
Set<UserRecord> users = userManager.getAccountInfo(identifiers);
Set<UserIdentifier> notFound = new HashSet<>();
for (UserIdentifier id : identifiers) {
if (!isUserFound(id, users)) {
notFound.add(id);
}
}
return new GetUsersResult(users, notFound);