Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(auth): Create use cases for device management APIs #2979

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -297,16 +297,16 @@ class AWSCognitoAuthPlugin : AuthPlugin<AWSCognitoAuthService>() {
enqueue(onSuccess, onError) { queueFacade.fetchAuthSession() }

override fun rememberDevice(onSuccess: Action, onError: Consumer<AuthException>) =
enqueue(onSuccess, onError) { queueFacade.rememberDevice() }
enqueue(onSuccess, onError) { useCaseFactory.rememberDevice().execute() }

override fun forgetDevice(onSuccess: Action, onError: Consumer<AuthException>) =
enqueue(onSuccess, onError) { queueFacade.forgetDevice() }
enqueue(onSuccess, onError) { useCaseFactory.forgetDevice().execute() }

override fun forgetDevice(device: AuthDevice, onSuccess: Action, onError: Consumer<AuthException>) =
enqueue(onSuccess, onError) { queueFacade.forgetDevice(device) }
enqueue(onSuccess, onError) { useCaseFactory.forgetDevice().execute(device) }

override fun fetchDevices(onSuccess: Consumer<List<AuthDevice>>, onError: Consumer<AuthException>) =
enqueue(onSuccess, onError) { queueFacade.fetchDevices() }
enqueue(onSuccess, onError) { useCaseFactory.fetchDevices().execute() }

override fun resetPassword(
username: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import com.amplifyframework.auth.cognito.actions.SignUpCognitoActions
import com.amplifyframework.auth.cognito.actions.UserAuthSignInCognitoActions
import com.amplifyframework.auth.cognito.actions.WebAuthnSignInCognitoActions
import com.amplifyframework.auth.exceptions.InvalidStateException
import com.amplifyframework.auth.exceptions.SignedOutException
import com.amplifyframework.statemachine.Environment
import com.amplifyframework.statemachine.StateMachine
import com.amplifyframework.statemachine.StateMachineResolver
Expand Down Expand Up @@ -137,3 +138,12 @@ internal suspend inline fun <reified T : AuthenticationState> AuthStateMachine.r
)
}
}

