Skip to content
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
1 change: 1 addition & 0 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ dependencies {
implementation(project(":core:navigation-api"))
implementation(project(":core:ui"))
implementation(project(":core:navigation-impl"))
implementation(project(":core:datastore-impl"))

//Timber
implementation(libs.timber)
Expand Down
2 changes: 2 additions & 0 deletions app/src/main/java/ru/yeahub/Application.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package ru.yeahub
import android.app.Application
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
import ru.yeahub.datastore_impl.di.datastoreModule
import ru.yeahub.detail_question.impl.di.detailQuestionFeatureModule
import ru.yeahub.example_details.impl.detailsFeatureModule
import ru.yeahub.example_home.impl.data.di.questionsMainFeatureModule
Expand Down Expand Up @@ -45,6 +46,7 @@ class Application : Application() {
modules(
networkModule,
navigationPathModule,
datastoreModule,
questionsModule,
profileFeatureModule,
questionsMainFeatureModule,
Expand Down
43 changes: 43 additions & 0 deletions core/datastore-api/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.android)
}

android {
namespace = "ru.yeahub.datastore_api"
compileSdk = 35

defaultConfig {
minSdk = 24

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles("consumer-rules.pro")
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "11"
}
}

dependencies {

implementation(libs.androidx.core.ktx)
implementation(libs.androidx.appcompat)
implementation(libs.material)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
}
Empty file.
21 changes: 21 additions & 0 deletions core/datastore-api/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
4 changes: 4 additions & 0 deletions core/datastore-api/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package ru.yeahub.datastore_api

/**
* Контракт локального хранения токена авторизации:
* - saveAccessToken - сохраняет access token
* - getAccessToken - возвращает сохранённый access token
* - clearTokens - очищает токены авторизации
*/
interface TokenDataStore {

suspend fun saveAccessToken(accessToken: String): TokenStorageResult

suspend fun getAccessToken(): String?

suspend fun clearTokens(): TokenStorageResult
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package ru.yeahub.datastore_api

/**
* Результат операции локального хранения токена:
* - Success - операция выполнена успешно
* - Error - операция завершилась ошибкой
*/
sealed interface TokenStorageResult {

data object Success : TokenStorageResult

data object Error : TokenStorageResult
}
47 changes: 47 additions & 0 deletions core/datastore-impl/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.android)
}

android {
namespace = "ru.yeahub.datastore_impl"
compileSdk = 35

defaultConfig {
minSdk = 24

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles("consumer-rules.pro")
}

buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "11"
}
}

dependencies {
implementation(project(":core:datastore-api"))

implementation(libs.androidx.core.ktx)
implementation(libs.androidx.datastore.preferences)

implementation(libs.koin.core)
implementation(libs.koin.android)

testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
}
Empty file.
21 changes: 21 additions & 0 deletions core/datastore-impl/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
4 changes: 4 additions & 0 deletions core/datastore-impl/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

</manifest>
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package ru.yeahub.datastore_impl

import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.first
import ru.yeahub.datastore_api.TokenDataStore
import ru.yeahub.datastore_api.TokenStorageResult
import ru.yeahub.datastore_impl.crypto.CryptoManager

/**
* Реализация локального хранения токена через Preferences DataStore:
* - шифрует access token перед сохранением
* - читает и расшифровывает access token
* - очищает токены авторизации
*/
class TokenDataStoreImpl(
private val dataStore: DataStore<Preferences>,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У нас в приложении в манифесте включен бэкап, куда бэкапятся также shared preferences. Это риск. И в целом я думаю было бы безопаснее юзать для хранения такого токена что-то другое, вот из доков:

To back up user credentials and authentication tokens, don't store them in shared preferences or a file. Instead use Block Store APIs to store and manage credentials. This helps ensure that they are securely stored and can be backed up and restored alongside other app data.

https://developer.android.com/identity/data/autobackup

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Немного неправильно выражаюсь - у тебя же не shared preferences, а datastore. Datastore держит данные в файлике, по дефолту он без шифрования

private val cryptoManager: CryptoManager,
) : TokenDataStore {

override suspend fun saveAccessToken(accessToken: String): TokenStorageResult {
return runCatching {
dataStore.edit { preferences ->
val encryptedToken = cryptoManager.encrypt(accessToken)
preferences[ACCESS_TOKEN_KEY] = encryptedToken
}
}.fold(
onSuccess = {
TokenStorageResult.Success
},
onFailure = { exception ->
if (exception is CancellationException) {
throw exception
}

TokenStorageResult.Error
},
)
}

override suspend fun getAccessToken(): String? {
val encryptedToken =
dataStore.data.first()[ACCESS_TOKEN_KEY]
?: return null

return runCatching {
cryptoManager.decrypt(encryptedToken)
}.getOrNull()
}

override suspend fun clearTokens(): TokenStorageResult {
return runCatching {
dataStore.edit { preferences ->
preferences.remove(ACCESS_TOKEN_KEY)
}
}.fold(
onSuccess = {
TokenStorageResult.Success
},
onFailure = { exception ->
if (exception is CancellationException) {
throw exception
}

TokenStorageResult.Error
},
)
}

private companion object {
private val ACCESS_TOKEN_KEY = stringPreferencesKey("access_token")
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package ru.yeahub.datastore_impl.crypto

/**
* Контракт шифрования данных:
* - encrypt - шифрует строку
* - decrypt - расшифровывает строку
*/
interface CryptoManager {

fun encrypt(value: String): String

fun decrypt(value: String): String
}
Loading
Loading