Skip to content

Commit

Permalink
Modified a logic of resolving base settings.| #716
Browse files Browse the repository at this point in the history
  • Loading branch information
DenBond7 committed Aug 27, 2020
1 parent 6085fdf commit 16dbd57
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 59 deletions.
18 changes: 18 additions & 0 deletions .idea/codeStyles/Project.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package com.flowcrypt.email.api.email

import com.flowcrypt.email.api.email.model.AuthCredentials
import com.flowcrypt.email.api.email.model.SecurityType
import com.flowcrypt.email.api.oauth.OAuth2Helper
import com.flowcrypt.email.util.GeneralUtil

/**
Expand All @@ -21,7 +22,7 @@ object EmailProviderSettingsHelper {
/*********************** Microsoft **********************/
private const val PROVIDER_OUTLOOK = "outlook.com"
private const val PROVIDER_HOTMAIL = "hotmail.com"
private const val PROVIDER_LIVE = "Live.com"
private const val PROVIDER_LIVE = "live.com"
private const val IMAP_SERVER_MICROSOFT = "outlook.office365.com"
private const val SMTP_SERVER_MICROSOFT = "smtp.office365.com"
private const val FAQ_URL_MICROSOFT = "https://support.microsoft.com/en-us/office/pop-imap-and-smtp-settings-for-outlook-com-d088b986-291d-42b8-9564-9c414e2aa040"
Expand Down Expand Up @@ -79,6 +80,12 @@ object EmailProviderSettingsHelper {
}
}

fun getBaseSettingsForProvider(email: String, provider: OAuth2Helper.Provider): AuthCredentials? {
return when (provider) {
OAuth2Helper.Provider.MICROSOFT -> getOutlookSettings(email, "")
}
}

private fun getOutlookSettings(email: String, password: String): AuthCredentials {
return AuthCredentials(
email = email,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ data class Result<out T>(val status: Status,
}

companion object {
fun <T> clearResult(): Result<T> {
return Result(status = Status.SUCCESS, data = null, exception = null, requestCode = 0)
}

fun <T> success(data: T, requestCode: Long = 0): Result<T> {
return Result(status = Status.SUCCESS, data = data, exception = null, requestCode = requestCode)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,17 +122,17 @@ class OAuth2AuthCredentialsViewModel(application: Application) : BaseAndroidView

val accessToken = response.data?.accessToken
?: throw NullPointerException("API error: accessToken is null!")
val recommendAuthCredentials = EmailProviderSettingsHelper.getBaseSettings(email, "")?.copy(
val recommendAuthCredentials = EmailProviderSettingsHelper.getBaseSettingsForProvider(email, OAuth2Helper.Provider.MICROSOFT)?.copy(
password = "",
smtpSignInPassword = null,
useOAuth2 = true,
displayName = displayName,
authTokenInfo = AuthTokenInfo(
email = email,
accessToken = accessToken,
expiresAt = OAuth2Helper.getExpiresAtTime(response.data.expiresIn),
refreshToken = KeyStoreCryptoManager.encryptSuspend(response.data.refreshToken)
)
)?.copy(password = "", smtpSignInPassword = null)
?: throw NullPointerException("Couldn't find default settings for $email!")
)) ?: throw NullPointerException("Couldn't find default settings for $email!")

microsoftOAuth2TokenLiveData.postValue(Result.success(recommendAuthCredentials))
} catch (e: Exception) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ class AddOtherAccountFragment : BaseSingInFragment(), ProgressBehaviour,
initViews(view)
updateView(authCreds)

setupOAuth2AuthCredentialsViewModel()
setupPrivateKeysViewModel()
}

Expand Down Expand Up @@ -414,7 +415,7 @@ class AddOtherAccountFragment : BaseSingInFragment(), ProgressBehaviour,
buttonSignInWithOutlook = view.findViewById(R.id.buttonSignInWithOutlook)
buttonSignInWithOutlook?.setOnClickListener {
it.isEnabled = false
getAuthorizationRequestForProvider(
oAuth2AuthCredentialsViewModel.getAuthorizationRequestForProvider(
requestCode = REQUEST_CODE_FETCH_MICROSOFT_OPENID_CONFIGURATION,
provider = OAuth2Helper.Provider.MICROSOFT)
}
Expand Down Expand Up @@ -568,48 +569,7 @@ class AddOtherAccountFragment : BaseSingInFragment(), ProgressBehaviour,
}
}

private fun setupPrivateKeysViewModel() {
privateKeysViewModel.savePrivateKeysLiveData.observe(viewLifecycleOwner, Observer {
it?.let {
when (it.status) {
Result.Status.LOADING -> {
showProgress(progressMsg = getString(R.string.saving_prv_keys))
}

Result.Status.SUCCESS -> {
if (existedAccounts.isEmpty()) runEmailManagerActivity() else returnResultOk()
}

Result.Status.ERROR, Result.Status.EXCEPTION -> {
showContent()
val e = it.exception
if (e is SavePrivateKeyToDatabaseException) {
showSnackbar(rootView, e.message ?: e.javaClass.simpleName,
getString(R.string.retry), Snackbar.LENGTH_INDEFINITE, View.OnClickListener {
privateKeysViewModel.encryptAndSaveKeysToDatabase(e.keys, KeyDetails.Type.EMAIL)
})
} else {
showInfoSnackbar(rootView, e?.message ?: e?.javaClass?.simpleName
?: getString(R.string.unknown_error))
}
}
}
}
})
}

