mirror of
https://github.com/bitwarden/android.git
synced 2026-11-19 17:40:12 -06:00
BIT-1490: Two factor login (#775)
This commit is contained in:
committed by
Álison Fernandes
parent
bc3a76260f
commit
3de3c8f0ed
@@ -362,6 +362,44 @@ class AuthDiskSourceTest {
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getTwoFactorToken should pull from SharedPreferences`() {
|
||||
val twoFactorTokenBaseKey = "bwPreferencesStorage:twoFactorToken"
|
||||
val mockEmail = "mockUserId"
|
||||
val mockTwoFactorToken = "immaLilToken123"
|
||||
fakeSharedPreferences
|
||||
.edit {
|
||||
putString(
|
||||
"${twoFactorTokenBaseKey}_$mockEmail",
|
||||
mockTwoFactorToken,
|
||||
)
|
||||
}
|
||||
val actual = authDiskSource.getTwoFactorToken(email = mockEmail)
|
||||
assertEquals(
|
||||
mockTwoFactorToken,
|
||||
actual,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `storeTwoFactorToken should update SharedPreferences`() {
|
||||
val twoFactorTokenBaseKey = "bwPreferencesStorage:twoFactorToken"
|
||||
val mockEmail = "mockUserId"
|
||||
val mockTwoFactorToken = "immaLilToken123"
|
||||
authDiskSource.storeTwoFactorToken(
|
||||
email = mockEmail,
|
||||
twoFactorToken = mockTwoFactorToken,
|
||||
)
|
||||
val actual = fakeSharedPreferences.getString(
|
||||
"${twoFactorTokenBaseKey}_$mockEmail",
|
||||
null,
|
||||
)
|
||||
assertEquals(
|
||||
mockTwoFactorToken,
|
||||
actual,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `getUserAutoUnlockKey should pull from SharedPreferences`() {
|
||||
val userAutoUnlockKeyBaseKey = "bwSecureStorage:userKeyAutoUnlock"
|
||||
|
||||
+15
@@ -23,6 +23,7 @@ class FakeAuthDiskSource : AuthDiskSource {
|
||||
private val storedInvalidUnlockAttempts = mutableMapOf<String, Int?>()
|
||||
private val storedUserKeys = mutableMapOf<String, String?>()
|
||||
private val storedPrivateKeys = mutableMapOf<String, String?>()
|
||||
private val storedTwoFactorTokens = mutableMapOf<String, String?>()
|
||||
private val storedUserAutoUnlockKeys = mutableMapOf<String, String?>()
|
||||
private val storedPinProtectedUserKeys = mutableMapOf<String, Pair<String?, Boolean>>()
|
||||
private val storedEncryptedPins = mutableMapOf<String, String?>()
|
||||
@@ -44,6 +45,7 @@ class FakeAuthDiskSource : AuthDiskSource {
|
||||
storedInvalidUnlockAttempts.remove(userId)
|
||||
storedUserKeys.remove(userId)
|
||||
storedPrivateKeys.remove(userId)
|
||||
storedTwoFactorTokens.clear()
|
||||
storedUserAutoUnlockKeys.remove(userId)
|
||||
storedPinProtectedUserKeys.remove(userId)
|
||||
storedEncryptedPins.remove(userId)
|
||||
@@ -85,6 +87,12 @@ class FakeAuthDiskSource : AuthDiskSource {
|
||||
storedPrivateKeys[userId] = privateKey
|
||||
}
|
||||
|
||||
override fun getTwoFactorToken(email: String): String? = storedTwoFactorTokens[email]
|
||||
|
||||
override fun storeTwoFactorToken(email: String, twoFactorToken: String?) {
|
||||
storedTwoFactorTokens[email] = twoFactorToken
|
||||
}
|
||||
|
||||
override fun getUserAutoUnlockKey(userId: String): String? =
|
||||
storedUserAutoUnlockKeys[userId]
|
||||
|
||||
@@ -173,6 +181,13 @@ class FakeAuthDiskSource : AuthDiskSource {
|
||||
assertEquals(privateKey, storedPrivateKeys[userId])
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the [twoFactorToken] was stored successfully using the [email].
|
||||
*/
|
||||
fun assertTwoFactorToken(email: String, twoFactorToken: String?) {
|
||||
assertEquals(twoFactorToken, storedTwoFactorTokens[email])
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that the [userAutoUnlockKey] was stored successfully using the [userId].
|
||||
*/
|
||||
|
||||
+1
@@ -254,6 +254,7 @@ private val LOGIN_SUCCESS = GetTokenResponseJson.Success(
|
||||
privateKey = "privateKey",
|
||||
shouldForcePasswordReset = true,
|
||||
shouldResetMasterPassword = true,
|
||||
twoFactorToken = null,
|
||||
masterPasswordPolicyOptions = MasterPasswordPolicyOptionsJson(
|
||||
minimumComplexity = 10,
|
||||
minimumLength = 100,
|
||||
|
||||
@@ -21,6 +21,7 @@ import com.x8bit.bitwarden.data.auth.datasource.network.model.RefreshTokenRespon
|
||||
import com.x8bit.bitwarden.data.auth.datasource.network.model.RegisterRequestJson
|
||||
import com.x8bit.bitwarden.data.auth.datasource.network.model.RegisterResponseJson
|
||||
import com.x8bit.bitwarden.data.auth.datasource.network.model.TwoFactorAuthMethod
|
||||
import com.x8bit.bitwarden.data.auth.datasource.network.model.TwoFactorDataModel
|
||||
import com.x8bit.bitwarden.data.auth.datasource.network.service.AccountsService
|
||||
import com.x8bit.bitwarden.data.auth.datasource.network.service.AuthRequestsService
|
||||
import com.x8bit.bitwarden.data.auth.datasource.network.service.DevicesService
|
||||
@@ -736,7 +737,7 @@ class AuthRepositoryTest {
|
||||
val result = repository.login(email = EMAIL, password = PASSWORD, captchaToken = null)
|
||||
assertEquals(LoginResult.TwoFactorRequired, result)
|
||||
assertEquals(
|
||||
repository.twoFactorData,
|
||||
repository.twoFactorResponse,
|
||||
GetTokenResponseJson.TwoFactorRequired(TWO_FACTOR_AUTH_METHODS_DATA, null, null),
|
||||
)
|
||||
assertEquals(AuthState.Unauthenticated, repository.authStateFlow.value)
|
||||
@@ -754,6 +755,184 @@ class AuthRepositoryTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login two factor with remember saves two factor auth token`() = runTest {
|
||||
// Attempt a normal login with a two factor error first, so that the auth
|
||||
// data will be cached.
|
||||
coEvery { accountsService.preLogin(EMAIL) } returns Result.success(PRE_LOGIN_SUCCESS)
|
||||
coEvery {
|
||||
identityService.getToken(
|
||||
email = EMAIL,
|
||||
authModel = IdentityTokenAuthModel.MasterPassword(
|
||||
username = EMAIL,
|
||||
password = PASSWORD_HASH,
|
||||
),
|
||||
captchaToken = null,
|
||||
uniqueAppId = UNIQUE_APP_ID,
|
||||
)
|
||||
} returns Result.success(
|
||||
GetTokenResponseJson.TwoFactorRequired(
|
||||
TWO_FACTOR_AUTH_METHODS_DATA, null, null,
|
||||
),
|
||||
)
|
||||
val firstResult = repository.login(email = EMAIL, password = PASSWORD, captchaToken = null)
|
||||
assertEquals(LoginResult.TwoFactorRequired, firstResult)
|
||||
coVerify { accountsService.preLogin(email = EMAIL) }
|
||||
coVerify {
|
||||
identityService.getToken(
|
||||
email = EMAIL,
|
||||
authModel = IdentityTokenAuthModel.MasterPassword(
|
||||
username = EMAIL,
|
||||
password = PASSWORD_HASH,
|
||||
),
|
||||
captchaToken = null,
|
||||
uniqueAppId = UNIQUE_APP_ID,
|
||||
)
|
||||
}
|
||||
|
||||
// Login with two factor data.
|
||||
val successResponse = GET_TOKEN_RESPONSE_SUCCESS.copy(
|
||||
twoFactorToken = "twoFactorTokenToStore",
|
||||
)
|
||||
coEvery {
|
||||
identityService.getToken(
|
||||
email = EMAIL,
|
||||
authModel = IdentityTokenAuthModel.MasterPassword(
|
||||
username = EMAIL,
|
||||
password = PASSWORD_HASH,
|
||||
),
|
||||
captchaToken = null,
|
||||
uniqueAppId = UNIQUE_APP_ID,
|
||||
twoFactorData = TWO_FACTOR_DATA,
|
||||
)
|
||||
} returns Result.success(successResponse)
|
||||
coEvery {
|
||||
vaultRepository.unlockVault(
|
||||
userId = USER_ID_1,
|
||||
email = EMAIL,
|
||||
kdf = ACCOUNT_1.profile.toSdkParams(),
|
||||
userKey = successResponse.key,
|
||||
privateKey = successResponse.privateKey,
|
||||
organizationKeys = null,
|
||||
masterPassword = PASSWORD,
|
||||
)
|
||||
} returns VaultUnlockResult.Success
|
||||
coEvery { vaultRepository.syncIfNecessary() } just runs
|
||||
every {
|
||||
successResponse.toUserState(
|
||||
previousUserState = null,
|
||||
environmentUrlData = EnvironmentUrlDataJson.DEFAULT_US,
|
||||
)
|
||||
} returns SINGLE_USER_STATE_1
|
||||
val finalResult = repository.login(
|
||||
email = EMAIL,
|
||||
password = PASSWORD,
|
||||
twoFactorData = TWO_FACTOR_DATA,
|
||||
captchaToken = null,
|
||||
)
|
||||
assertEquals(LoginResult.Success, finalResult)
|
||||
assertNull(repository.twoFactorResponse)
|
||||
fakeAuthDiskSource.assertTwoFactorToken(
|
||||
email = EMAIL,
|
||||
twoFactorToken = "twoFactorTokenToStore",
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login uses remembered two factor tokens`() = runTest {
|
||||
fakeAuthDiskSource.storeTwoFactorToken(EMAIL, "storedTwoFactorToken")
|
||||
val rememberedTwoFactorData = TwoFactorDataModel(
|
||||
code = "storedTwoFactorToken",
|
||||
method = TwoFactorAuthMethod.REMEMBER.value.toString(),
|
||||
remember = false,
|
||||
)
|
||||
val successResponse = GET_TOKEN_RESPONSE_SUCCESS
|
||||
coEvery {
|
||||
accountsService.preLogin(email = EMAIL)
|
||||
} returns Result.success(PRE_LOGIN_SUCCESS)
|
||||
coEvery {
|
||||
identityService.getToken(
|
||||
email = EMAIL,
|
||||
authModel = IdentityTokenAuthModel.MasterPassword(
|
||||
username = EMAIL,
|
||||
password = PASSWORD_HASH,
|
||||
),
|
||||
captchaToken = null,
|
||||
uniqueAppId = UNIQUE_APP_ID,
|
||||
twoFactorData = rememberedTwoFactorData,
|
||||
)
|
||||
} returns Result.success(successResponse)
|
||||
coEvery {
|
||||
vaultRepository.unlockVault(
|
||||
userId = USER_ID_1,
|
||||
email = EMAIL,
|
||||
kdf = ACCOUNT_1.profile.toSdkParams(),
|
||||
userKey = successResponse.key,
|
||||
privateKey = successResponse.privateKey,
|
||||
organizationKeys = null,
|
||||
masterPassword = PASSWORD,
|
||||
)
|
||||
} returns VaultUnlockResult.Success
|
||||
coEvery { vaultRepository.syncIfNecessary() } just runs
|
||||
every {
|
||||
GET_TOKEN_RESPONSE_SUCCESS.toUserState(
|
||||
previousUserState = null,
|
||||
environmentUrlData = EnvironmentUrlDataJson.DEFAULT_US,
|
||||
)
|
||||
} returns SINGLE_USER_STATE_1
|
||||
val result = repository.login(email = EMAIL, password = PASSWORD, captchaToken = null)
|
||||
assertEquals(LoginResult.Success, result)
|
||||
assertEquals(AuthState.Authenticated(ACCESS_TOKEN), repository.authStateFlow.value)
|
||||
coVerify { accountsService.preLogin(email = EMAIL) }
|
||||
fakeAuthDiskSource.assertPrivateKey(
|
||||
userId = USER_ID_1,
|
||||
privateKey = "privateKey",
|
||||
)
|
||||
fakeAuthDiskSource.assertUserKey(
|
||||
userId = USER_ID_1,
|
||||
userKey = "key",
|
||||
)
|
||||
coVerify {
|
||||
identityService.getToken(
|
||||
email = EMAIL,
|
||||
authModel = IdentityTokenAuthModel.MasterPassword(
|
||||
username = EMAIL,
|
||||
password = PASSWORD_HASH,
|
||||
),
|
||||
captchaToken = null,
|
||||
uniqueAppId = UNIQUE_APP_ID,
|
||||
twoFactorData = rememberedTwoFactorData,
|
||||
)
|
||||
vaultRepository.unlockVault(
|
||||
userId = USER_ID_1,
|
||||
email = EMAIL,
|
||||
kdf = ACCOUNT_1.profile.toSdkParams(),
|
||||
userKey = successResponse.key,
|
||||
privateKey = successResponse.privateKey,
|
||||
organizationKeys = null,
|
||||
masterPassword = PASSWORD,
|
||||
)
|
||||
vaultRepository.syncIfNecessary()
|
||||
}
|
||||
assertEquals(
|
||||
SINGLE_USER_STATE_1,
|
||||
fakeAuthDiskSource.userState,
|
||||
)
|
||||
verify { settingsRepository.setDefaultsIfNecessary(userId = USER_ID_1) }
|
||||
verify { vaultRepository.clearUnlockedData() }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `login two factor returns error if no cached auth data`() = runTest {
|
||||
val result = repository.login(
|
||||
email = EMAIL,
|
||||
password = PASSWORD,
|
||||
twoFactorData = TWO_FACTOR_DATA,
|
||||
captchaToken = null,
|
||||
)
|
||||
assertEquals(LoginResult.Error(errorMessage = null), result)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `register check data breaches error should still return register success`() = runTest {
|
||||
coEvery {
|
||||
@@ -1557,6 +1736,14 @@ class AuthRepositoryTest {
|
||||
private const val REFRESH_TOKEN = "refreshToken"
|
||||
private const val REFRESH_TOKEN_2 = "refreshToken2"
|
||||
private const val CAPTCHA_KEY = "captcha"
|
||||
private const val TWO_FACTOR_CODE = "123456"
|
||||
private val TWO_FACTOR_METHOD = TwoFactorAuthMethod.EMAIL
|
||||
private const val TWO_FACTOR_REMEMBER = true
|
||||
private val TWO_FACTOR_DATA = TwoFactorDataModel(
|
||||
code = TWO_FACTOR_CODE,
|
||||
method = TWO_FACTOR_METHOD.value.toString(),
|
||||
remember = TWO_FACTOR_REMEMBER,
|
||||
)
|
||||
|
||||
private const val DEFAULT_KDF_ITERATIONS = 600000
|
||||
private const val ENCRYPTED_USER_KEY = "encryptedUserKey"
|
||||
@@ -1591,6 +1778,7 @@ class AuthRepositoryTest {
|
||||
privateKey = "privateKey",
|
||||
shouldForcePasswordReset = true,
|
||||
shouldResetMasterPassword = true,
|
||||
twoFactorToken = null,
|
||||
masterPasswordPolicyOptions = null,
|
||||
userDecryptionOptions = null,
|
||||
)
|
||||
|
||||
+1
@@ -81,6 +81,7 @@ private val GET_TOKEN_RESPONSE_SUCCESS = GetTokenResponseJson.Success(
|
||||
privateKey = "privateKey",
|
||||
shouldForcePasswordReset = true,
|
||||
shouldResetMasterPassword = true,
|
||||
twoFactorToken = null,
|
||||
masterPasswordPolicyOptions = null,
|
||||
userDecryptionOptions = null,
|
||||
)
|
||||
|
||||
@@ -64,7 +64,7 @@ class LoginScreenTest : BaseComposeTest() {
|
||||
onNavigateToMasterPasswordHint = { onNavigateToMasterPasswordHintCalled = true },
|
||||
onNavigateToEnterpriseSignOn = { onNavigateToEnterpriseSignOnCalled = true },
|
||||
onNavigateToLoginWithDevice = { onNavigateToLoginWithDeviceCalled = true },
|
||||
onNavigateToTwoFactorLogin = { onNavigateToTwoFactorLoginCalled = true },
|
||||
onNavigateToTwoFactorLogin = { _, _ -> onNavigateToTwoFactorLoginCalled = true },
|
||||
viewModel = viewModel,
|
||||
intentManager = intentManager,
|
||||
)
|
||||
|
||||
+57
-10
@@ -1,5 +1,6 @@
|
||||
package com.x8bit.bitwarden.ui.auth.feature.twofactorlogin
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.compose.ui.test.assertIsDisplayed
|
||||
import androidx.compose.ui.test.assertIsEnabled
|
||||
import androidx.compose.ui.test.assertIsNotDisplayed
|
||||
@@ -14,6 +15,7 @@ import androidx.compose.ui.test.performTextInput
|
||||
import com.x8bit.bitwarden.data.auth.datasource.network.model.TwoFactorAuthMethod
|
||||
import com.x8bit.bitwarden.data.platform.repository.util.bufferedMutableSharedFlow
|
||||
import com.x8bit.bitwarden.ui.platform.base.BaseComposeTest
|
||||
import com.x8bit.bitwarden.ui.platform.base.util.asText
|
||||
import com.x8bit.bitwarden.ui.platform.manager.intent.IntentManager
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
@@ -47,6 +49,22 @@ class TwoFactorLoginScreenTest : BaseComposeTest() {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `basicDialog should update according to state`() {
|
||||
composeTestRule.onNodeWithText("Error message").assertDoesNotExist()
|
||||
|
||||
mutableStateFlow.update {
|
||||
it.copy(
|
||||
dialogState = TwoFactorLoginState.DialogState.Error(
|
||||
title = null,
|
||||
message = "Error message".asText(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
composeTestRule.onNodeWithText("Error message").isDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `close button click should send CloseButtonClick action`() {
|
||||
composeTestRule.onNodeWithContentDescription("Close").performClick()
|
||||
@@ -102,6 +120,19 @@ class TwoFactorLoginScreenTest : BaseComposeTest() {
|
||||
composeTestRule.onNodeWithText(authAppDetails).isDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `loadingOverlay should update according to state`() {
|
||||
composeTestRule.onNodeWithText("Loading...").assertDoesNotExist()
|
||||
|
||||
mutableStateFlow.update {
|
||||
it.copy(
|
||||
dialogState = TwoFactorLoginState.DialogState.Loading("Loading...".asText()),
|
||||
)
|
||||
}
|
||||
|
||||
composeTestRule.onNodeWithText("Loading...").isDisplayed()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `remember me click should send RememberMeToggle action`() {
|
||||
composeTestRule.onNodeWithText("Remember me").performClick()
|
||||
@@ -131,7 +162,7 @@ class TwoFactorLoginScreenTest : BaseComposeTest() {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `resend email button visibility should should update according to state`() {
|
||||
fun `resend email button visibility should update according to state`() {
|
||||
val buttonText = "Send verification code email again"
|
||||
composeTestRule.onNodeWithText(buttonText).assertIsDisplayed()
|
||||
|
||||
@@ -178,6 +209,13 @@ class TwoFactorLoginScreenTest : BaseComposeTest() {
|
||||
TestCase.assertTrue(onNavigateBackCalled)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `NavigateToCaptcha should call intentManager startCustomTabsActivity`() {
|
||||
val mockUri = mockk<Uri>()
|
||||
mutableEventFlow.tryEmit(TwoFactorLoginEvent.NavigateToCaptcha(mockUri))
|
||||
verify { intentManager.startCustomTabsActivity(mockUri) }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `NavigateToRecoveryCode should launch the recovery code uri`() {
|
||||
mutableEventFlow.tryEmit(TwoFactorLoginEvent.NavigateToRecoveryCode)
|
||||
@@ -185,13 +223,22 @@ class TwoFactorLoginScreenTest : BaseComposeTest() {
|
||||
intentManager.launchUri(any())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val DEFAULT_STATE = TwoFactorLoginState(
|
||||
authMethod = TwoFactorAuthMethod.EMAIL,
|
||||
availableAuthMethods = listOf(TwoFactorAuthMethod.EMAIL, TwoFactorAuthMethod.RECOVERY_CODE),
|
||||
codeInput = "",
|
||||
displayEmail = "ex***@email.com",
|
||||
isContinueButtonEnabled = false,
|
||||
isRememberMeEnabled = false,
|
||||
)
|
||||
companion object {
|
||||
private val DEFAULT_STATE = TwoFactorLoginState(
|
||||
authMethod = TwoFactorAuthMethod.EMAIL,
|
||||
availableAuthMethods = listOf(
|
||||
TwoFactorAuthMethod.EMAIL,
|
||||
TwoFactorAuthMethod.RECOVERY_CODE,
|
||||
),
|
||||
codeInput = "",
|
||||
displayEmail = "ex***@email.com",
|
||||
dialogState = null,
|
||||
isContinueButtonEnabled = false,
|
||||
isRememberMeEnabled = false,
|
||||
captchaToken = null,
|
||||
email = "example@email.com",
|
||||
password = "password123",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+216
-4
@@ -1,24 +1,52 @@
|
||||
package com.x8bit.bitwarden.ui.auth.feature.twofactorlogin
|
||||
|
||||
import android.net.Uri
|
||||
import androidx.lifecycle.SavedStateHandle
|
||||
import app.cash.turbine.test
|
||||
import com.x8bit.bitwarden.R
|
||||
import com.x8bit.bitwarden.data.auth.datasource.network.model.GetTokenResponseJson
|
||||
import com.x8bit.bitwarden.data.auth.datasource.network.model.TwoFactorAuthMethod
|
||||
import com.x8bit.bitwarden.data.auth.datasource.network.model.TwoFactorDataModel
|
||||
import com.x8bit.bitwarden.data.auth.repository.AuthRepository
|
||||
import com.x8bit.bitwarden.data.auth.repository.model.LoginResult
|
||||
import com.x8bit.bitwarden.data.auth.repository.util.CaptchaCallbackTokenResult
|
||||
import com.x8bit.bitwarden.data.auth.repository.util.generateUriForCaptcha
|
||||
import com.x8bit.bitwarden.data.platform.repository.util.bufferedMutableSharedFlow
|
||||
import com.x8bit.bitwarden.ui.platform.base.BaseViewModelTest
|
||||
import com.x8bit.bitwarden.ui.platform.base.util.asText
|
||||
import io.mockk.coEvery
|
||||
import io.mockk.coVerify
|
||||
import io.mockk.every
|
||||
import io.mockk.mockk
|
||||
import io.mockk.mockkStatic
|
||||
import io.mockk.unmockkStatic
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import org.junit.jupiter.api.AfterEach
|
||||
import org.junit.jupiter.api.Assertions.assertEquals
|
||||
import org.junit.jupiter.api.BeforeEach
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
class TwoFactorLoginViewModelTest : BaseViewModelTest() {
|
||||
|
||||
private val mutableCaptchaTokenResultFlow =
|
||||
bufferedMutableSharedFlow<CaptchaCallbackTokenResult>()
|
||||
private val authRepository: AuthRepository = mockk(relaxed = true) {
|
||||
every { twoFactorData } returns TWO_FACTOR_DATA
|
||||
every { twoFactorResponse } returns TWO_FACTOR_RESPONSE
|
||||
every { captchaTokenResultFlow } returns mutableCaptchaTokenResultFlow
|
||||
}
|
||||
|
||||
private val savedStateHandle = SavedStateHandle().also {
|
||||
it["email_address"] = "test@gmail.com"
|
||||
it["email_address"] = "example@email.com"
|
||||
it["password"] = "password123"
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
fun setUp() {
|
||||
mockkStatic(::generateUriForCaptcha)
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
fun tearDown() {
|
||||
unmockkStatic(::generateUriForCaptcha)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -29,6 +57,36 @@ class TwoFactorLoginViewModelTest : BaseViewModelTest() {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `captchaTokenFlow success update should trigger a login`() = runTest {
|
||||
coEvery {
|
||||
authRepository.login(
|
||||
email = "example@email.com",
|
||||
password = "password123",
|
||||
twoFactorData = TwoFactorDataModel(
|
||||
code = "",
|
||||
method = TwoFactorAuthMethod.AUTHENTICATOR_APP.value.toString(),
|
||||
remember = false,
|
||||
),
|
||||
captchaToken = "token",
|
||||
)
|
||||
} returns LoginResult.Success
|
||||
createViewModel()
|
||||
mutableCaptchaTokenResultFlow.tryEmit(CaptchaCallbackTokenResult.Success("token"))
|
||||
coVerify {
|
||||
authRepository.login(
|
||||
email = "example@email.com",
|
||||
password = "password123",
|
||||
twoFactorData = TwoFactorDataModel(
|
||||
code = "",
|
||||
method = TwoFactorAuthMethod.AUTHENTICATOR_APP.value.toString(),
|
||||
remember = false,
|
||||
),
|
||||
captchaToken = "token",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `CloseButtonClick should emit NavigateBack`() = runTest {
|
||||
val viewModel = createViewModel()
|
||||
@@ -86,6 +144,156 @@ class TwoFactorLoginViewModelTest : BaseViewModelTest() {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ContinueButtonClick login returns success should update loadingDialogState`() = runTest {
|
||||
coEvery {
|
||||
authRepository.login(
|
||||
email = "example@email.com",
|
||||
password = "password123",
|
||||
twoFactorData = TwoFactorDataModel(
|
||||
code = "",
|
||||
method = TwoFactorAuthMethod.AUTHENTICATOR_APP.value.toString(),
|
||||
remember = false,
|
||||
),
|
||||
captchaToken = null,
|
||||
)
|
||||
} returns LoginResult.Success
|
||||
|
||||
val viewModel = createViewModel()
|
||||
viewModel.stateFlow.test {
|
||||
assertEquals(DEFAULT_STATE, awaitItem())
|
||||
|
||||
viewModel.trySendAction(TwoFactorLoginAction.ContinueButtonClick)
|
||||
assertEquals(
|
||||
DEFAULT_STATE.copy(
|
||||
dialogState = TwoFactorLoginState.DialogState.Loading(
|
||||
message = R.string.logging_in.asText(),
|
||||
),
|
||||
),
|
||||
awaitItem(),
|
||||
)
|
||||
assertEquals(
|
||||
DEFAULT_STATE,
|
||||
awaitItem(),
|
||||
)
|
||||
}
|
||||
coVerify {
|
||||
authRepository.login(
|
||||
email = "example@email.com",
|
||||
password = "password123",
|
||||
twoFactorData = TwoFactorDataModel(
|
||||
code = "",
|
||||
method = TwoFactorAuthMethod.AUTHENTICATOR_APP.value.toString(),
|
||||
remember = false,
|
||||
),
|
||||
captchaToken = null,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ContinueButtonClick login returns CaptchaRequired should emit NavigateToCaptcha`() =
|
||||
runTest {
|
||||
val mockkUri = mockk<Uri>()
|
||||
every {
|
||||
generateUriForCaptcha(captchaId = "mock_captcha_id")
|
||||
} returns mockkUri
|
||||
coEvery {
|
||||
authRepository.login(
|
||||
email = "example@email.com",
|
||||
password = "password123",
|
||||
twoFactorData = TwoFactorDataModel(
|
||||
code = "",
|
||||
method = TwoFactorAuthMethod.AUTHENTICATOR_APP.value.toString(),
|
||||
remember = false,
|
||||
),
|
||||
captchaToken = null,
|
||||
)
|
||||
} returns LoginResult.CaptchaRequired(captchaId = "mock_captcha_id")
|
||||
val viewModel = createViewModel()
|
||||
viewModel.eventFlow.test {
|
||||
viewModel.actionChannel.trySend(TwoFactorLoginAction.ContinueButtonClick)
|
||||
|
||||
assertEquals(
|
||||
DEFAULT_STATE,
|
||||
viewModel.stateFlow.value,
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
TwoFactorLoginEvent.NavigateToCaptcha(uri = mockkUri),
|
||||
awaitItem(),
|
||||
)
|
||||
}
|
||||
coVerify {
|
||||
authRepository.login(
|
||||
email = "example@email.com",
|
||||
password = "password123",
|
||||
twoFactorData = TwoFactorDataModel(
|
||||
code = "",
|
||||
method = TwoFactorAuthMethod.AUTHENTICATOR_APP.value.toString(),
|
||||
remember = false,
|
||||
),
|
||||
captchaToken = null,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `ContinueButtonClick login returns Error should update errorStateDialog`() = runTest {
|
||||
coEvery {
|
||||
authRepository.login(
|
||||
email = "example@email.com",
|
||||
password = "password123",
|
||||
twoFactorData = TwoFactorDataModel(
|
||||
code = "",
|
||||
method = TwoFactorAuthMethod.AUTHENTICATOR_APP.value.toString(),
|
||||
remember = false,
|
||||
),
|
||||
captchaToken = null,
|
||||
)
|
||||
} returns LoginResult.Error(errorMessage = null)
|
||||
|
||||
val viewModel = createViewModel()
|
||||
viewModel.stateFlow.test {
|
||||
assertEquals(DEFAULT_STATE, awaitItem())
|
||||
|
||||
viewModel.trySendAction(TwoFactorLoginAction.ContinueButtonClick)
|
||||
assertEquals(
|
||||
DEFAULT_STATE.copy(
|
||||
dialogState = TwoFactorLoginState.DialogState.Loading(
|
||||
message = R.string.logging_in.asText(),
|
||||
),
|
||||
),
|
||||
awaitItem(),
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
DEFAULT_STATE.copy(
|
||||
dialogState = TwoFactorLoginState.DialogState.Error(
|
||||
title = R.string.an_error_has_occurred.asText(),
|
||||
message = R.string.invalid_verification_code.asText(),
|
||||
),
|
||||
),
|
||||
awaitItem(),
|
||||
)
|
||||
|
||||
viewModel.trySendAction(TwoFactorLoginAction.DialogDismiss)
|
||||
assertEquals(DEFAULT_STATE, awaitItem())
|
||||
}
|
||||
coVerify {
|
||||
authRepository.login(
|
||||
email = "example@email.com",
|
||||
password = "password123",
|
||||
twoFactorData = TwoFactorDataModel(
|
||||
code = "",
|
||||
method = TwoFactorAuthMethod.AUTHENTICATOR_APP.value.toString(),
|
||||
remember = false,
|
||||
),
|
||||
captchaToken = null,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `RememberMeToggle should update the state`() = runTest {
|
||||
val viewModel = createViewModel()
|
||||
@@ -158,7 +366,7 @@ class TwoFactorLoginViewModelTest : BaseViewModelTest() {
|
||||
TwoFactorAuthMethod.EMAIL to mapOf("Email" to "ex***@email.com"),
|
||||
TwoFactorAuthMethod.AUTHENTICATOR_APP to mapOf("Email" to null),
|
||||
)
|
||||
private val TWO_FACTOR_DATA =
|
||||
private val TWO_FACTOR_RESPONSE =
|
||||
GetTokenResponseJson.TwoFactorRequired(
|
||||
TWO_FACTOR_AUTH_METHODS_DATA,
|
||||
null,
|
||||
@@ -174,8 +382,12 @@ class TwoFactorLoginViewModelTest : BaseViewModelTest() {
|
||||
),
|
||||
codeInput = "",
|
||||
displayEmail = "ex***@email.com",
|
||||
dialogState = null,
|
||||
isContinueButtonEnabled = false,
|
||||
isRememberMeEnabled = false,
|
||||
captchaToken = null,
|
||||
email = "example@email.com",
|
||||
password = "password123",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user