-
Notifications
You must be signed in to change notification settings - Fork 549
/
Copy pathAWSMobileClient.java
4000 lines (3609 loc) · 177 KB
/
AWSMobileClient.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 2017-2019 Amazon.com, Inc. or its affiliates.
* All Rights Reserved.
*
* 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.amazonaws.mobile.client;
import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import androidx.annotation.AnyThread;
import androidx.annotation.WorkerThread;
import androidx.browser.customtabs.CustomTabsCallback;
import androidx.browser.customtabs.CustomTabsClient;
import androidx.browser.customtabs.CustomTabsIntent;
import androidx.browser.customtabs.CustomTabsServiceConnection;
import androidx.browser.customtabs.CustomTabsSession;
import androidx.core.content.ContextCompat;
import com.amazonaws.AmazonClientException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSAbstractCognitoIdentityProvider;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSSessionCredentials;
import com.amazonaws.auth.AnonymousAWSCredentials;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.internal.keyvaluestore.AWSKeyValueStore;
import com.amazonaws.mobile.auth.core.IdentityManager;
import com.amazonaws.mobile.auth.core.SignInStateChangeListener;
import com.amazonaws.mobile.auth.core.StartupAuthResultHandler;
import com.amazonaws.mobile.auth.core.signin.SignInManager;
import com.amazonaws.mobile.auth.core.signin.SignInProvider;
import com.amazonaws.mobile.auth.facebook.FacebookButton;
import com.amazonaws.mobile.auth.facebook.FacebookSignInProvider;
import com.amazonaws.mobile.auth.google.GoogleButton;
import com.amazonaws.mobile.auth.google.GoogleSignInProvider;
import com.amazonaws.mobile.auth.ui.AuthUIConfiguration;
import com.amazonaws.mobile.auth.ui.SignInUI;
import com.amazonaws.mobile.auth.userpools.CognitoUserPoolsSignInProvider;
import com.amazonaws.mobile.client.internal.InternalCallback;
import com.amazonaws.mobile.client.internal.ReturningRunnable;
import com.amazonaws.mobile.client.internal.oauth2.AuthorizeResponse;
import com.amazonaws.mobile.client.internal.oauth2.OAuth2Client;
import com.amazonaws.mobile.client.internal.oauth2.OAuth2Tokens;
import com.amazonaws.mobile.client.results.ForgotPasswordResult;
import com.amazonaws.mobile.client.results.ForgotPasswordState;
import com.amazonaws.mobile.client.results.SignInResult;
import com.amazonaws.mobile.client.results.SignInState;
import com.amazonaws.mobile.client.results.SignUpResult;
import com.amazonaws.mobile.client.results.Tokens;
import com.amazonaws.mobile.client.results.UserCodeDeliveryDetails;
import com.amazonaws.mobile.config.AWSConfigurable;
import com.amazonaws.mobile.config.AWSConfiguration;
import com.amazonaws.mobileconnectors.cognitoauth.Auth;
import com.amazonaws.mobileconnectors.cognitoauth.AuthUserSession;
import com.amazonaws.mobileconnectors.cognitoauth.handlers.AuthHandler;
import com.amazonaws.mobileconnectors.cognitoauth.util.ClientConstants;
import com.amazonaws.mobileconnectors.cognitoauth.util.Pkce;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoDevice;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserAttributes;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserCodeDeliveryDetails;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserDetails;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserPool;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUserSession;
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.CognitoIdentityProviderContinuation;
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.handlers.AuthenticationHandler;
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.SignUpHandler;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.UpdateAttributesHandler;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.handlers.VerificationHandler;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.util.CognitoPinpointSharedContext;
import com.amazonaws.mobileconnectors.cognitoidentityprovider.util.CognitoServiceConstants;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.cognitoidentity.AmazonCognitoIdentity;
import com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient;
import com.amazonaws.services.cognitoidentity.model.NotAuthorizedException;
import com.amazonaws.services.cognitoidentityprovider.AmazonCognitoIdentityProvider;
import com.amazonaws.services.cognitoidentityprovider.AmazonCognitoIdentityProviderClient;
import com.amazonaws.services.cognitoidentityprovider.model.GlobalSignOutRequest;
import com.amazonaws.util.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import static com.amazonaws.mobile.client.results.SignInState.CUSTOM_CHALLENGE;
/**
* The AWSMobileClient provides client APIs and building blocks for developers who want to create
* user authentication experiences. This includes declarative methods for performing
* authentication actions, a simple “drop-in auth” UI for performing common tasks, automatic
* token and credentials management, and state tracking with notifications for performing
* workflows in your application when users have authenticated.
*
* The following demonstrates a simple sample usage inside of MainActivity.java onCreate method.
* <pre>
* AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {
* public void onResult(UserStateDetails userStateDetails) {
* switch (userStateDetails.getUserState()) {
* case SIGNED_IN:
* break;
* case SIGNED_OUT:
* try {
* AWSMobileClient.getInstance().showSignIn(MainActivity.this);
* } catch (Exception e) {
* Log.e("TAG", "", e);
* }
* break;
* default:
* Log.w("Unhandled state see UserState for a list of states");
* break;
* }
* }
* })
* }
* </pre>
*/
public final class AWSMobileClient implements AWSCredentialsProvider {
/**
* Log Tag.
*/
private static final String TAG = AWSMobileClient.class.getSimpleName();
public static final String DEFAULT_USER_AGENT = "AWSMobileClient";
static final String AUTH_KEY = "Auth";
static final String SHARED_PREFERENCES_KEY = "com.amazonaws.mobile.client";
static final String PROVIDER_KEY = "provider";
static final String TOKEN_KEY = "token";
static final String IDENTITY_ID_KEY = "cognitoIdentityId";
static final String SIGN_IN_MODE = "signInMode";
public static final String HOSTED_UI_KEY = "hostedUI";
/// This value is a boolean stored as a String 'true' 'false'
static final String FEDERATION_ENABLED_KEY = "isFederationEnabled";
private static final String CUSTOM_ROLE_ARN_KEY = "customRoleArn";
public static final String CHALLENGE_RESPONSE_NEW_PASSWORD_KEY = CognitoServiceConstants.CHLG_RESP_NEW_PASSWORD;
public static final String CHALLENGE_RESPONSE_USER_ATTRIBUTES_PREFIX_KEY = CognitoServiceConstants.CHLG_PARAM_USER_ATTRIBUTE_PREFIX;
/**
* Configuration keys for SignInProviders in awsconfiguration.json.
*/
private static final String USER_POOLS = "CognitoUserPool";
private static final String FACEBOOK = "FacebookSignIn";
private static final String GOOGLE = "GoogleSignIn";
private static final String GOOGLE_WEBAPP_CONFIG_KEY = "ClientId-WebApp";
/**
* Singleton instance for AWSMobileClient.
*/
private static volatile AWSMobileClient singleton = null;
/**
* Map of SDK Client Class and object.
*/
private final LinkedHashMap<Class<? extends AWSConfigurable>, AWSConfigurable> clientMap;
/**
* AWSConfiguration object that represents the `awsconfiguration.json` file.
*/
AWSConfiguration awsConfiguration;
/**
* Federation into this identity pool
*/
CognitoCachingCredentialsProvider cognitoIdentity;
/**
* Object that encapuslates the high-level Cognito UserPools client
*/
CognitoUserPool userpool;
String userpoolsLoginKey;
Context mContext;
Map<String, String> mFederatedLoginsMap;
private UserStateDetails userStateDetails;
private Lock mWaitForSignInLock;
private volatile CountDownLatch mSignedOutWaitLatch;
CognitoUserSession mCognitoUserSession;
// Sign-in continuation callbacks given by customer
private Callback<SignInResult> signInCallback;
// Internal tracking continuation
private MultiFactorAuthenticationContinuation signInMfaContinuation;
private ChallengeContinuation signInChallengeContinuation;
private SignInState signInState;
// Forgot password continuation callbacks given by customer
private Callback<ForgotPasswordResult> forgotPasswordCallback;
// Forgot password continuation
private ForgotPasswordContinuation forgotPasswordContinuation;
// Sign-up user
private CognitoUser signUpUser;
// Setup TOTP callback given by customer
// private Callback<SetupTotpResult> totpCallback;
// Internal tracking setup TOTP
// private String totpSessionToken;
// private VerifyMfaContinuation totpContinuation;
/**
* CredentialsProvider created by the IdentityManager.
*/
private AWSCredentialsProvider awsCredentialsProvider;
/**
* Config of SignInProviders: class and permissions.
*/
private SignInProviderConfig[] signInProviderConfig;
/**
* Callback for resuming auth session.
*/
private StartupAuthResultHandler startupAuthResultHandler;
/**
* Callback for initalizing the SDK with AWSMobileClient.
*/
private AWSStartupHandler awsStartupHandler;
/**
* Flag to use default config automatically.
* Use the default configuration information if TRUE.
*/
private boolean mIsLegacyMode;
List<UserStateListener> listeners;
private Object showSignInLockObject;
private volatile CountDownLatch showSignInWaitLatch;
private Object federateWithCognitoIdentityLockObject;
private Object initLockObject;
AWSMobileClientStore mStore;
AWSMobileClientCognitoIdentityProvider provider;
DeviceOperations mDeviceOperations;
AmazonCognitoIdentityProvider userpoolLL;
Auth hostedUI;
OAuth2Client mOAuth2Client;
String mUserPoolPoolId;
String userAgentOverride;
enum SignInMode {
SIGN_IN("0"),
FEDERATED_SIGN_IN("1"),
HOSTED_UI("2"),
OAUTH2("3"),
UNKNOWN("-1"),
;
String encode;
SignInMode(final String encode) {
this.encode = encode;
}
public String toString() {
return encode;
}
static SignInMode fromString(final String str) {
if ("0".equals(str)) {
return SIGN_IN;
} else if ("1".equals(str)) {
return FEDERATED_SIGN_IN;
} else if ("2".equals(str)) {
return HOSTED_UI;
} else if ("3".equals(str)) {
return OAUTH2;
}
return UNKNOWN;
}
}
/**
* Flag that indicates if the tokens would be persisted in SharedPreferences.
* By default, this is set to true. If set to false, the tokens would be
* kept in memory.
*/
boolean mIsPersistenceEnabled = true;
/**
* Constructor invoked by getInstance.
*
* @throws AssertionError when this is called with context more than once.
*/
private AWSMobileClient() {
if (singleton != null) {
throw new AssertionError();
}
this.clientMap = new LinkedHashMap<Class<? extends AWSConfigurable>, AWSConfigurable>();
userpoolsLoginKey = "";
mWaitForSignInLock = new ReentrantLock();
mFederatedLoginsMap = new HashMap<String, String>();
listeners = new ArrayList<UserStateListener>();
showSignInLockObject = new Object();
federateWithCognitoIdentityLockObject = new Object();
showSignInWaitLatch = new CountDownLatch(1);
initLockObject = new Object();
}
/**
* Gets the singleton instance of this class.
*
* @return singleton instance
*/
public static synchronized AWSMobileClient getInstance() {
if (singleton == null) {
singleton = new AWSMobileClient();
}
return singleton;
}
/**
* Retrieve the AWSConfiguration object that represents
* the awsconfiguration.json file.
*
* @return the AWSConfiguration object
*/
public AWSConfiguration getConfiguration() {
return this.awsConfiguration;
}
@Override
public AWSCredentials getCredentials() {
if (isLegacyMode()) {
return IdentityManager.getDefaultIdentityManager().getCredentialsProvider().getCredentials();
}
if (cognitoIdentity == null) {
throw new AmazonClientException("Cognito Identity not configured");
}
try {
if (waitForSignIn()) {
Log.d(TAG, "getCredentials: Validated user is signed-in");
}
AWSSessionCredentials credentials = cognitoIdentity.getCredentials();
mStore.set(IDENTITY_ID_KEY, cognitoIdentity.getIdentityId());
return credentials;
} catch (NotAuthorizedException e) {
Log.w(TAG, "getCredentials: Failed to getCredentials from Cognito Identity", e);
throw new AmazonClientException("Failed to get credentials from Cognito Identity", e);
} catch (Exception e) {
throw new AmazonClientException("Failed to get credentials from Cognito Identity", e);
}
}
@Override
public void refresh() {
if (isLegacyMode()) {
IdentityManager.getDefaultIdentityManager().getCredentialsProvider().refresh();
return;
}
if (cognitoIdentity == null) {
throw new AmazonClientException("Cognito Identity not configured");
}
cognitoIdentity.refresh();
mStore.set(IDENTITY_ID_KEY, cognitoIdentity.getIdentityId());
}
/**
* Returns AWSCredentials obtained from Cognito Identity
* @return AWSCredentials obtained from Cognito Identity
* @throws Exception
*/
@WorkerThread
public AWSCredentials getAWSCredentials() throws Exception {
return _getAWSCredentials().await();
}
@AnyThread
public void getAWSCredentials(final Callback<AWSCredentials> callback) {
_getAWSCredentials().async(callback);
}
private ReturningRunnable<AWSCredentials> _getAWSCredentials() {
return new ReturningRunnable<AWSCredentials>() {
@Override
public AWSCredentials run() {
return getCredentials();
}
};
}
@AnyThread
public String getIdentityId() {
if (isLegacyMode()) {
return IdentityManager.getDefaultIdentityManager().getCachedUserID();
}
if (cognitoIdentity == null) {
throw new RuntimeException("Cognito Identity not configured");
}
final String cachedIdentityId = cognitoIdentity.getCachedIdentityId();
if (cachedIdentityId == null) {
return mStore.get(IDENTITY_ID_KEY);
}
return cachedIdentityId;
}
boolean isLegacyMode() {
return mIsLegacyMode;
}
@AnyThread
public void initialize(final Context context, final Callback<UserStateDetails> callback) {
final Context applicationContext = context.getApplicationContext();
initialize(applicationContext, new AWSConfiguration(applicationContext), callback);
}
@AnyThread
public void initialize(final Context context, final AWSConfiguration awsConfig, final Callback<UserStateDetails> callback) {
final InternalCallback internalCallback = new InternalCallback<UserStateDetails>(callback);
internalCallback.async(_initialize(context, awsConfig, internalCallback));
}
CountDownLatch getSignInUILatch() {
return showSignInWaitLatch;
}
protected Runnable _initialize(final Context context, final AWSConfiguration awsConfiguration, final Callback<UserStateDetails> callback) {
return new Runnable() {
public void run() {
synchronized (initLockObject) {
if (AWSMobileClient.this.awsConfiguration != null) {
callback.onResult(getUserStateDetails(true));
return;
}
mIsPersistenceEnabled = true; // Default value
// Read Persistence key from the awsconfiguration.json and set the flag
// appropriately.
try {
if (awsConfiguration.optJsonObject(AUTH_KEY) != null &&
awsConfiguration.optJsonObject(AUTH_KEY).has("Persistence")) {
mIsPersistenceEnabled = awsConfiguration
.optJsonObject(AUTH_KEY)
.getBoolean("Persistence");
}
} catch (final Exception ex) {
// If reading from awsconfiguration.json fails, invoke callback.
callback.onError(new RuntimeException("Failed to initialize AWSMobileClient; please check your awsconfiguration.json", ex));
return;
}
userAgentOverride = awsConfiguration.getUserAgentOverride();
mContext = context.getApplicationContext();
mStore = new AWSMobileClientStore(AWSMobileClient.this);
final IdentityManager identityManager = new IdentityManager(mContext);
identityManager.enableFederation(false);
identityManager.setConfiguration(awsConfiguration);
identityManager.setPersistenceEnabled(mIsPersistenceEnabled);
IdentityManager.setDefaultIdentityManager(identityManager);
identityManager.addSignInStateChangeListener(new SignInStateChangeListener() {
@Override
public void onUserSignedIn() {
Log.d(TAG, "onUserSignedIn: Updating user state from drop-in UI");
signInState = SignInState.DONE;
com.amazonaws.mobile.auth.core.IdentityProvider currentIdentityProvider = identityManager.getCurrentIdentityProvider();
String token = currentIdentityProvider.getToken();
String providerKey = currentIdentityProvider.getCognitoLoginKey();
federatedSignInWithoutAssigningState(providerKey, token, new Callback<UserStateDetails>() {
@Override
public void onResult(UserStateDetails result) {
Log.d(TAG, "onResult: showSignIn federated");
setUserState(getUserStateDetails(false));
getSignInUILatch().countDown();
}
@Override
public void onError(Exception e) {
Log.w(TAG, "onError: User sign-in had errors from drop-in UI", e);
setUserState(getUserStateDetails(false));
getSignInUILatch().countDown();
}
});
}
@Override
public void onUserSignedOut() {
Log.d(TAG, "onUserSignedOut: Updating user state from drop-in UI");
setUserState(getUserStateDetails(false));
showSignInWaitLatch.countDown();
}
});
if (awsConfiguration.optJsonObject("CredentialsProvider") != null
&& awsConfiguration.optJsonObject("CredentialsProvider").optJSONObject("CognitoIdentity") != null) {
try {
JSONObject identityPoolJSON = awsConfiguration.optJsonObject(
"CredentialsProvider").getJSONObject("CognitoIdentity").getJSONObject(awsConfiguration.getConfiguration());
final String poolId = identityPoolJSON.getString("PoolId");
final String regionStr = identityPoolJSON.getString("Region");
final ClientConfiguration clientConfig = new ClientConfiguration();
clientConfig.setUserAgent(DEFAULT_USER_AGENT + " " + awsConfiguration.getUserAgent());
if (userAgentOverride != null) {
clientConfig.setUserAgentOverride(userAgentOverride);
}
AmazonCognitoIdentityClient cibClient =
new AmazonCognitoIdentityClient(new AnonymousAWSCredentials(), clientConfig);
cibClient.setRegion(Region.getRegion(regionStr));
provider = new AWSMobileClientCognitoIdentityProvider(
null, poolId, cibClient);
cognitoIdentity = new CognitoCachingCredentialsProvider(
mContext, provider, Regions.fromName(regionStr));
cognitoIdentity.setPersistenceEnabled(mIsPersistenceEnabled);
if (userAgentOverride != null) {
cognitoIdentity.setUserAgentOverride(userAgentOverride);
}
} catch (Exception e) {
callback.onError(new RuntimeException("Failed to initialize Cognito Identity; please check your awsconfiguration.json", e));
return;
}
}
final JSONObject userPoolJSON = awsConfiguration.optJsonObject("CognitoUserPool");
if (userPoolJSON != null) {
try {
mUserPoolPoolId = userPoolJSON.getString("PoolId");
final String clientId = userPoolJSON.getString("AppClientId");
final String clientSecret = userPoolJSON.optString("AppClientSecret");
final String pinpointEndpointId = CognitoPinpointSharedContext.getPinpointEndpoint(context, userPoolJSON.optString("PinpointAppId"));
final ClientConfiguration clientConfig = new ClientConfiguration();
clientConfig.setUserAgent(DEFAULT_USER_AGENT + " " + awsConfiguration.getUserAgent());
if (userAgentOverride != null) {
clientConfig.setUserAgentOverride(userAgentOverride);
}
userpoolLL =
new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), clientConfig);
userpoolLL.setRegion(com.amazonaws.regions.Region.getRegion(Regions.fromName(userPoolJSON.getString("Region"))));
userpoolsLoginKey = String.format("cognito-idp.%s.amazonaws.com/%s", userPoolJSON.getString("Region"), userPoolJSON.getString("PoolId"));
userpool = new CognitoUserPool(mContext, mUserPoolPoolId, clientId, clientSecret, userpoolLL, pinpointEndpointId);
userpool.setPersistenceEnabled(mIsPersistenceEnabled);
mDeviceOperations = new DeviceOperations(AWSMobileClient.this, userpoolLL);
} catch (Exception e) {
callback.onError(new RuntimeException("Failed to initialize Cognito Userpool; please check your awsconfiguration.json", e));
return;
}
}
JSONObject hostedUIJSON = getHostedUIJSON(awsConfiguration);
if (hostedUIJSON != null) {
try {
// Pre-warm the Custom Tabs based on
if (hostedUIJSON.has("TokenURI")) {
Log.d(TAG, "initialize: OAuth2 client detected");
mOAuth2Client = new OAuth2Client(mContext, AWSMobileClient.this);
mOAuth2Client.setPersistenceEnabled(mIsPersistenceEnabled);
mOAuth2Client.setUserAgentOverride(userAgentOverride);
} else {
_initializeHostedUI(hostedUIJSON);
}
} catch (Exception e) {
callback.onError(new RuntimeException("Failed to initialize OAuth, please check your awsconfiguration.json", e));
}
}
if (cognitoIdentity == null && userpool == null) {
callback.onError(new RuntimeException(
"Neither Cognito Identity or Cognito UserPool was used." +
" At least one must be present to use AWSMobileClient."));
return;
}
AWSMobileClient.this.awsConfiguration = awsConfiguration;
final UserStateDetails userStateDetails = getUserStateDetails(true);
callback.onResult(userStateDetails);
setUserState(userStateDetails);
}
}
};
}
private void _initializeHostedUI(JSONObject hostedUIJSON) throws JSONException {
Log.d(TAG, "initialize: Cognito HostedUI client detected");
final JSONArray scopesJSONArray = hostedUIJSON.getJSONArray("Scopes");
final Set<String> scopes = new HashSet<String>();
for (int i = 0; i < scopesJSONArray.length(); i++) {
scopes.add(scopesJSONArray.getString(i));
}
if (mUserPoolPoolId == null) {
throw new IllegalStateException("User pool Id must be available through user pool setting");
}
hostedUI = getHostedUI(hostedUIJSON)
.setPersistenceEnabled(mIsPersistenceEnabled)
.setAuthHandler(new AuthHandler() {
@Override
public void onSuccess(AuthUserSession session) {
// Ignored because this is used to pre-warm the session
}
@Override
public void onSignout() {
// Ignored because this is used to pre-warm the session
}
@Override
public void onFailure(Exception e) {
// Ignored because this is used to pre-warm the session
}
})
.build();
}
JSONObject getHostedUIJSONFromJSON() {
return getHostedUIJSONFromJSON(this.awsConfiguration);
}
JSONObject getHostedUIJSONFromJSON(final AWSConfiguration awsConfig) {
final JSONObject mobileClientJSON = awsConfig.optJsonObject(AUTH_KEY);
if (mobileClientJSON != null && mobileClientJSON.has("OAuth")) {
try {
JSONObject hostedUIJSONFromJSON = mobileClientJSON.getJSONObject("OAuth");
return hostedUIJSONFromJSON;
} catch (Exception e) {
Log.w(TAG, "getHostedUIJSONFromJSON: Failed to read config", e);
}
}
return null;
}
JSONObject getHostedUIJSON() {
return getHostedUIJSON(this.awsConfiguration);
}
JSONObject getHostedUIJSON(final AWSConfiguration awsConfig) {
try {
JSONObject hostedUIJSONFromJSON = getHostedUIJSONFromJSON(awsConfig);
if (hostedUIJSONFromJSON == null) {
return null;
}
final String hostedUIString = mStore.get(HOSTED_UI_KEY);
JSONObject hostedUIJSON = null;
try {
hostedUIJSON = new JSONObject(hostedUIString);
} catch (Exception e) {
Log.w(TAG,
"Failed to parse HostedUI settings from store. Defaulting to awsconfiguration.json", e);
}
if (hostedUIJSON == null && hostedUIJSONFromJSON != null) {
hostedUIJSON = new JSONObject(hostedUIJSONFromJSON.toString());
mStore.set(HOSTED_UI_KEY, hostedUIJSON.toString());
}
return hostedUIJSON;
} catch (Exception e) {
Log.d(TAG, "getHostedUIJSON: Failed to read config", e);
}
return null;
}
Auth.Builder getHostedUI(final JSONObject hostedUIJSON) throws JSONException {
final JSONArray scopesJSONArray = hostedUIJSON.getJSONArray("Scopes");
final Set<String> scopes = new HashSet<String>();
for (int i = 0; i < scopesJSONArray.length(); i++) {
scopes.add(scopesJSONArray.getString(i));
}
return new Auth.Builder()
.setApplicationContext(mContext)
.setUserPoolId(mUserPoolPoolId)
.setAppClientId(hostedUIJSON.getString("AppClientId"))
.setAppClientSecret(hostedUIJSON.optString("AppClientSecret", null))
.setAppCognitoWebDomain(hostedUIJSON.getString("WebDomain"))
.setSignInRedirect(hostedUIJSON.getString("SignInRedirectURI"))
.setSignOutRedirect(hostedUIJSON.getString("SignOutRedirectURI"))
.setScopes(scopes)
.setAdvancedSecurityDataCollection(false)
.setIdentityProvider(hostedUIJSON.optString("IdentityProvider"))
.setIdpIdentifier(hostedUIJSON.optString("IdpIdentifier"));
}
/**
* Retrieve a handle to perform device related operations.
* This is only available for Cognito User Pools and it must be configured in the client.
*
* @return a handle for device operations
*/
@AnyThread
public DeviceOperations getDeviceOperations() {
if (mDeviceOperations == null) {
throw new AmazonClientException("Please check if userpools is configured.");
}
return mDeviceOperations;
}
/**
* Release the wait for tokens to be refreshed
* Doing this fails all pending operations that were
* waiting for sign-in.
*/
@AnyThread
public void releaseSignInWait() {
if (mSignedOutWaitLatch != null) {
mSignedOutWaitLatch.countDown();
}
}
protected void setUserState(final UserStateDetails details) {
final boolean hasChanged = !details.equals(this.userStateDetails);
this.userStateDetails = details;
if (hasChanged) {
synchronized (listeners) {
for (final UserStateListener listener : listeners) {
new Thread(new Runnable() {
@Override
public void run() {
listener.onUserStateChanged(details);
}
}).start();
}
}
}
}
/**
* Uses Android system commands to determine if the device is online.
* Requires ACCESS_NETWORK_STATE.
*
* @param context application context
* @return true if permission to access network state is granted and network is connected.
*/
protected boolean isNetworkAvailable(final Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int hasReadExternalStoragePermission = ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_NETWORK_STATE);
if (hasReadExternalStoragePermission != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
try {
ConnectivityManager manager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
} catch (Exception e) {
Log.w(TAG, "Could not access network state", e);
}
return false;
}
boolean isUserpoolsSignedIn() {
return userpoolsLoginKey.equals(mStore.get(PROVIDER_KEY));
}
/**
* Returns the signed-in user's username obtained from the access token.
* @return signed-in user's username
*/
@AnyThread
public String getUsername() {
try {
if (userpoolsLoginKey.equals(mStore.get(PROVIDER_KEY))) {
return userpool.getCurrentUser().getUserId();
}
return null;
} catch (Exception e) {
return null;
}
}
/**
* Performs a check on the current UserState. When online, this method will attempt to
* refresh tokens when they expired. Failing a refresh may cause the UserState to change.
*
* @return details about the user's state
*/
@WorkerThread
public UserStateDetails currentUserState() {
try {
return _currentUserState().await();
} catch (Exception e) {
throw new RuntimeException("Failed to retrieve user state.", e);
}
}
/**
* Performs a check on the current UserState. When online, this method will attempt to
* refresh tokens when they expired. Failing a refresh may cause the UserState to change.
*
* @return details about the user's state
*/
@AnyThread
public void currentUserState(final Callback<UserStateDetails> callback) {
_currentUserState().async(callback);
}
ReturningRunnable<UserStateDetails> _currentUserState() {
return new ReturningRunnable<UserStateDetails>() {
@Override
public UserStateDetails run() throws Exception {
return getUserStateDetails(false);
}
};
}
/**
* Adds a listener to be notified of state changes.
* When encountering SIGNED_OUT_FEDERATED_TOKENS_INVALID
* or SIGNED_OUT_USER_POOLS_TOKENS_INVALID
* {@link #releaseSignInWait()} or any form of sign-in can be called
* to prevent blocking {@link #getCredentials()}, {@link #getTokens()}, or other methods
* requiring a sign-in.
* @param listener
*/
@AnyThread
public void addUserStateListener(final UserStateListener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
/**
* Removes a listener. This will hold onto references.
* Remove when a lifecycle ends to prevent memory leaks.
* @param listener
* @return true if removed
*/
@AnyThread
public boolean removeUserStateListener(final UserStateListener listener) {
synchronized (listeners) {
int index = listeners.indexOf(listener);
if (index != -1) {
this.listeners.remove(index);
return true;
}
return false;
}
}
String getLoginKey() {
return userpoolsLoginKey;
}
/**
* A variant of {@link #currentUserState()} that simplifies the output to a boolean.
* True if SIGNED_IN, SIGNED_OUT_USER_POOLS_TOKENS_INVALID, SIGNED_OUT_FEDERATED_TOKENS_INVALID.
* False if GUEST, SIGNED_OUT.
*
* @return see above
*/
@AnyThread
public boolean isSignedIn() {
final UserStateDetails userStateDetails = getUserStateDetails(true);
switch (userStateDetails.getUserState()) {
case SIGNED_IN:
case SIGNED_OUT_USER_POOLS_TOKENS_INVALID:
case SIGNED_OUT_FEDERATED_TOKENS_INVALID:
return true;
case GUEST:
case SIGNED_OUT:
return false;
default:
throw new IllegalStateException("Unknown user state, please report this exception");
}
}
/**
* This method checks the current state of the user.
* If the user's session is determined to be expired, then the {@link UserStateListener} will be
* notified with @{@link UserState#SIGNED_OUT_USER_POOLS_TOKENS_INVALID} or
* @{link UserState#SIGNED_OUT_FEDERATED_TOKENS_INVALID}.
* @return true if user is signed-in, false otherwise
*/
protected boolean waitForSignIn() {
UserStateDetails userStateDetails = null;
try {
mWaitForSignInLock.lock();
mSignedOutWaitLatch = new CountDownLatch(1);
userStateDetails = getUserStateDetails(false);
Log.d(TAG, "waitForSignIn: userState:" + userStateDetails.getUserState());
switch (userStateDetails.getUserState()) {
case SIGNED_IN:
setUserState(userStateDetails);
return true;
case GUEST:
case SIGNED_OUT:
setUserState(userStateDetails);
return false;
case SIGNED_OUT_USER_POOLS_TOKENS_INVALID:
case SIGNED_OUT_FEDERATED_TOKENS_INVALID:
if (userStateDetails.getException() == null
|| isSignedOutRelatedException(userStateDetails.getException())) {
// The service has returned an exception that indicates the user is not authorized
// Ask for another sign-in
setUserState(userStateDetails);
mSignedOutWaitLatch.await();
return getUserStateDetails(false).getUserState().equals(UserState.SIGNED_IN);
} else {
// The exception is non-conclusive whether the user is not authorized or
// there was a network related issue. Throw the exception back to the API call.
throw userStateDetails.getException();
}
}
} catch (Exception e) {
throw new AmazonClientException("Operation requires a signed-in state", e);
} finally {
mWaitForSignInLock.unlock();
}
return false;
}
Map<String, String> getSignInDetailsMap() {
return mStore.get(PROVIDER_KEY, TOKEN_KEY);
}
String _getCachedIdentityId() {
return mStore.get(IDENTITY_ID_KEY);
}
/**
* Has side-effect of attempting to alert developer to try and sign-in user
* when required to be signed-in and will mutate the user's state.
*
* @param offlineCheck true, will determine if the tokens are expired or the credentials are expired and block for refresh
* @return the current state of the user
*/
protected UserStateDetails getUserStateDetails(final boolean offlineCheck) {
final Map<String, String> details = getSignInDetailsMap();
final String providerKey = details.get(PROVIDER_KEY);
final String token = details.get(TOKEN_KEY);
final String identityId = _getCachedIdentityId();
final boolean federationEnabled = isFederationEnabled();
Log.d(TAG, "Inspecting user state details");
final boolean hasUsefulToken = providerKey != null && token != null;
// Offline state detection
if (offlineCheck || !isNetworkAvailable(mContext)) {
if (hasUsefulToken) {
return new UserStateDetails(UserState.SIGNED_IN, details);
} else {
if (identityId != null) {
return new UserStateDetails(UserState.GUEST, details);
} else {
return new UserStateDetails(UserState.SIGNED_OUT, null);
}
}
}
// Online state detection
if (hasUsefulToken && !userpoolsLoginKey.equals(providerKey)) {
// TODO enhancement: check if token is expired
try {
if (!federationEnabled) {
// Do nothing, you are signed-in by having the token
} else {
// Attempt to refresh the token if it matches drop-in UI