-
Notifications
You must be signed in to change notification settings - Fork 548
/
CognitoUser.java
4081 lines (3834 loc) · 186 KB
/
CognitoUser.java
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 2013-2019 Amazon.com,
* Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Amazon Software License (the "License").
* You may not use this file except in compliance with the
* License. A copy of the License is located at
*
* http://aws.amazon.com/asl/
*
* or in the "license" file accompanying this file. This file is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, express or implied. See the License
* for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.mobileconnectors.cognitoidentityprovider;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationContinuation;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.AuthenticationDetails;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.ChallengeContinuation;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.ChooseMfaContinuation;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.ForgotPasswordContinuation;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.MultiFactorAuthenticationContinuation;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.NewPasswordContinuation;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.RegisterMfaContinuation;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.VerifyMfaContinuation;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.CognitoInternalErrorException;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.CognitoNotAuthorizedException;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.exceptions.CognitoParameterInvalidException;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.AuthenticationHandler;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.DevicesHandler;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.ForgotPasswordHandler;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GenericHandler;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.GetDetailsHandler;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.RegisterMfaHandler;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.UpdateAttributesHandler;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.VerificationHandler;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.tokens.CognitoAccessToken;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.tokens.CognitoIdToken;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.tokens.CognitoRefreshToken;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.util.CognitoDeviceHelper;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.util.CognitoJWTParser;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.util.CognitoSecretHash;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.util.CognitoServiceConstants;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.util.Hkdf;
import com.amazonaws.services.cognitoidentityprovider.AmazonCognitoIdentityProvider;
import com.amazonaws.services.cognitoidentityprovider.model.AnalyticsMetadataType;
import com.amazonaws.services.cognitoidentityprovider.model.AssociateSoftwareTokenRequest;
import com.amazonaws.services.cognitoidentityprovider.model.AssociateSoftwareTokenResult;
import com.amazonaws.services.cognitoidentityprovider.model.AttributeType;
import com.amazonaws.services.cognitoidentityprovider.model.AuthenticationResultType;
import com.amazonaws.services.cognitoidentityprovider.model.ChangePasswordRequest;
import com.amazonaws.services.cognitoidentityprovider.model.CodeDeliveryDetailsType;
import com.amazonaws.services.cognitoidentityprovider.model.ConfirmDeviceRequest;
import com.amazonaws.services.cognitoidentityprovider.model.ConfirmDeviceResult;
import com.amazonaws.services.cognitoidentityprovider.model.ConfirmForgotPasswordRequest;
import com.amazonaws.services.cognitoidentityprovider.model.ConfirmSignUpRequest;
import com.amazonaws.services.cognitoidentityprovider.model.DeleteUserAttributesRequest;
import com.amazonaws.services.cognitoidentityprovider.model.DeleteUserRequest;
import com.amazonaws.services.cognitoidentityprovider.model.DeviceSecretVerifierConfigType;
import com.amazonaws.services.cognitoidentityprovider.model.DeviceType;
import com.amazonaws.services.cognitoidentityprovider.model.ForgotPasswordRequest;
import com.amazonaws.services.cognitoidentityprovider.model.ForgotPasswordResult;
import com.amazonaws.services.cognitoidentityprovider.model.GetUserAttributeVerificationCodeRequest;
import com.amazonaws.services.cognitoidentityprovider.model.GetUserAttributeVerificationCodeResult;
import com.amazonaws.services.cognitoidentityprovider.model.GetUserRequest;
import com.amazonaws.services.cognitoidentityprovider.model.GetUserResult;
import com.amazonaws.services.cognitoidentityprovider.model.GlobalSignOutRequest;
import com.amazonaws.services.cognitoidentityprovider.model.InitiateAuthRequest;
import com.amazonaws.services.cognitoidentityprovider.model.InitiateAuthResult;
import com.amazonaws.services.cognitoidentityprovider.model.InvalidParameterException;
import com.amazonaws.services.cognitoidentityprovider.model.ListDevicesRequest;
import com.amazonaws.services.cognitoidentityprovider.model.ListDevicesResult;
import com.amazonaws.services.cognitoidentityprovider.model.NewDeviceMetadataType;
import com.amazonaws.services.cognitoidentityprovider.model.NotAuthorizedException;
import com.amazonaws.services.cognitoidentityprovider.model.ResendConfirmationCodeRequest;
import com.amazonaws.services.cognitoidentityprovider.model.ResendConfirmationCodeResult;
import com.amazonaws.services.cognitoidentityprovider.model.ResourceNotFoundException;
import com.amazonaws.services.cognitoidentityprovider.model.RespondToAuthChallengeRequest;
import com.amazonaws.services.cognitoidentityprovider.model.RespondToAuthChallengeResult;
import com.amazonaws.services.cognitoidentityprovider.model.RevokeTokenRequest;
import com.amazonaws.services.cognitoidentityprovider.model.RevokeTokenResult;
import com.amazonaws.services.cognitoidentityprovider.model.SMSMfaSettingsType;
import com.amazonaws.services.cognitoidentityprovider.model.SetUserMFAPreferenceRequest;
import com.amazonaws.services.cognitoidentityprovider.model.SetUserMFAPreferenceResult;
import com.amazonaws.services.cognitoidentityprovider.model.SetUserSettingsRequest;
import com.amazonaws.services.cognitoidentityprovider.model.SetUserSettingsResult;
import com.amazonaws.services.cognitoidentityprovider.model.SoftwareTokenMfaSettingsType;
import com.amazonaws.services.cognitoidentityprovider.model.UpdateUserAttributesRequest;
import com.amazonaws.services.cognitoidentityprovider.model.UpdateUserAttributesResult;
import com.amazonaws.services.cognitoidentityprovider.model.UserContextDataType;
import com.amazonaws.services.cognitoidentityprovider.model.UserNotFoundException;
import com.amazonaws.services.cognitoidentityprovider.model.VerifySoftwareTokenRequest;
import com.amazonaws.services.cognitoidentityprovider.model.VerifySoftwareTokenResponseType;
import com.amazonaws.services.cognitoidentityprovider.model.VerifySoftwareTokenResult;
import com.amazonaws.services.cognitoidentityprovider.model.VerifyUserAttributeRequest;
import com.amazonaws.services.cognitoidentityprovider.model.VerifyUserAttributeResult;
import com.amazonaws.util.Base64;
import com.amazonaws.util.StringUtils;
import com.amazonaws.logging.Log;
import com.amazonaws.logging.LogFactory;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* Represents a single Cognito User.
* <p>
* This class encapsulates all operations possible on a user and all tokens
* belonging to the user. The user tokens, as {@link CognitoUserSession}, are
* stored in SharedPreferences. Only the tokens belonging to the last
* successfully authenticated user are stored.
* </p>
*/
public class CognitoUser {
private static final Log LOGGER = LogFactory.getLog(CognitoUser.class);
private static final int SRP_RADIX = 16;
/**
* Application context.
*/
private final Context context;
/**
* CIP low-level client.
*/
private final AmazonCognitoIdentityProvider cognitoIdentityProviderClient;
/**
* Client ID for Your Identity Pool.
*/
private final String clientId;
/**
* Client secret generated for this {@code clientId}, this may be
* {@code null} if a secret is not generated for the {@code clientId}.
*/
private final String clientSecret;
/**
* userId for this user, this is mutable to allow the userId to be set
* during authentication. This can be the username (users' unique sign-in
* username) or an alias (if available, such as email or phone number).
*/
private String userId;
/**
* Username used for authentication process. This will be set from the
* results in the pre-auth API call.
*/
private String usernameInternal;
/**
* Device-key of this device, if available.
*/
private String deviceKey;
/**
* Reference to the {@link CognitoUserPool} to which this user belongs .
*/
private final CognitoUserPool pool;
/**
* Secret-Hash for this user-pool, this is mutable because userId is
* mutable.
*/
private String secretHash;
/**
* The current session.
*/
private CognitoUserSession cipSession;
/**
* Lock for getCachedSession.
*/
private static final Object GET_CACHED_SESSION_LOCK = new Object();
/**
* Constructs a new Cognito User from a Cognito user identity pool
* {@link CognitoUserPool} and userId.
*
* @param pool REQUIRED: Reference to {@link CognitoUserPool}, to which this
* user belongs.
* @param userId REQUIRED: userId of this user.
* @param clientId REQUIRED: Client-Id of the android app.
* @param clientSecret REQUIRED: Client secret assigned for this Client-Id.
* @param secretHash REQUIRED: Secret-Hash, calculated for this android app.
* @param client REQUIRED: Low level android client.
* @param context REQUIRED: Application context.
*/
protected CognitoUser(CognitoUserPool pool, String userId,
String clientId, String clientSecret, String secretHash,
AmazonCognitoIdentityProvider client, Context context) {
this.pool = pool;
this.context = context;
this.userId = userId;
this.cognitoIdentityProviderClient = client;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.secretHash = secretHash;
this.deviceKey = null;
cipSession = null;
}
/**
* Returns the userId of this user.
*
* @return userId.
*/
public String getUserId() {
return userId;
}
/**
* Returns the pool Id of this user.
*
* @return pool Id.
*/
public String getUserPoolId() {
return pool.getUserPoolId();
}
/**
* Method low-level client for Amazon Cognito Identity Provider.
*
* @return
*/
protected AmazonCognitoIdentityProvider getCognitoIdentityProviderClient() {
return cognitoIdentityProviderClient;
}
/**
* Confirms user registration in background.
* <p>
* Confirming a user is required to complete the user's registration. Any
* other operations on a user. are possible only after registration
* confirmation.
* </p>
*
* @param confirmationCode REQUIRED: Code sent to the phone-number or email
* used to register the user.
* @param forcedAliasCreation REQUIRED: This flag indicates if the
* confirmation should go-through in case of parameter
* contentions.
* @param callback REQUIRED: This is a reference to {@link GenericHandler}
* callback handler.
*/
public void confirmSignUpInBackground(final String confirmationCode,
final boolean forcedAliasCreation,
final GenericHandler callback) {
confirmSignUpInBackground(confirmationCode, forcedAliasCreation,
Collections.<String, String>emptyMap(), callback);
}
/**
* Confirms user registration in current thread.
* <p>
* Confirming a user is required to complete the user's registration. Any
* other operations on a user are possible only after registration
* confirmation. <b>Note:</b> This method will perform network operations.
* Calling this method in applications' main thread will cause Android to
* throw NetworkOnMainThreadException.
* </p>
*
* @param confirmationCode REQUIRED: Code sent to the phone-number or email
* used to register the user
* @param forcedAliasCreation REQUIRED: This flag indicates if the
* confirmation should go-through in case of parameter
* contentions.
* @param callback REQUIRED: This is a reference to {@link GenericHandler}
* callback handler
*/
public void confirmSignUp(String confirmationCode,
boolean forcedAliasCreation,
GenericHandler callback) {
confirmSignUp(confirmationCode, forcedAliasCreation, Collections.<String, String>emptyMap(), callback);
}
/**
* Confirms user registration in background.
* <p>
* Confirming a user is required to complete the user's registration. Any
* other operations on a user. are possible only after registration
* confirmation.
* </p>
*
* @param confirmationCode REQUIRED: Code sent to the phone-number or email
* used to register the user.
* @param forcedAliasCreation REQUIRED: This flag indicates if the
* confirmation should go-through in case of parameter
* contentions.
* @param clientMetadata A map of custom key-value pairs that is passed to the lambda function for
* custom workflow.
* @param callback REQUIRED: This is a reference to {@link GenericHandler}
* callback handler.
*/
public void confirmSignUpInBackground(final String confirmationCode,
final boolean forcedAliasCreation,
final Map<String, String> clientMetadata,
final GenericHandler callback) {
if (callback == null) {
throw new CognitoParameterInvalidException("callback is null");
}
new Thread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler(context.getMainLooper());
Runnable returnCallback;
try {
confirmSignUpInternal(confirmationCode, forcedAliasCreation, clientMetadata);
returnCallback = new Runnable() {
@Override
public void run() {
callback.onSuccess();
}
};
} catch (final Exception e) {
returnCallback = new Runnable() {
@Override
public void run() {
callback.onFailure(e);
}
};
}
handler.post(returnCallback);
}
}).start();
}
/**
* Confirms user registration in current thread.
* <p>
* Confirming a user is required to complete the user's registration. Any
* other operations on a user are possible only after registration
* confirmation. <b>Note:</b> This method will perform network operations.
* Calling this method in applications' main thread will cause Android to
* throw NetworkOnMainThreadException.
* </p>
*
* @param confirmationCode REQUIRED: Code sent to the phone-number or email
* used to register the user
* @param forcedAliasCreation REQUIRED: This flag indicates if the
* confirmation should go-through in case of parameter
* contentions.
* @param clientMetadata A map of custom key-value pairs that is passed to the lambda function for
* custom workflow.
* @param callback REQUIRED: This is a reference to {@link GenericHandler}
* callback handler
*/
public void confirmSignUp(String confirmationCode,
boolean forcedAliasCreation,
Map<String, String> clientMetadata,
GenericHandler callback) {
if (callback == null) {
throw new CognitoParameterInvalidException("callback is null");
}
try {
confirmSignUpInternal(confirmationCode, forcedAliasCreation, clientMetadata);
callback.onSuccess();
} catch (final Exception e) {
callback.onFailure(e);
}
}
/**
* Internal method to Confirm Registration.
*
* @param confirmationCode REQUIRED: Code to confirm this user.
* @param forcedAliasCreation REQUIRED: If set over-rides parameter
* contentions
* @param clientMetadata A map of custom key-value pairs that is passed to the lambda function for
* custom workflow.
*/
private void confirmSignUpInternal(final String confirmationCode,
final boolean forcedAliasCreation,
final Map<String, String> clientMetadata) {
final ConfirmSignUpRequest confirmUserRegistrationRequest = new ConfirmSignUpRequest()
.withClientId(clientId)
.withSecretHash(secretHash)
.withUsername(userId)
.withConfirmationCode(confirmationCode)
.withForceAliasCreation(forcedAliasCreation)
.withClientMetadata(clientMetadata)
.withUserContextData(getUserContextData());
final String pinpointEndpointId = pool.getPinpointEndpointId();
if (pinpointEndpointId != null) {
final AnalyticsMetadataType amd = new AnalyticsMetadataType();
amd.setAnalyticsEndpointId(pinpointEndpointId);
confirmUserRegistrationRequest.setAnalyticsMetadata(amd);
}
cognitoIdentityProviderClient.confirmSignUp(confirmUserRegistrationRequest);
}
/**
* Request to resend registration confirmation code for a user, in
* background.
*
* @param callback REQUIRED: {@link VerificationHandler} callback handler.
*/
public void resendConfirmationCodeInBackground(final VerificationHandler callback) {
resendConfirmationCodeInBackground(Collections.<String, String>emptyMap(), callback);
}
/**
* Request to resend registration confirmation code for a user, in
* background.
*
* @param clientMetadata A map of custom key-value pairs that is passed to the lambda function for
* custom workflow.
* @param callback REQUIRED: {@link VerificationHandler} callback handler.
*/
public void resendConfirmationCodeInBackground(
final Map<String, String> clientMetadata,
final VerificationHandler callback) {
if (callback == null) {
throw new CognitoParameterInvalidException("callback is null");
}
new Thread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler(context.getMainLooper());
Runnable returnCallback;
try {
final ResendConfirmationCodeResult resendConfirmationCodeResult =
resendConfirmationCodeInternal(clientMetadata);
returnCallback = new Runnable() {
@Override
public void run() {
callback.onSuccess(new CognitoUserCodeDeliveryDetails(
resendConfirmationCodeResult.getCodeDeliveryDetails()));
}
};
} catch (final Exception e) {
returnCallback = new Runnable() {
@Override
public void run() {
callback.onFailure(e);
}
};
}
handler.post(returnCallback);
}
}).start();
}
/**
* Request to resend registration confirmation code for a user, in current
* thread.
* <p>
* <b>Note:</b> This method will perform network operations. Calling this
* method in applications' main thread will cause Android to throw
* NetworkOnMainThreadException.
* </p>
*
* @param callback REQUIRED: {@link VerificationHandler} callback handler.
*/
public void resendConfirmationCode(final VerificationHandler callback) {
resendConfirmationCode(Collections.<String, String>emptyMap(), callback);
}
/**
* Request to resend registration confirmation code for a user, in current
* thread.
* <p>
* <b>Note:</b> This method will perform network operations. Calling this
* method in applications' main thread will cause Android to throw
* NetworkOnMainThreadException.
* </p>
*
* @param clientMetadata A map of custom key-value pairs that is passed to the lambda function for
* custom workflow.
* @param callback REQUIRED: {@link VerificationHandler} callback handler.
*/
public void resendConfirmationCode(
final Map<String, String> clientMetadata,
final VerificationHandler callback) {
if (callback == null) {
throw new CognitoParameterInvalidException("callback is null");
}
try {
final ResendConfirmationCodeResult resendConfirmationCodeResult =
resendConfirmationCodeInternal(clientMetadata);
callback.onSuccess(new CognitoUserCodeDeliveryDetails(
resendConfirmationCodeResult.getCodeDeliveryDetails()));
} catch (final Exception e) {
callback.onFailure(e);
}
}
/**
* Internal method to request registration code resend.
* @param clientMetadata A map of custom key-value pairs that is passed to the lambda function for
* custom workflow.
*/
private ResendConfirmationCodeResult resendConfirmationCodeInternal(final Map<String, String> clientMetadata) {
final ResendConfirmationCodeRequest resendConfirmationCodeRequest =
new ResendConfirmationCodeRequest()
.withUsername(userId)
.withClientId(clientId)
.withSecretHash(secretHash)
.withClientMetadata(clientMetadata);
final String pinpointEndpointId = pool.getPinpointEndpointId();
resendConfirmationCodeRequest.setUserContextData(getUserContextData());
if (pinpointEndpointId != null) {
AnalyticsMetadataType amd = new AnalyticsMetadataType();
amd.setAnalyticsEndpointId(pinpointEndpointId);
resendConfirmationCodeRequest.setAnalyticsMetadata(amd);
}
return cognitoIdentityProviderClient.resendConfirmationCode(resendConfirmationCodeRequest);
}
/**
* Starts the process to set a new password for forgotten password case, in
* background.
* <p>
* This will initiate the process to set a new password when the current
* password is forgotten. The new password will be successfully set only
* after the verification code, sent to the registered email or phone number
* of the user, successfully verified by Cognito Identity Provider service.
* This method will pass a continuation object to the callback. Use setters
* in the Continuation object {@link ForgotPasswordContinuation} to set the
* new password and verification code and call continue on the continuation
* object, {@code CognitoIdentityProviderContinuation.continueTask()}.
* </p>
*
* @param callback REQUIRED: {@link ForgotPasswordHandler} callback
*/
public void forgotPasswordInBackground(final ForgotPasswordHandler callback) {
forgotPasswordInBackground(Collections.<String, String>emptyMap(), callback);
}
/**
* Starts the process to set a new new password for forgotten password case,
* in current thread.
* <p>
* This will initiate the process to set a new password when the current
* password is forgotten. The new password will be successfully set only
* after the verification code, sent to the registered email or phone number
* of the user, successfully verified by Cognito Identity Provider service.
* This method will pass a continuation object to the callback. Use setters
* in the Continuation object {@link ForgotPasswordContinuation} to set the
* new password and verification code and call continue on the continuation
* object, {@code CognitoIdentityProviderContinuation.continueTask()}.
* <b>Note:</b> This method will perform network operations. Calling this
* method in applications' main thread will cause Android to throw
* NetworkOnMainThreadException.
* </p>
*
* @param callback REQUIRED: {@link ForgotPasswordHandler} callback
*/
public void forgotPassword(final ForgotPasswordHandler callback) {
forgotPassword(Collections.<String, String>emptyMap(), callback);
}
/**
* Starts the process to set a new password for forgotten password case, in
* background.
* <p>
* This will initiate the process to set a new password when the current
* password is forgotten. The new password will be successfully set only
* after the verification code, sent to the registered email or phone number
* of the user, successfully verified by Cognito Identity Provider service.
* This method will pass a continuation object to the callback. Use setters
* in the Continuation object {@link ForgotPasswordContinuation} to set the
* new password and verification code and call continue on the continuation
* object, {@code CognitoIdentityProviderContinuation.continueTask()}.
* </p>
*
* @param clientMetadata A map of custom key-value pairs that is passed to the lambda function for
* lambda functions triggered by forgot password.
* @param callback REQUIRED: {@link ForgotPasswordHandler} callback
*/
public void forgotPasswordInBackground(final Map<String, String> clientMetadata,
final ForgotPasswordHandler callback) {
if (callback == null) {
throw new CognitoParameterInvalidException("callback is null");
}
final CognitoUser cognitoUser = this;
new Thread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler(context.getMainLooper());
Runnable returnCallback;
try {
final ForgotPasswordResult forgotPasswordResult = forgotPasswordInternal(clientMetadata);
final ForgotPasswordContinuation continuation = new ForgotPasswordContinuation(
cognitoUser,
new CognitoUserCodeDeliveryDetails(
forgotPasswordResult.getCodeDeliveryDetails()),
ForgotPasswordContinuation.RUN_IN_BACKGROUND, callback);
returnCallback = new Runnable() {
@Override
public void run() {
callback.getResetCode(continuation);
}
};
} catch (final Exception e) {
returnCallback = new Runnable() {
@Override
public void run() {
callback.onFailure(e);
}
};
}
handler.post(returnCallback);
}
}).start();
}
/**
* Starts the process to set a new new password for forgotten password case,
* in current thread.
* <p>
* This will initiate the process to set a new password when the current
* password is forgotten. The new password will be successfully set only
* after the verification code, sent to the registered email or phone number
* of the user, successfully verified by Cognito Identity Provider service.
* This method will pass a continuation object to the callback. Use setters
* in the Continuation object {@link ForgotPasswordContinuation} to set the
* new password and verification code and call continue on the continuation
* object, {@code CognitoIdentityProviderContinuation.continueTask()}.
* <b>Note:</b> This method will perform network operations. Calling this
* method in applications' main thread will cause Android to throw
* NetworkOnMainThreadException.
* </p>
*
* @param clientMetadata A map of custom key-value pairs that is passed to the lambda function for
* lambda functions triggered by forgot password.
* @param callback REQUIRED: {@link ForgotPasswordHandler} callback
*/
public void forgotPassword(final Map<String, String> clientMetadata,
final ForgotPasswordHandler callback) {
if (callback == null) {
throw new CognitoParameterInvalidException("callback is null");
}
final CognitoUser cognitoUser = this;
try {
final ForgotPasswordResult forgotPasswordResult = forgotPasswordInternal(clientMetadata);
final ForgotPasswordContinuation continuation = new ForgotPasswordContinuation(
cognitoUser,
new CognitoUserCodeDeliveryDetails(
forgotPasswordResult.getCodeDeliveryDetails()),
ForgotPasswordContinuation.RUN_IN_CURRENT, callback);
callback.getResetCode(continuation);
} catch (final Exception e) {
callback.onFailure(e);
}
}
/**
* Internal method to start forgot password process.
*/
private ForgotPasswordResult forgotPasswordInternal(final Map<String, String> clientMetadata) {
final ForgotPasswordRequest resetPasswordRequest = new ForgotPasswordRequest();
resetPasswordRequest.setClientId(clientId);
resetPasswordRequest.setSecretHash(secretHash);
resetPasswordRequest.setUsername(userId);
resetPasswordRequest.setUserContextData(getUserContextData());
resetPasswordRequest.setClientMetadata(clientMetadata);
final String pinpointEndpointId = pool.getPinpointEndpointId();
if (pinpointEndpointId != null) {
AnalyticsMetadataType amd = new AnalyticsMetadataType();
amd.setAnalyticsEndpointId(pinpointEndpointId);
resetPasswordRequest.setAnalyticsMetadata(amd);
}
return cognitoIdentityProviderClient.forgotPassword(resetPasswordRequest);
}
/**
* Set new password and send verification code to Cognito Identity Provider
* service, in background.
* <p>
* This method will be called by {@link ForgotPasswordContinuation}
* continuation object.
* </p>
*
* @param verificationCode REQUIRED: Code sent from Cognito Identity
* Provider Service.
* @param newPassword REQUIRED: New password. On successful verification of
* {@code verificationCode}, this will be the new password for
* this user.
* @param callback REQUIRED: {@link ForgotPasswordHandler} callback.
*/
public void confirmPasswordInBackground(final String verificationCode,
final String newPassword,
final ForgotPasswordHandler callback) {
confirmPasswordInBackground(verificationCode, newPassword, Collections.<String, String>emptyMap(), callback);
}
/**
* Set new password and send verification code to Cognito Identity Provider
* service, in background.
* <p>
* This method will be called by {@link ForgotPasswordContinuation}
* continuation object.
* </p>
*
* @param verificationCode REQUIRED: Code sent from Cognito Identity
* Provider Service.
* @param newPassword REQUIRED: New password. On successful verification of
* {@code verificationCode}, this will be the new password for
* this user.
* @param clientMetadata A map of custom key-value pairs that you can provide as input for any
* custom workflows triggered by confirm password.
* @param callback REQUIRED: {@link ForgotPasswordHandler} callback.
*/
public void confirmPasswordInBackground(final String verificationCode,
final String newPassword,
final Map<String, String> clientMetadata,
final ForgotPasswordHandler callback) {
if (callback == null) {
throw new CognitoParameterInvalidException("callback is null");
}
new Thread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler(context.getMainLooper());
Runnable returnCallback;
try {
confirmPasswordInternal(verificationCode, newPassword, clientMetadata);
returnCallback = new Runnable() {
@Override
public void run() {
callback.onSuccess();
}
};
} catch (final Exception e) {
returnCallback = new Runnable() {
@Override
public void run() {
callback.onFailure(e);
}
};
}
handler.post(returnCallback);
}
}).start();
}
/**
* Sends the new password and the verification code to Cognito Identity
* Provider service, in background.
* <p>
* This method will be called by {@link ForgotPasswordContinuation}
* continuation object. <b>Note:</b> This method will perform network
* operations. Calling this method in applications' main thread will cause
* Android to throw NetworkOnMainThreadException.
* </p>
*
* @param verificationCode REQUIRED: Code sent from Cognito Identity
* Provider Service.
* @param newPassword REQUIRED: New password. On successful verification of
* {@code verificationCode}, this will be the new password for
* this user.
* @param callback REQUIRED: {@link ForgotPasswordHandler} callback.
*/
public void confirmPassword(final String verificationCode,
final String newPassword,
final ForgotPasswordHandler callback) {
confirmPassword(verificationCode, newPassword, Collections.<String, String>emptyMap(), callback);
}
/**
* Sends the new password and the verification code to Cognito Identity
* Provider service, in background.
* <p>
* This method will be called by {@link ForgotPasswordContinuation}
* continuation object. <b>Note:</b> This method will perform network
* operations. Calling this method in applications' main thread will cause
* Android to throw NetworkOnMainThreadException.
* </p>
*
* @param verificationCode REQUIRED: Code sent from Cognito Identity
* Provider Service.
* @param newPassword REQUIRED: New password. On successful verification of
* {@code verificationCode}, this will be the new password for
* this user.
* @param clientMetadata A map of custom key-value pairs that you can provide as input for any
* custom workflows triggered by confirm password.
* @param callback REQUIRED: {@link ForgotPasswordHandler} callback.
*/
public void confirmPassword(final String verificationCode,
final String newPassword,
final Map<String, String> clientMetadata,
final ForgotPasswordHandler callback) {
if (callback == null) {
throw new CognitoParameterInvalidException("callback is null");
}
try {
confirmPasswordInternal(verificationCode, newPassword, clientMetadata);
callback.onSuccess();
} catch (final Exception e) {
callback.onFailure(e);
}
}
/**
* Internal method to set a new password.
*
* @param verificationCode REQUIRED: Verification code sent to the user.
* @param newPassword REQUIRED: New password for the user.
*/
private void confirmPasswordInternal(final String verificationCode,
final String newPassword,
final Map<String, String> clientMetadata) {
final ConfirmForgotPasswordRequest confirmResetPasswordRequest = new ConfirmForgotPasswordRequest();
confirmResetPasswordRequest.setUsername(userId);
confirmResetPasswordRequest.setClientId(clientId);
confirmResetPasswordRequest.setSecretHash(secretHash);
confirmResetPasswordRequest.setConfirmationCode(verificationCode);
confirmResetPasswordRequest.setPassword(newPassword);
confirmResetPasswordRequest.setUserContextData(getUserContextData());
confirmResetPasswordRequest.setClientMetadata(clientMetadata);
final String pinpointEndpointId = pool.getPinpointEndpointId();
if (pinpointEndpointId != null) {
AnalyticsMetadataType amd = new AnalyticsMetadataType();
amd.setAnalyticsEndpointId(pinpointEndpointId);
confirmResetPasswordRequest.setAnalyticsMetadata(amd);
}
cognitoIdentityProviderClient.confirmForgotPassword(confirmResetPasswordRequest);
}
/**
* getSession orchestrates the SignIn flow with Amazon Cognito UserPools.
*
* <p>
* This method is asynchronous and performs network operations
* on a background thread.
* </p>
*
* <p>
* 1) Read the tokens (Id, Access and Refresh) that are cached on the device.
* 1.1) If the Id and Access tokens are present and they are valid, the
* {@link AuthenticationHandler#onSuccess(CognitoUserSession, CognitoDevice)}.
* will be called with a {@link CognitoUserSession} that has references to the valid tokens.
* This means that the user is signed-in.
* 1.2) If the Id and Access tokens are expired, and if there is a valid refresh token,
* a network call is made to get new Id and Access tokens.
* If valid Id and Access tokens are retrieved, they are cached on the device
* and {@link AuthenticationHandler#onSuccess(CognitoUserSession, CognitoDevice)}
* will be called with a {@link CognitoUserSession} that has references to the valid
* tokens. This means that the user is signed-in.
*
* 2) If there are no valid tokens cached on the device, the callback method
* {@link AuthenticationHandler#getAuthenticationDetails(AuthenticationContinuation, String)}
* will be called where the {@link AuthenticationDetails} will need to be supplied
* to continue the SignIn operation. See
* {@link com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.CognitoIdentityProviderContinuation}
* for details on continuation objects.
*
* 3) In all other error scenarios, {@link AuthenticationHandler#onFailure(Exception)} will
* be called with the type and message of the exception and it is the responsibility of
* the caller to handle the exceptions appropriately.
* </p>
*
* @param callback REQUIRED: {@link AuthenticationHandler} callback
*/
public void getSessionInBackground(final AuthenticationHandler callback) {
if (callback == null) {
throw new CognitoParameterInvalidException("callback is null");
}
final CognitoUser cognitoUser = this;
new Thread(new Runnable() {
@Override
public void run() {
final Handler handler = new Handler(context.getMainLooper());
Runnable returnCallback;
try {
getCachedSession();
returnCallback = new Runnable() {
@Override
public void run() {
callback.onSuccess(cipSession, null);
}
};
} catch (final CognitoNotAuthorizedException e) {
returnCallback = new Runnable() {
@Override
public void run() {
final AuthenticationContinuation authenticationContinuation =
new AuthenticationContinuation(
cognitoUser,
context,
AuthenticationContinuation.RUN_IN_BACKGROUND, callback
);
callback.getAuthenticationDetails(authenticationContinuation,
cognitoUser.getUserId());
}
};
} catch (final Exception e) {
returnCallback = new Runnable() {
@Override
public void run() {
callback.onFailure(e);
}
};
}
handler.post(returnCallback);
}
}).start();
}
/**
* getSession orchestrates the SignIn flow with Amazon Cognito UserPools.
*
* <p>
* This method is synchronous and performs network operations
* on the same thread in which the method is called. Calling this
* method in the MainThread will result in NetworkOnMainThreadException
* </p>
*
* <p>
* 1) Read the tokens (Id, Access and Refresh) that are cached on the device.
* 1.1) If the Id and Access tokens are present and they are valid, the
* {@link AuthenticationHandler#onSuccess(CognitoUserSession, CognitoDevice)}.
* will be called with a {@link CognitoUserSession} that has references to the valid tokens.
* This means that the user is signed-in.
* 1.2) If the Id and Access tokens are expired, and if there is a valid refresh token,
* a network call is made to get new Id and Access tokens.
* If valid Id and Access tokens are retrieved, they are cached on the device
* and {@link AuthenticationHandler#onSuccess(CognitoUserSession, CognitoDevice)}
* will be called with a {@link CognitoUserSession} that has references to the valid
* tokens. This means that the user is signed-in.
*
* 2) If there are no valid tokens cached on the device, the callback method
* {@link AuthenticationHandler#getAuthenticationDetails(AuthenticationContinuation, String)}
* will be called where the {@link AuthenticationDetails} will need to be supplied
* to continue the SignIn operation. See
* {@link com.amazonaws.mobileconnectors.cognitoidentityprovider.continuations.CognitoIdentityProviderContinuation}
* for details on continuation objects.
*
* 3) In all other error scenarios, {@link AuthenticationHandler#onFailure(Exception)} will
* be called with the type and message of the exception and it is the responsibility of
* the caller to handle the exceptions appropriately.
* </p>
*
* @param callback REQUIRED: {@link AuthenticationHandler} callback
*/
public void getSession(
final AuthenticationHandler callback) {
getSession(Collections.<String, String>emptyMap(), callback);
}
/**
* getSession orchestrates the SignIn flow with Amazon Cognito UserPools.
*
* <p>
* This method is synchronous and performs network operations
* on the same thread in which the method is called. Calling this
* method in the MainThread will result in NetworkOnMainThreadException
* </p>
*
* <p>
* 1) Read the tokens (Id, Access and Refresh) that are cached on the device.
* 1.1) If the Id and Access tokens are present and they are valid, the
* {@link AuthenticationHandler#onSuccess(CognitoUserSession, CognitoDevice)}.
* will be called with a {@link CognitoUserSession} that has references to the valid tokens.
* This means that the user is signed-in.
* 1.2) If the Id and Access tokens are expired, and if there is a valid refresh token,
* a network call is made to get new Id and Access tokens.
* If valid Id and Access tokens are retrieved, they are cached on the device
* and {@link AuthenticationHandler#onSuccess(CognitoUserSession, CognitoDevice)}
* will be called with a {@link CognitoUserSession} that has references to the valid
* tokens. This means that the user is signed-in.
*
* 2) If there are no valid tokens cached on the device, the callback method
* {@link AuthenticationHandler#getAuthenticationDetails(AuthenticationContinuation, String)}
* will be called where the {@link AuthenticationDetails} will need to be supplied