Skip to content

Commit

Permalink
update encrypteddatastore
Browse files Browse the repository at this point in the history
  • Loading branch information
reskimulud committed Nov 1, 2022
1 parent e9e78f5 commit 3397b23
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ class PreferencesDataStore(

// Encrypted DataStore (DataStore yang dienkripsi)
fun getUserName(): Flow<String> =
encryptedDataStore.data.secureMap(aes) {
it[USER_NAME_KEY] ?: ""
encryptedDataStore.data.secureMap(aes, DEFAULT_VALUE) {
it[USER_NAME_KEY] ?: DEFAULT_VALUE
}

suspend fun setUserName(name: String) =
Expand All @@ -37,8 +37,8 @@ class PreferencesDataStore(
}

fun getUserEmail(): Flow<String> =
encryptedDataStore.data.secureMap(aes) {
it[USER_EMAIL_KEY] ?: ""
encryptedDataStore.data.secureMap(aes, DEFAULT_VALUE) {
it[USER_EMAIL_KEY] ?: DEFAULT_VALUE
}

suspend fun setUserEmail(email: String) =
Expand All @@ -47,8 +47,8 @@ class PreferencesDataStore(
}

fun getUserApiKey(): Flow<String> =
encryptedDataStore.data.secureMap(aes) {
it[USER_API_KEY] ?: ""
encryptedDataStore.data.secureMap(aes, DEFAULT_VALUE) {
it[USER_API_KEY] ?: DEFAULT_VALUE
}

suspend fun setUserApiKey(apiKey: String) =
Expand Down Expand Up @@ -77,6 +77,8 @@ class PreferencesDataStore(
private val USER_EMAIL_KEY = stringPreferencesKey("user_email")
private val USER_API_KEY = stringPreferencesKey("user_api_key")

private const val DEFAULT_VALUE = "empty"

@Volatile
private var INSTANCE: PreferencesDataStore? = null

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,21 @@ object EncryptedDataStore {

inline fun <reified T> Flow<Preferences>.secureMap(
aes: AES,
defaultValue: T,
crossinline fetchValue: (value: Preferences) -> String,
): Flow<T> =
map { preference ->
val value = fetchValue(preference)

if (value.isNotEmpty() && value != "") {
if (value.isNotEmpty() && value != defaultValue) {
val byteArrayFromHexString =
value.chunked(2).map { it.toInt(16).toByte() }.toByteArray()

val decryptedValue = aes.decrypt(byteArrayFromHexString)
val jsonEncode = Json { encodeDefaults = true }
jsonEncode.decodeFromString(decryptedValue.decodeToString())
} else {
value as T
defaultValue
}
}
}

0 comments on commit 3397b23

Please sign in to comment.