-
Notifications
You must be signed in to change notification settings - Fork 108
/
RealAWSCognitoAuthPlugin.kt
1892 lines (1795 loc) · 82.9 KB
/
RealAWSCognitoAuthPlugin.kt
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 2022 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amplifyframework.auth.cognito
import android.app.Activity
import android.content.Intent
import androidx.annotation.WorkerThread
import aws.sdk.kotlin.services.cognitoidentityprovider.confirmForgotPassword
import aws.sdk.kotlin.services.cognitoidentityprovider.confirmSignUp
import aws.sdk.kotlin.services.cognitoidentityprovider.model.AnalyticsMetadataType
import aws.sdk.kotlin.services.cognitoidentityprovider.model.AttributeType
import aws.sdk.kotlin.services.cognitoidentityprovider.model.ChangePasswordRequest
import aws.sdk.kotlin.services.cognitoidentityprovider.model.DeviceRememberedStatusType
import aws.sdk.kotlin.services.cognitoidentityprovider.model.GetUserAttributeVerificationCodeRequest
import aws.sdk.kotlin.services.cognitoidentityprovider.model.GetUserRequest
import aws.sdk.kotlin.services.cognitoidentityprovider.model.ListDevicesRequest
import aws.sdk.kotlin.services.cognitoidentityprovider.model.UpdateDeviceStatusRequest
import aws.sdk.kotlin.services.cognitoidentityprovider.model.UpdateUserAttributesRequest
import aws.sdk.kotlin.services.cognitoidentityprovider.model.UpdateUserAttributesResponse
import aws.sdk.kotlin.services.cognitoidentityprovider.model.VerifyUserAttributeRequest
import aws.sdk.kotlin.services.cognitoidentityprovider.resendConfirmationCode
import aws.sdk.kotlin.services.cognitoidentityprovider.signUp
import com.amplifyframework.AmplifyException
import com.amplifyframework.auth.AWSCredentials
import com.amplifyframework.auth.AWSTemporaryCredentials
import com.amplifyframework.auth.AuthCategoryBehavior
import com.amplifyframework.auth.AuthChannelEventName
import com.amplifyframework.auth.AuthCodeDeliveryDetails
import com.amplifyframework.auth.AuthDevice
import com.amplifyframework.auth.AuthException
import com.amplifyframework.auth.AuthProvider
import com.amplifyframework.auth.AuthSession
import com.amplifyframework.auth.AuthUser
import com.amplifyframework.auth.AuthUserAttribute
import com.amplifyframework.auth.AuthUserAttributeKey
import com.amplifyframework.auth.cognito.exceptions.configuration.InvalidOauthConfigurationException
import com.amplifyframework.auth.cognito.exceptions.configuration.InvalidUserPoolConfigurationException
import com.amplifyframework.auth.cognito.exceptions.invalidstate.SignedInException
import com.amplifyframework.auth.cognito.exceptions.service.CodeDeliveryFailureException
import com.amplifyframework.auth.cognito.exceptions.service.HostedUISignOutException
import com.amplifyframework.auth.cognito.exceptions.service.InvalidAccountTypeException
import com.amplifyframework.auth.cognito.exceptions.service.UserCancelledException
import com.amplifyframework.auth.cognito.helpers.AuthHelper
import com.amplifyframework.auth.cognito.helpers.HostedUIHelper
import com.amplifyframework.auth.cognito.helpers.SessionHelper
import com.amplifyframework.auth.cognito.helpers.SignInChallengeHelper
import com.amplifyframework.auth.cognito.helpers.identityProviderName
import com.amplifyframework.auth.cognito.options.AWSCognitoAuthConfirmResetPasswordOptions
import com.amplifyframework.auth.cognito.options.AWSCognitoAuthConfirmSignInOptions
import com.amplifyframework.auth.cognito.options.AWSCognitoAuthConfirmSignUpOptions
import com.amplifyframework.auth.cognito.options.AWSCognitoAuthResendSignUpCodeOptions
import com.amplifyframework.auth.cognito.options.AWSCognitoAuthResendUserAttributeConfirmationCodeOptions
import com.amplifyframework.auth.cognito.options.AWSCognitoAuthSignInOptions
import com.amplifyframework.auth.cognito.options.AWSCognitoAuthSignOutOptions
import com.amplifyframework.auth.cognito.options.AWSCognitoAuthSignUpOptions
import com.amplifyframework.auth.cognito.options.AWSCognitoAuthUpdateUserAttributeOptions
import com.amplifyframework.auth.cognito.options.AWSCognitoAuthUpdateUserAttributesOptions
import com.amplifyframework.auth.cognito.options.AWSCognitoAuthWebUISignInOptions
import com.amplifyframework.auth.cognito.options.AuthFlowType
import com.amplifyframework.auth.cognito.options.FederateToIdentityPoolOptions
import com.amplifyframework.auth.cognito.result.AWSCognitoAuthSignOutResult
import com.amplifyframework.auth.cognito.result.FederateToIdentityPoolResult
import com.amplifyframework.auth.cognito.result.GlobalSignOutError
import com.amplifyframework.auth.cognito.result.HostedUIError
import com.amplifyframework.auth.cognito.result.RevokeTokenError
import com.amplifyframework.auth.cognito.usecases.ResetPasswordUseCase
import com.amplifyframework.auth.exceptions.ConfigurationException
import com.amplifyframework.auth.exceptions.InvalidStateException
import com.amplifyframework.auth.exceptions.SessionExpiredException
import com.amplifyframework.auth.exceptions.SignedOutException
import com.amplifyframework.auth.exceptions.UnknownException
import com.amplifyframework.auth.options.AuthConfirmResetPasswordOptions
import com.amplifyframework.auth.options.AuthConfirmSignInOptions
import com.amplifyframework.auth.options.AuthConfirmSignUpOptions
import com.amplifyframework.auth.options.AuthFetchSessionOptions
import com.amplifyframework.auth.options.AuthResendSignUpCodeOptions
import com.amplifyframework.auth.options.AuthResendUserAttributeConfirmationCodeOptions
import com.amplifyframework.auth.options.AuthResetPasswordOptions
import com.amplifyframework.auth.options.AuthSignInOptions
import com.amplifyframework.auth.options.AuthSignOutOptions
import com.amplifyframework.auth.options.AuthSignUpOptions
import com.amplifyframework.auth.options.AuthUpdateUserAttributeOptions
import com.amplifyframework.auth.options.AuthUpdateUserAttributesOptions
import com.amplifyframework.auth.options.AuthWebUISignInOptions
import com.amplifyframework.auth.result.AuthResetPasswordResult
import com.amplifyframework.auth.result.AuthSignInResult
import com.amplifyframework.auth.result.AuthSignOutResult
import com.amplifyframework.auth.result.AuthSignUpResult
import com.amplifyframework.auth.result.AuthUpdateAttributeResult
import com.amplifyframework.auth.result.step.AuthNextSignInStep
import com.amplifyframework.auth.result.step.AuthNextSignUpStep
import com.amplifyframework.auth.result.step.AuthNextUpdateAttributeStep
import com.amplifyframework.auth.result.step.AuthSignInStep
import com.amplifyframework.auth.result.step.AuthSignUpStep
import com.amplifyframework.auth.result.step.AuthUpdateAttributeStep
import com.amplifyframework.core.Action
import com.amplifyframework.core.Amplify
import com.amplifyframework.core.Consumer
import com.amplifyframework.hub.HubChannel
import com.amplifyframework.hub.HubEvent
import com.amplifyframework.logging.Logger
import com.amplifyframework.statemachine.StateChangeListenerToken
import com.amplifyframework.statemachine.codegen.data.AmplifyCredential
import com.amplifyframework.statemachine.codegen.data.AuthConfiguration
import com.amplifyframework.statemachine.codegen.data.DeviceMetadata
import com.amplifyframework.statemachine.codegen.data.FederatedToken
import com.amplifyframework.statemachine.codegen.data.HostedUIErrorData
import com.amplifyframework.statemachine.codegen.data.SignInData
import com.amplifyframework.statemachine.codegen.data.SignInMethod
import com.amplifyframework.statemachine.codegen.data.SignOutData
import com.amplifyframework.statemachine.codegen.errors.SessionError
import com.amplifyframework.statemachine.codegen.events.AuthEvent
import com.amplifyframework.statemachine.codegen.events.AuthenticationEvent
import com.amplifyframework.statemachine.codegen.events.AuthorizationEvent
import com.amplifyframework.statemachine.codegen.events.DeleteUserEvent
import com.amplifyframework.statemachine.codegen.events.HostedUIEvent
import com.amplifyframework.statemachine.codegen.events.SignInChallengeEvent
import com.amplifyframework.statemachine.codegen.events.SignOutEvent
import com.amplifyframework.statemachine.codegen.states.AuthState
import com.amplifyframework.statemachine.codegen.states.AuthenticationState
import com.amplifyframework.statemachine.codegen.states.AuthorizationState
import com.amplifyframework.statemachine.codegen.states.DeleteUserState
import com.amplifyframework.statemachine.codegen.states.HostedUISignInState
import com.amplifyframework.statemachine.codegen.states.SRPSignInState
import com.amplifyframework.statemachine.codegen.states.SignInChallengeState
import com.amplifyframework.statemachine.codegen.states.SignInState
import com.amplifyframework.statemachine.codegen.states.SignOutState
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
internal class RealAWSCognitoAuthPlugin(
private val configuration: AuthConfiguration,
private val authEnvironment: AuthEnvironment,
private val authStateMachine: AuthStateMachine,
private val logger: Logger
) : AuthCategoryBehavior {
private val lastPublishedHubEventName = AtomicReference<String>()
init {
addAuthStateChangeListener()
configureAuthStates()
}
fun escapeHatch() = authEnvironment.cognitoAuthService
@WorkerThread
@Throws(AmplifyException::class)
fun initialize() {
val token = StateChangeListenerToken()
val latch = CountDownLatch(1)
authStateMachine.listen(
token,
{ authState ->
if (authState is AuthState.Configured) {
authStateMachine.cancel(token)
latch.countDown()
}
},
{ }
)
try {
latch.await(10, TimeUnit.SECONDS)
} catch (e: Exception) {
throw AmplifyException(
"Failed to configure auth plugin.",
"Make sure your amplifyconfiguration.json is valid"
)
}
}
override fun signUp(
username: String,
password: String,
options: AuthSignUpOptions,
onSuccess: Consumer<AuthSignUpResult>,
onError: Consumer<AuthException>
) {
authStateMachine.getCurrentState { authState ->
when (authState.authNState) {
is AuthenticationState.NotConfigured -> onError.accept(
InvalidUserPoolConfigurationException()
)
is AuthenticationState.SignedIn, is AuthenticationState.SignedOut -> GlobalScope.launch {
_signUp(username, password, options, onSuccess, onError)
}
else -> onError.accept(InvalidStateException())
}
}
}
private suspend fun _signUp(
username: String,
password: String,
options: AuthSignUpOptions,
onSuccess: Consumer<AuthSignUpResult>,
onError: Consumer<AuthException>
) {
logger.verbose("SignUp Starting execution")
try {
val userAttributes = options.userAttributes.map {
AttributeType {
name = it.key.keyString
value = it.value
}
}
val encodedContextData = authEnvironment.getUserContextData(username)
val pinpointEndpointId = authEnvironment.getPinpointEndpointId()
val response = authEnvironment.cognitoAuthService.cognitoIdentityProviderClient?.signUp {
this.username = username
this.password = password
this.userAttributes = userAttributes
this.clientId = configuration.userPool?.appClient
this.secretHash = AuthHelper.getSecretHash(
username,
configuration.userPool?.appClient,
configuration.userPool?.appClientSecret
)
pinpointEndpointId?.let {
this.analyticsMetadata = AnalyticsMetadataType.invoke { analyticsEndpointId = it }
}
encodedContextData?.let { this.userContextData { encodedData = it } }
(options as? AWSCognitoAuthSignUpOptions)?.let {
this.validationData = it.validationData.mapNotNull { option ->
AttributeType {
name = option.key
value = option.value
}
}
this.clientMetadata = it.clientMetadata
}
}
val deliveryDetails = response?.codeDeliveryDetails?.let { details ->
mapOf(
"DESTINATION" to details.destination,
"MEDIUM" to details.deliveryMedium?.value,
"ATTRIBUTE" to details.attributeName
)
}
val authSignUpResult = if (response?.userConfirmed == true) {
AuthSignUpResult(
true,
AuthNextSignUpStep(
AuthSignUpStep.DONE,
mapOf(),
null
),
response.userSub
)
} else {
AuthSignUpResult(
false,
AuthNextSignUpStep(
AuthSignUpStep.CONFIRM_SIGN_UP_STEP,
mapOf(),
AuthCodeDeliveryDetails(
deliveryDetails?.getValue("DESTINATION") ?: "",
AuthCodeDeliveryDetails.DeliveryMedium.fromString(
deliveryDetails?.getValue("MEDIUM")
),
deliveryDetails?.getValue("ATTRIBUTE")
)
),
response?.userSub
)
}
onSuccess.accept(authSignUpResult)
logger.verbose("SignUp Execution complete")
} catch (exception: Exception) {
onError.accept(CognitoAuthExceptionConverter.lookup(exception, "Sign up failed."))
}
}
override fun confirmSignUp(
username: String,
confirmationCode: String,
onSuccess: Consumer<AuthSignUpResult>,
onError: Consumer<AuthException>
) {
confirmSignUp(username, confirmationCode, AuthConfirmSignUpOptions.defaults(), onSuccess, onError)
}
override fun confirmSignUp(
username: String,
confirmationCode: String,
options: AuthConfirmSignUpOptions,
onSuccess: Consumer<AuthSignUpResult>,
onError: Consumer<AuthException>
) {
authStateMachine.getCurrentState { authState ->
when (authState.authNState) {
is AuthenticationState.NotConfigured -> onError.accept(
InvalidUserPoolConfigurationException()
)
is AuthenticationState.SignedIn, is AuthenticationState.SignedOut -> GlobalScope.launch {
_confirmSignUp(username, confirmationCode, options, onSuccess, onError)
}
else -> onError.accept(InvalidStateException())
}
}
}
private suspend fun _confirmSignUp(
username: String,
confirmationCode: String,
options: AuthConfirmSignUpOptions,
onSuccess: Consumer<AuthSignUpResult>,
onError: Consumer<AuthException>
) {
logger.verbose("ConfirmSignUp Starting execution")
try {
val encodedContextData = authEnvironment.getUserContextData(username)
val pinpointEndpointId = authEnvironment.getPinpointEndpointId()
authEnvironment.cognitoAuthService.cognitoIdentityProviderClient?.confirmSignUp {
this.username = username
this.confirmationCode = confirmationCode
this.clientId = configuration.userPool?.appClient
this.secretHash = AuthHelper.getSecretHash(
username,
configuration.userPool?.appClient,
configuration.userPool?.appClientSecret
)
pinpointEndpointId?.let {
this.analyticsMetadata = AnalyticsMetadataType.invoke { analyticsEndpointId = it }
}
encodedContextData?.let { this.userContextData { encodedData = it } }
(options as? AWSCognitoAuthConfirmSignUpOptions)?.let {
this.clientMetadata = it.clientMetadata
}
}
val authSignUpResult = AuthSignUpResult(
true,
AuthNextSignUpStep(AuthSignUpStep.DONE, mapOf(), null),
null
)
onSuccess.accept(authSignUpResult)
logger.verbose("ConfirmSignUp Execution complete")
} catch (exception: Exception) {
onError.accept(
CognitoAuthExceptionConverter.lookup(exception, "Confirm sign up failed.")
)
}
}
override fun resendSignUpCode(
username: String,
onSuccess: Consumer<AuthCodeDeliveryDetails>,
onError: Consumer<AuthException>
) {
resendSignUpCode(username, AuthResendSignUpCodeOptions.defaults(), onSuccess, onError)
}
override fun resendSignUpCode(
username: String,
options: AuthResendSignUpCodeOptions,
onSuccess: Consumer<AuthCodeDeliveryDetails>,
onError: Consumer<AuthException>
) {
authStateMachine.getCurrentState { authState ->
when (authState.authNState) {
is AuthenticationState.NotConfigured -> onError.accept(
InvalidUserPoolConfigurationException()
)
is AuthenticationState.SignedIn, is AuthenticationState.SignedOut -> GlobalScope.launch {
_resendSignUpCode(username, options, onSuccess, onError)
}
else -> onError.accept(InvalidStateException())
}
}
}
private suspend fun _resendSignUpCode(
username: String,
options: AuthResendSignUpCodeOptions,
onSuccess: Consumer<AuthCodeDeliveryDetails>,
onError: Consumer<AuthException>
) {
logger.verbose("ResendSignUpCode Starting execution")
try {
val metadata = (options as? AWSCognitoAuthResendSignUpCodeOptions)?.metadata
val encodedContextData = authEnvironment.getUserContextData(username)
val pinpointEndpointId = authEnvironment.getPinpointEndpointId()
val response = authEnvironment.cognitoAuthService.cognitoIdentityProviderClient?.resendConfirmationCode {
clientId = configuration.userPool?.appClient
this.username = username
secretHash = AuthHelper.getSecretHash(
username,
configuration.userPool?.appClient,
configuration.userPool?.appClientSecret
)
clientMetadata = metadata
pinpointEndpointId?.let {
this.analyticsMetadata = AnalyticsMetadataType.invoke { analyticsEndpointId = it }
}
encodedContextData?.let { this.userContextData { encodedData = it } }
}
val deliveryDetails = response?.codeDeliveryDetails?.let { details ->
mapOf(
"DESTINATION" to details.destination,
"MEDIUM" to details.deliveryMedium?.value,
"ATTRIBUTE" to details.attributeName
)
}
val codeDeliveryDetails = AuthCodeDeliveryDetails(
deliveryDetails?.getValue("DESTINATION") ?: "",
AuthCodeDeliveryDetails.DeliveryMedium.fromString(
deliveryDetails?.getValue("MEDIUM")
),
deliveryDetails?.getValue("ATTRIBUTE")
)
onSuccess.accept(codeDeliveryDetails)
logger.verbose("ResendSignUpCode Execution complete")
} catch (exception: Exception) {
onError.accept(CognitoAuthExceptionConverter.lookup(exception, "Resend sign up code failed."))
}
}
override fun signIn(
username: String?,
password: String?,
onSuccess: Consumer<AuthSignInResult>,
onError: Consumer<AuthException>
) {
signIn(username, password, AuthSignInOptions.defaults(), onSuccess, onError)
}
override fun signIn(
username: String?,
password: String?,
options: AuthSignInOptions,
onSuccess: Consumer<AuthSignInResult>,
onError: Consumer<AuthException>
) {
authStateMachine.getCurrentState { authState ->
when (authState.authNState) {
is AuthenticationState.NotConfigured -> onError.accept(
InvalidUserPoolConfigurationException()
)
// Continue sign in
is AuthenticationState.SignedOut, is AuthenticationState.Configured -> {
val signInOptions = options as? AWSCognitoAuthSignInOptions ?: AWSCognitoAuthSignInOptions.builder()
.authFlowType(configuration.authFlowType)
.build()
_signIn(username, password, signInOptions, onSuccess, onError)
}
is AuthenticationState.SignedIn -> onError.accept(SignedInException())
else -> onError.accept(InvalidStateException())
}
}
}
private fun _signIn(
username: String?,
password: String?,
options: AWSCognitoAuthSignInOptions,
onSuccess: Consumer<AuthSignInResult>,
onError: Consumer<AuthException>
) {
val token = StateChangeListenerToken()
authStateMachine.listen(
token,
{ authState ->
val authNState = authState.authNState
val authZState = authState.authZState
when {
authNState is AuthenticationState.SigningIn -> {
val signInState = authNState.signInState
val srpSignInState = (signInState as? SignInState.SigningInWithSRP)?.srpSignInState
val challengeState = (signInState as? SignInState.ResolvingChallenge)?.challengeState
when {
srpSignInState is SRPSignInState.Error -> {
authStateMachine.cancel(token)
onError.accept(
CognitoAuthExceptionConverter.lookup(srpSignInState.exception, "Sign in failed.")
)
}
signInState is SignInState.Error -> {
authStateMachine.cancel(token)
onError.accept(
CognitoAuthExceptionConverter.lookup(signInState.exception, "Sign in failed.")
)
}
challengeState is SignInChallengeState.WaitingForAnswer -> {
authStateMachine.cancel(token)
SignInChallengeHelper.getNextStep(challengeState.challenge, onSuccess, onError)
}
}
}
authNState is AuthenticationState.SignedIn &&
authZState is AuthorizationState.SessionEstablished -> {
authStateMachine.cancel(token)
val authSignInResult = AuthSignInResult(
true,
AuthNextSignInStep(AuthSignInStep.DONE, mapOf(), null)
)
onSuccess.accept(authSignInResult)
sendHubEvent(AuthChannelEventName.SIGNED_IN.toString())
}
else -> Unit
}
},
{
val signInData = when (options.authFlowType ?: configuration.authFlowType) {
AuthFlowType.USER_SRP_AUTH -> {
SignInData.SRPSignInData(username, password, options.metadata)
}
AuthFlowType.CUSTOM_AUTH, AuthFlowType.CUSTOM_AUTH_WITHOUT_SRP -> {
SignInData.CustomAuthSignInData(username, options.metadata)
}
AuthFlowType.CUSTOM_AUTH_WITH_SRP -> {
SignInData.CustomSRPAuthSignInData(username, password, options.metadata)
}
AuthFlowType.USER_PASSWORD_AUTH -> {
SignInData.MigrationAuthSignInData(username, password, options.metadata)
}
}
val event = AuthenticationEvent(AuthenticationEvent.EventType.SignInRequested(signInData))
authStateMachine.send(event)
}
)
}
override fun confirmSignIn(
challengeResponse: String,
onSuccess: Consumer<AuthSignInResult>,
onError: Consumer<AuthException>
) {
confirmSignIn(challengeResponse, AuthConfirmSignInOptions.defaults(), onSuccess, onError)
}
override fun confirmSignIn(
challengeResponse: String,
options: AuthConfirmSignInOptions,
onSuccess: Consumer<AuthSignInResult>,
onError: Consumer<AuthException>
) {
authStateMachine.getCurrentState { authState ->
val authNState = authState.authNState
val signInState = (authNState as? AuthenticationState.SigningIn)?.signInState
when ((signInState as? SignInState.ResolvingChallenge)?.challengeState) {
is SignInChallengeState.WaitingForAnswer -> {
_confirmSignIn(challengeResponse, options, onSuccess, onError)
}
else -> onError.accept(InvalidStateException())
}
}
}
private fun _confirmSignIn(
challengeResponse: String,
options: AuthConfirmSignInOptions,
onSuccess: Consumer<AuthSignInResult>,
onError: Consumer<AuthException>
) {
val token = StateChangeListenerToken()
authStateMachine.listen(
token,
{ authState ->
val authNState = authState.authNState
val authZState = authState.authZState
val signInState = (authNState as? AuthenticationState.SigningIn)?.signInState
val challengeState = (signInState as? SignInState.ResolvingChallenge)?.challengeState
when {
authNState is AuthenticationState.SignedIn &&
authZState is AuthorizationState.SessionEstablished -> {
authStateMachine.cancel(token)
val authSignInResult = AuthSignInResult(
true,
AuthNextSignInStep(AuthSignInStep.DONE, mapOf(), null)
)
onSuccess.accept(authSignInResult)
sendHubEvent(AuthChannelEventName.SIGNED_IN.toString())
}
signInState is SignInState.Error -> {
authStateMachine.cancel(token)
onError.accept(
CognitoAuthExceptionConverter.lookup(signInState.exception, "Confirm Sign in failed.")
)
}
}
},
{
val awsCognitoConfirmSignInOptions = options as? AWSCognitoAuthConfirmSignInOptions
val event = SignInChallengeEvent(
SignInChallengeEvent.EventType.VerifyChallengeAnswer(
challengeResponse,
awsCognitoConfirmSignInOptions?.metadata ?: mapOf()
)
)
authStateMachine.send(event)
}
)
}
override fun signInWithSocialWebUI(
provider: AuthProvider,
callingActivity: Activity,
onSuccess: Consumer<AuthSignInResult>,
onError: Consumer<AuthException>
) {
signInWithSocialWebUI(
provider,
callingActivity,
AWSCognitoAuthWebUISignInOptions.builder().build(),
onSuccess,
onError
)
}
override fun signInWithSocialWebUI(
provider: AuthProvider,
callingActivity: Activity,
options: AuthWebUISignInOptions,
onSuccess: Consumer<AuthSignInResult>,
onError: Consumer<AuthException>
) {
signInWithHostedUI(
provider = provider,
callingActivity = callingActivity,
options = options,
onSuccess = onSuccess,
onError = onError
)
}
override fun signInWithWebUI(
callingActivity: Activity,
onSuccess: Consumer<AuthSignInResult>,
onError: Consumer<AuthException>
) {
signInWithWebUI(callingActivity, AuthWebUISignInOptions.builder().build(), onSuccess, onError)
}
override fun signInWithWebUI(
callingActivity: Activity,
options: AuthWebUISignInOptions,
onSuccess: Consumer<AuthSignInResult>,
onError: Consumer<AuthException>
) {
signInWithHostedUI(
callingActivity = callingActivity,
options = options,
onSuccess = onSuccess,
onError = onError
)
}
private fun signInWithHostedUI(
provider: AuthProvider? = null,
callingActivity: Activity,
options: AuthWebUISignInOptions,
onSuccess: Consumer<AuthSignInResult>,
onError: Consumer<AuthException>
) {
authStateMachine.getCurrentState { authState ->
when (authState.authNState) {
is AuthenticationState.NotConfigured -> onError.accept(
InvalidUserPoolConfigurationException()
)
// Continue sign in
is AuthenticationState.SignedOut -> {
if (configuration.oauth == null) {
onError.accept(InvalidOauthConfigurationException())
return@getCurrentState
}
_signInWithHostedUI(
callingActivity = callingActivity,
options = options,
onSuccess = onSuccess,
onError = onError,
provider = provider
)
}
is AuthenticationState.SignedIn -> onError.accept(SignedInException())
else -> onError.accept(InvalidStateException())
}
}
}
private fun _signInWithHostedUI(
callingActivity: Activity,
options: AuthWebUISignInOptions,
onSuccess: Consumer<AuthSignInResult>,
onError: Consumer<AuthException>,
provider: AuthProvider? = null
) {
val token = StateChangeListenerToken()
authStateMachine.listen(
token,
{ authState ->
val authNState = authState.authNState
val authZState = authState.authZState
when {
authNState is AuthenticationState.SigningIn -> {
val hostedUISignInState = authNState.signInState.hostedUISignInState
if (hostedUISignInState is HostedUISignInState.Error) {
authStateMachine.cancel(token)
val exception = hostedUISignInState.exception
onError.accept(
if (exception is AuthException) {
exception
} else {
UnknownException("Sign in failed", exception)
}
)
authStateMachine.send(AuthenticationEvent(AuthenticationEvent.EventType.CancelSignIn()))
}
}
authNState is AuthenticationState.SignedIn &&
authZState is AuthorizationState.SessionEstablished -> {
authStateMachine.cancel(token)
val authSignInResult =
AuthSignInResult(
true,
AuthNextSignInStep(AuthSignInStep.DONE, mapOf(), null)
)
onSuccess.accept(authSignInResult)
sendHubEvent(AuthChannelEventName.SIGNED_IN.toString())
}
else -> Unit
}
},
{
val hostedUIOptions = HostedUIHelper.createHostedUIOptions(callingActivity, provider, options)
authStateMachine.send(
AuthenticationEvent(
AuthenticationEvent.EventType.SignInRequested(
SignInData.HostedUISignInData(hostedUIOptions)
)
)
)
}
)
}
override fun handleWebUISignInResponse(intent: Intent?) {
authStateMachine.getCurrentState {
val callbackUri = intent?.data
when (val authNState = it.authNState) {
is AuthenticationState.SigningOut -> {
(authNState.signOutState as? SignOutState.SigningOutHostedUI)?.let { signOutState ->
if (callbackUri == null && signOutState.signedInData.signInMethod !=
SignInMethod.ApiBased(SignInMethod.ApiBased.AuthType.UNKNOWN)
) {
authStateMachine.send(
SignOutEvent(SignOutEvent.EventType.UserCancelled(signOutState.signedInData))
)
} else {
val hostedUIErrorData = if (callbackUri == null) {
// This error will be appended if sign out redirect failed with an UNKNOWN sign in
// method. We will provide a URL to allow the developer to manually retry.
HostedUIErrorData(
url = authEnvironment.hostedUIClient?.createSignOutUri()?.toString(),
error = HostedUISignOutException(authEnvironment.hostedUIClient != null)
)
} else {
null
}
if (signOutState.globalSignOut) {
authStateMachine.send(
SignOutEvent(
SignOutEvent.EventType.SignOutGlobally(
signOutState.signedInData,
hostedUIErrorData
)
)
)
} else {
authStateMachine.send(
SignOutEvent(
SignOutEvent.EventType.RevokeToken(
signOutState.signedInData,
hostedUIErrorData
)
)
)
}
}
}
}
is AuthenticationState.SigningIn -> {
if (callbackUri == null) {
authStateMachine.send(
HostedUIEvent(
HostedUIEvent.EventType.ThrowError(
UserCancelledException(
"The user cancelled the sign-in attempt, so it did not complete.",
"To recover: catch this error, and show the sign-in screen again."
)
)
)
)
} else {
authStateMachine.send(HostedUIEvent(HostedUIEvent.EventType.FetchToken(callbackUri)))
}
}
else -> {
logger.warn(
"Received handleWebUIResponse but ignoring because the user is not currently signing in " +
"or signing out"
)
Unit
}
}
}
}
private suspend fun getSession(): AWSCognitoAuthSession {
return suspendCoroutine { continuation ->
fetchAuthSession(
{ authSession ->
if (authSession is AWSCognitoAuthSession) {
continuation.resume(authSession)
} else {
continuation.resumeWithException(
UnknownException(
message = "fetchAuthSession did not return a type of AWSCognitoAuthSession"
)
)
}
},
{ continuation.resumeWithException(it) }
)
}
}
override fun fetchAuthSession(onSuccess: Consumer<AuthSession>, onError: Consumer<AuthException>) {
fetchAuthSession(AuthFetchSessionOptions.defaults(), onSuccess, onError)
}
override fun fetchAuthSession(
options: AuthFetchSessionOptions,
onSuccess: Consumer<AuthSession>,
onError: Consumer<AuthException>
) {
val forceRefresh = options.forceRefresh
authStateMachine.getCurrentState { authState ->
when (val authZState = authState.authZState) {
is AuthorizationState.Configured -> {
authStateMachine.send(AuthorizationEvent(AuthorizationEvent.EventType.FetchUnAuthSession))
_fetchAuthSession(onSuccess, onError)
}
is AuthorizationState.SessionEstablished -> {
val credential = authZState.amplifyCredential
if (!credential.isValid() || forceRefresh) {
if (credential is AmplifyCredential.IdentityPoolFederated) {
authStateMachine.send(
AuthorizationEvent(
AuthorizationEvent.EventType.StartFederationToIdentityPool(
credential.federatedToken,
credential.identityId,
credential
)
)
)
} else {
authStateMachine.send(
AuthorizationEvent(AuthorizationEvent.EventType.RefreshSession(credential))
)
}
_fetchAuthSession(onSuccess, onError)
} else onSuccess.accept(credential.getCognitoSession())
}
is AuthorizationState.Error -> {
val error = authZState.exception
if (error is SessionError) {
val amplifyCredential = error.amplifyCredential
if (amplifyCredential is AmplifyCredential.IdentityPoolFederated) {
authStateMachine.send(
AuthorizationEvent(
AuthorizationEvent.EventType.StartFederationToIdentityPool(
amplifyCredential.federatedToken,
amplifyCredential.identityId,
amplifyCredential
)
)
)
} else {
authStateMachine.send(
AuthorizationEvent(AuthorizationEvent.EventType.RefreshSession(amplifyCredential))
)
}
_fetchAuthSession(onSuccess, onError)
} else {
onError.accept(InvalidStateException())
}
}
else -> onError.accept(InvalidStateException())
}
}
}
private fun _fetchAuthSession(
onSuccess: Consumer<AuthSession>,
onError: Consumer<AuthException>
) {
val token = StateChangeListenerToken()
authStateMachine.listen(
token,
{ authState ->
when (val authZState = authState.authZState) {
is AuthorizationState.SessionEstablished -> {
authStateMachine.cancel(token)
onSuccess.accept(authZState.amplifyCredential.getCognitoSession())
}
is AuthorizationState.Error -> {
authStateMachine.cancel(token)
when (val error = authZState.exception) {
is SessionError -> {
when (error.exception) {
is SignedOutException -> {
onSuccess.accept(error.amplifyCredential.getCognitoSession(error.exception))
}
is SessionExpiredException -> {
onSuccess.accept(AmplifyCredential.Empty.getCognitoSession(error.exception))
sendHubEvent(AuthChannelEventName.SESSION_EXPIRED.toString())
}
else -> {
val errorResult = UnknownException("Fetch auth session failed.", error)
onSuccess.accept(error.amplifyCredential.getCognitoSession(errorResult))
}
}
}
is ConfigurationException -> {
val errorResult = InvalidAccountTypeException(error)
onSuccess.accept(AmplifyCredential.Empty.getCognitoSession(errorResult))
}
else -> {
val errorResult = UnknownException("Fetch auth session failed.", error)
onSuccess.accept(AmplifyCredential.Empty.getCognitoSession(errorResult))
}
}
}
else -> Unit
}
},
null
)
}
override fun rememberDevice(onSuccess: Action, onError: Consumer<AuthException>) {
authStateMachine.getCurrentState { authState ->
when (val state = authState.authNState) {
is AuthenticationState.SignedIn -> {
updateDevice(
(state.deviceMetadata as? DeviceMetadata.Metadata)?.deviceKey,
DeviceRememberedStatusType.Remembered,
onSuccess,
onError
)
}
is AuthenticationState.SignedOut -> {
onError.accept(SignedOutException())
}
else -> {
onError.accept(InvalidStateException())
}
}
}
}
override fun forgetDevice(onSuccess: Action, onError: Consumer<AuthException>) {
forgetDevice(AuthDevice.fromId(""), onSuccess, onError)
}
private fun updateDevice(