private fun getOAuthToken(schema: String?, code: String) {
authRequest?.let { request ->
when (schema) {
OAuth2Helper.MICROSOFT_OAUTH2_SCHEMA -> {
observeMicrosoftOAuth2TokenLiveData()
oAuth2AuthCredentialsViewModel.getMicrosoftOAuth2Token(authorizeCode = code, authRequest = request)
}
}
}
}

private fun observeMicrosoftOAuth2TokenLiveData() {
private fun setupOAuth2AuthCredentialsViewModel() {
oAuth2AuthCredentialsViewModel.microsoftOAuth2TokenLiveData.observe(viewLifecycleOwner, Observer {
when (it.status) {
Result.Status.LOADING -> {
Expand All @@ -619,13 +579,13 @@ class AddOtherAccountFragment : BaseSingInFragment(), ProgressBehaviour,
Result.Status.SUCCESS -> {
it.data?.let { authCredentials ->
authCreds = authCredentials
oAuth2AuthCredentialsViewModel.microsoftOAuth2TokenLiveData.value = Result.clearResult()

val existedAccount = existedAccounts.firstOrNull { account ->
account.email.equals(authCredentials.email, ignoreCase = true)
}

if (existedAccount == null) {
oAuth2AuthCredentialsViewModel.microsoftOAuth2TokenLiveData.removeObservers(viewLifecycleOwner)
val account = AccountEntity(authCredentials).copy(
password = authCredentials.peekPassword(),
smtpPassword = authCredentials.peekSmtpPassword()
Expand All @@ -639,37 +599,34 @@ class AddOtherAccountFragment : BaseSingInFragment(), ProgressBehaviour,

return@let
} else {
oAuth2AuthCredentialsViewModel.microsoftOAuth2TokenLiveData.value = Result.success(null)
showContent()
showInfoSnackbar(msgText = getString(R.string.template_email_alredy_added, existedAccount.email), duration = Snackbar.LENGTH_LONG)
}
}
}

Result.Status.ERROR, Result.Status.EXCEPTION -> {
oAuth2AuthCredentialsViewModel.microsoftOAuth2TokenLiveData.removeObservers(viewLifecycleOwner)
oAuth2AuthCredentialsViewModel.microsoftOAuth2TokenLiveData.value = Result.clearResult()
showContent()
showInfoDialog(
dialogMsg = it.exception?.message ?: it.exception?.javaClass?.simpleName
?: "Couldn't fetch token")
}
}
})
}

private fun getAuthorizationRequestForProvider(requestCode: Long, provider: OAuth2Helper.Provider) {
oAuth2AuthCredentialsViewModel.authorizationRequestLiveData.observe(viewLifecycleOwner, Observer {
when (it.status) {
Result.Status.LOADING -> {
showProgress(progressMsg = getString(R.string.loading_oauth_server_configuration))
}

Result.Status.SUCCESS -> {
oAuth2AuthCredentialsViewModel.authorizationRequestLiveData.removeObservers(viewLifecycleOwner)
buttonSignInWithOutlook?.isEnabled = true
showContent()

it.data?.let { authorizationRequest ->
oAuth2AuthCredentialsViewModel.authorizationRequestLiveData.value = Result.clearResult()
buttonSignInWithOutlook?.isEnabled = true
showContent()

authRequest = authorizationRequest
authRequest?.let { request ->
AuthorizationService(requireContext())
Expand All @@ -681,7 +638,7 @@ class AddOtherAccountFragment : BaseSingInFragment(), ProgressBehaviour,
}

Result.Status.ERROR, Result.Status.EXCEPTION -> {
oAuth2AuthCredentialsViewModel.authorizationRequestLiveData.removeObservers(viewLifecycleOwner)
oAuth2AuthCredentialsViewModel.authorizationRequestLiveData.value = Result.clearResult()
buttonSignInWithOutlook?.isEnabled = true
showContent()
showInfoDialog(
Expand All @@ -690,8 +647,49 @@ class AddOtherAccountFragment : BaseSingInFragment(), ProgressBehaviour,
}
}
})
}

private fun setupPrivateKeysViewModel() {
privateKeysViewModel.savePrivateKeysLiveData.observe(viewLifecycleOwner, Observer {
it?.let {
when (it.status) {
Result.Status.LOADING -> {
showProgress(progressMsg = getString(R.string.saving_prv_keys))
}

Result.Status.SUCCESS -> {
if (existedAccounts.isEmpty()) runEmailManagerActivity() else returnResultOk()
}

Result.Status.ERROR, Result.Status.EXCEPTION -> {
showContent()
val e = it.exception
if (e is SavePrivateKeyToDatabaseException) {
showSnackbar(rootView, e.message ?: e.javaClass.simpleName,
getString(R.string.retry), Snackbar.LENGTH_INDEFINITE, View.OnClickListener {
privateKeysViewModel.encryptAndSaveKeysToDatabase(e.keys, KeyDetails.Type.EMAIL)
})
} else {
showInfoSnackbar(rootView, e?.message ?: e?.javaClass?.simpleName
?: getString(R.string.unknown_error))
}
}
}
}
})
}

oAuth2AuthCredentialsViewModel.getAuthorizationRequestForProvider(requestCode, provider)
private fun getOAuthToken(schema: String?, code: String) {
authRequest?.let { request ->
when (schema) {
OAuth2Helper.MICROSOFT_OAUTH2_SCHEMA -> {
oAuth2AuthCredentialsViewModel.getMicrosoftOAuth2Token(
authorizeCode = code,
authRequest = request
)
}
}
}
}

/**
Expand Down

0 comments on commit 16dbd57

Please sign in to comment.