// Returns the SignedInState or throws SignedOutException or InvalidStateException
internal suspend fun AuthStateMachine.requireSignedInState(): AuthenticationState.SignedIn {
return when (val state = getCurrentState().authNState) {
is AuthenticationState.SignedIn -> state
is AuthenticationState.SignedOut -> throw SignedOutException()
else -> throw InvalidStateException()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package com.amplifyframework.auth.cognito
import android.app.Activity
import android.content.Intent
import com.amplifyframework.auth.AuthCodeDeliveryDetails
import com.amplifyframework.auth.AuthDevice
import com.amplifyframework.auth.AuthProvider
import com.amplifyframework.auth.AuthSession
import com.amplifyframework.auth.AuthUser
Expand Down Expand Up @@ -259,43 +258,6 @@ internal class KotlinAuthFacadeInternal(private val delegate: RealAWSCognitoAuth
}
}

suspend fun rememberDevice() {
return suspendCoroutine { continuation ->
delegate.rememberDevice(
{ continuation.resume(Unit) },
{ continuation.resumeWithException(it) }
)
}
}

suspend fun forgetDevice() {
return suspendCoroutine { continuation ->
delegate.forgetDevice(
{ continuation.resume(Unit) },
{ continuation.resumeWithException(it) }
)
}
}

suspend fun forgetDevice(device: AuthDevice) {
return suspendCoroutine { continuation ->
delegate.forgetDevice(
device,
{ continuation.resume(Unit) },
{ continuation.resumeWithException(it) }
)
}
}

suspend fun fetchDevices(): List<AuthDevice> {
return suspendCoroutine { continuation ->
delegate.fetchDevices(
{ continuation.resume(it) },
{ continuation.resumeWithException(it) }
)
}
}

suspend fun resetPassword(
username: String
): AuthResetPasswordResult {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,11 @@ import aws.sdk.kotlin.services.cognitoidentityprovider.model.AnalyticsMetadataTy
import aws.sdk.kotlin.services.cognitoidentityprovider.model.AttributeType
import aws.sdk.kotlin.services.cognitoidentityprovider.model.ChallengeNameType
import aws.sdk.kotlin.services.cognitoidentityprovider.model.ChangePasswordRequest
import aws.sdk.kotlin.services.cognitoidentityprovider.model.DeviceRememberedStatusType
import aws.sdk.kotlin.services.cognitoidentityprovider.model.EmailMfaSettingsType
import aws.sdk.kotlin.services.cognitoidentityprovider.model.ForgetDeviceRequest
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.SmsMfaSettingsType
import aws.sdk.kotlin.services.cognitoidentityprovider.model.SoftwareTokenMfaSettingsType
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.VerifySoftwareTokenResponseType
Expand All @@ -48,7 +44,6 @@ import com.amplifyframework.auth.AWSCredentials
import com.amplifyframework.auth.AWSTemporaryCredentials
import com.amplifyframework.auth.AuthChannelEventName
import com.amplifyframework.auth.AuthCodeDeliveryDetails
import com.amplifyframework.auth.AuthDevice
import com.amplifyframework.auth.AuthException
import com.amplifyframework.auth.AuthFactorType
import com.amplifyframework.auth.AuthProvider
Expand Down Expand Up @@ -1497,135 +1492,6 @@ internal class RealAWSCognitoAuthPlugin(
)
}

fun rememberDevice(onSuccess: Action, onError: Consumer<AuthException>) {
authStateMachine.getCurrentState { authState ->
when (val state = authState.authNState) {
is AuthenticationState.SignedIn -> {
GlobalScope.launch {
updateDevice(
authEnvironment.getDeviceMetadata(state.signedInData.username)?.deviceKey,
DeviceRememberedStatusType.Remembered,
onSuccess,
onError
)
}
}
is AuthenticationState.SignedOut -> {
onError.accept(SignedOutException())
}
else -> {
onError.accept(InvalidStateException())
}
}
}
}

fun forgetDevice(onSuccess: Action, onError: Consumer<AuthException>) {
forgetDevice(AuthDevice.fromId(""), onSuccess, onError)
}

private fun updateDevice(
alternateDeviceId: String?,
rememberedStatusType: DeviceRememberedStatusType,
onSuccess: Action,
onError: Consumer<AuthException>
) {
GlobalScope.async {
try {
val tokens = getSession().userPoolTokensResult
authEnvironment.cognitoAuthService.cognitoIdentityProviderClient?.updateDeviceStatus(
UpdateDeviceStatusRequest.invoke {
accessToken = tokens.value?.accessToken
deviceKey = alternateDeviceId
deviceRememberedStatus = rememberedStatusType
}
)
onSuccess.call()
} catch (e: Exception) {
onError.accept(CognitoAuthExceptionConverter.lookup(e, "Update device ID failed."))
}
}
}

fun forgetDevice(device: AuthDevice, onSuccess: Action, onError: Consumer<AuthException>) {
authStateMachine.getCurrentState { authState ->
when (val authNState = authState.authNState) {
is AuthenticationState.SignedIn -> {
GlobalScope.launch {
try {
if (device.id.isEmpty()) {
val deviceKey = authEnvironment.getDeviceMetadata(authNState.signedInData.username)
?.deviceKey
forgetDevice(deviceKey)
} else {
forgetDevice(device.id)
}
onSuccess.call()
} catch (e: Exception) {
onError.accept(CognitoAuthExceptionConverter.lookup(e, "Failed to forget device."))
}
}
}
is AuthenticationState.SignedOut -> {
onError.accept(SignedOutException())
}
else -> {
onError.accept(InvalidStateException())
}
}
}
}

private suspend fun forgetDevice(alternateDeviceId: String?) {
val tokens = getSession().userPoolTokensResult
authEnvironment.cognitoAuthService.cognitoIdentityProviderClient?.forgetDevice(
ForgetDeviceRequest.invoke {
accessToken = tokens.value?.accessToken
deviceKey = alternateDeviceId
}
)
}

fun fetchDevices(onSuccess: Consumer<List<AuthDevice>>, onError: Consumer<AuthException>) {
authStateMachine.getCurrentState { authState ->
when (authState.authNState) {
is AuthenticationState.SignedIn -> {
_fetchDevices(onSuccess, onError)
}
is AuthenticationState.SignedOut -> {
onError.accept(SignedOutException())
}
else -> {
onError.accept(InvalidStateException())
}
}
}
}

private fun _fetchDevices(onSuccess: Consumer<List<AuthDevice>>, onError: Consumer<AuthException>) {
GlobalScope.async {
try {
val tokens = getSession().userPoolTokensResult
val response =
authEnvironment.cognitoAuthService.cognitoIdentityProviderClient?.listDevices(
ListDevicesRequest.invoke {
accessToken = tokens.value?.accessToken
}
)

val devices = response?.devices?.map { device ->
val id = device.deviceKey ?: ""
val name = device.deviceAttributes?.find { it.name == "device_name" }?.value
AuthDevice.fromId(id, name)
} ?: emptyList()

onSuccess.accept(devices)
} catch (e: Exception) {
onError.accept(CognitoAuthExceptionConverter.lookup(e, "Fetch devices failed."))
}
}
}

@OptIn(DelicateCoroutinesApi::class)
fun resetPassword(
username: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,8 @@ import aws.sdk.kotlin.services.cognitoidentityprovider.startWebAuthnRegistration
import com.amplifyframework.auth.cognito.AuthStateMachine
import com.amplifyframework.auth.cognito.helpers.WebAuthnHelper
import com.amplifyframework.auth.cognito.helpers.authLogger
import com.amplifyframework.auth.cognito.requireAuthenticationState
import com.amplifyframework.auth.cognito.requireSignedInState
import com.amplifyframework.auth.options.AuthAssociateWebAuthnCredentialsOptions
import com.amplifyframework.statemachine.codegen.states.AuthenticationState.SignedIn
import com.amplifyframework.statemachine.util.mask
import com.amplifyframework.util.JsonDocument
import com.amplifyframework.util.toJsonString
Expand All @@ -40,7 +39,7 @@ internal class AssociateWebAuthnCredentialUseCase(
@Suppress("UNUSED_PARAMETER")
suspend fun execute(callingActivity: Activity, options: AuthAssociateWebAuthnCredentialsOptions) {
// User must be signed in to call this API
stateMachine.requireAuthenticationState<SignedIn>()
stateMachine.requireSignedInState()

val accessToken = fetchAuthSession.execute().accessToken

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,24 @@
fetchAuthSession = fetchAuthSession(),
stateMachine = stateMachine
)

fun rememberDevice() = RememberDeviceUseCase(
client = authEnvironment.requireIdentityProviderClient(),
fetchAuthSession = fetchAuthSession(),
stateMachine = stateMachine,
environment = authEnvironment

Check warning on line 55 in aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/usecases/AuthUseCaseFactory.kt

View check run for this annotation

Codecov / codecov/patch

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/usecases/AuthUseCaseFactory.kt#L51-L55

Added lines #L51 - L55 were not covered by tests
)

fun forgetDevice() = ForgetDeviceUseCase(
client = authEnvironment.requireIdentityProviderClient(),
fetchAuthSession = fetchAuthSession(),
stateMachine = stateMachine,
environment = authEnvironment

Check warning on line 62 in aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/usecases/AuthUseCaseFactory.kt

View check run for this annotation

Codecov / codecov/patch

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/usecases/AuthUseCaseFactory.kt#L58-L62

Added lines #L58 - L62 were not covered by tests
)

fun fetchDevices() = FetchDevicesUseCase(
client = authEnvironment.requireIdentityProviderClient(),
fetchAuthSession = fetchAuthSession(),
stateMachine = stateMachine

Check warning on line 68 in aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/usecases/AuthUseCaseFactory.kt

View check run for this annotation

Codecov / codecov/patch

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/usecases/AuthUseCaseFactory.kt#L65-L68

Added lines #L65 - L68 were not covered by tests
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@ package com.amplifyframework.auth.cognito.usecases
import aws.sdk.kotlin.services.cognitoidentityprovider.CognitoIdentityProviderClient
import aws.sdk.kotlin.services.cognitoidentityprovider.deleteWebAuthnCredential
import com.amplifyframework.auth.cognito.AuthStateMachine
import com.amplifyframework.auth.cognito.requireAuthenticationState
import com.amplifyframework.auth.cognito.requireSignedInState
import com.amplifyframework.auth.options.AuthDeleteWebAuthnCredentialOptions
import com.amplifyframework.statemachine.codegen.states.AuthenticationState.SignedIn

internal class DeleteWebAuthnCredentialUseCase(
private val client: CognitoIdentityProviderClient,
Expand All @@ -30,7 +29,7 @@ internal class DeleteWebAuthnCredentialUseCase(
@Suppress("UNUSED_PARAMETER")
suspend fun execute(credentialId: String, options: AuthDeleteWebAuthnCredentialOptions) {
// User must be signed in to call this API
stateMachine.requireAuthenticationState<SignedIn>()
stateMachine.requireSignedInState()

val accessToken = fetchAuthSession.execute().accessToken
client.deleteWebAuthnCredential {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright 2025 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.usecases

import aws.sdk.kotlin.services.cognitoidentityprovider.CognitoIdentityProviderClient
import aws.sdk.kotlin.services.cognitoidentityprovider.listDevices
import com.amplifyframework.auth.AuthDevice
import com.amplifyframework.auth.cognito.AuthStateMachine
import com.amplifyframework.auth.cognito.requireSignedInState

internal class FetchDevicesUseCase(
private val client: CognitoIdentityProviderClient,
private val fetchAuthSession: FetchAuthSessionUseCase,
private val stateMachine: AuthStateMachine
) {
suspend fun execute(): List<AuthDevice> {
stateMachine.requireSignedInState()
val token = fetchAuthSession.execute().accessToken
val response = client.listDevices { accessToken = token }
return response.devices?.map { device ->
val id = device.deviceKey ?: ""
val name = device.deviceAttributes?.find { it.name == "device_name" }?.value
AuthDevice.fromId(id, name)
} ?: emptyList()

Check warning on line 37 in aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/usecases/FetchDevicesUseCase.kt

View check run for this annotation

Codecov / codecov/patch

aws-auth-cognito/src/main/java/com/amplifyframework/auth/cognito/usecases/FetchDevicesUseCase.kt#L37

Added line #L37 was not covered by tests
}
}
Loading
Loading