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_api.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)

suspend fun getAccessToken(): String?

suspend fun clearTokens()
}
46 changes: 46 additions & 0 deletions core/datastore-impl/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
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.datastore.preferences)
implementation(libs.koin.core)
implementation(libs.koin.android)
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-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,38 @@
package ru.yeahub.datastore_api

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.flow.first

/**
* Реализация локального хранения токена через 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 держит данные в файлике, по дефолту он без шифрования

) : TokenDataStore {

override suspend fun saveAccessToken(accessToken: String) {
dataStore.edit { preferences ->
preferences[ACCESS_TOKEN_KEY] = accessToken
}
}

override suspend fun getAccessToken(): String? {
return dataStore.data.first()[ACCESS_TOKEN_KEY]
}

override suspend fun clearTokens() {
dataStore.edit { preferences ->
preferences.remove(ACCESS_TOKEN_KEY)
}
}

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

import androidx.datastore.core.DataStore
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.preferencesDataStoreFile
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import org.koin.android.ext.koin.androidContext
import org.koin.core.module.dsl.bind
import org.koin.core.module.dsl.singleOf
import org.koin.dsl.module
import ru.yeahub.datastore_api.TokenDataStore
import ru.yeahub.datastore_api.TokenDataStoreImpl

/**
* DI модуль локального хранения:
* - создаёт Preferences DataStore
* - регистрирует TokenDataStore
*/
val datastoreModule = module {
single<DataStore<Preferences>> {
PreferenceDataStoreFactory.create(
corruptionHandler = ReplaceFileCorruptionHandler(
produceNewData = {
emptyPreferences()
},
),
produceFile = {
androidContext().preferencesDataStoreFile(
name = DATASTORE_FILE_NAME,
)
},
)
}

singleOf(::TokenDataStoreImpl) {
bind<TokenDataStore>()
}
}

private const val DATASTORE_FILE_NAME = "auth_preferences"
1 change: 1 addition & 0 deletions feature/authentication/impl/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ android {
}

dependencies {
implementation(project(":core:datastore-api"))
implementation(project(":core:navigation-api"))
implementation(project(":core:network-api"))
implementation(libs.androidx.compose.material.icons.extended)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import ru.yeahub.authentication.impl.login.domain.entity.LoginError
import ru.yeahub.authentication.impl.login.domain.entity.LoginException
import ru.yeahub.authentication.impl.login.domain.entity.LoginModel
import ru.yeahub.authentication.impl.login.domain.repository.LoginRepositoryApi
import ru.yeahub.datastore_api.TokenDataStore
import ru.yeahub.network_api.models.ErrorResponseDto
import java.io.IOException

Expand All @@ -26,14 +27,28 @@ class LoginRepositoryImpl(
private val remoteDataSourceApi: LoginRemoteDataSourceApi,
private val domainToDataMapper: LoginDomainToDataMapper,
private val responseToDomainMapper: LoginResponseToDomainMapper,
private val tokenDataStore: TokenDataStore,
private val gson: Gson,
) : LoginRepositoryApi {

/**
* Выполняет авторизацию пользователя:
* - преобразует LoginModel в request DTO
* - вызывает backend
* - преобразует response DTO в AuthResult
* - сохраняет access token в локальное хранилище
*/
override suspend fun login(loginModel: LoginModel): AuthResult {
return try {
val request = domainToDataMapper.map(loginModel)
val response = remoteDataSourceApi.login(request)
responseToDomainMapper.map(response)
val authResult = responseToDomainMapper.map(response)

tokenDataStore.saveAccessToken(
accessToken = authResult.tokens.accessToken,
)

authResult
} catch (exception: CancellationException) {
throw exception
} catch (exception: IOException) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import ru.yeahub.authentication.impl.login.data.repository.remote.LoginRemoteDat
import ru.yeahub.authentication.impl.login.data.repository.LoginRepositoryImpl
import ru.yeahub.authentication.impl.login.data.repository.remote.LoginRemoteDataSourceImpl
import ru.yeahub.authentication.impl.login.domain.repository.LoginRepositoryApi
import ru.yeahub.authentication.impl.login.domain.usecase.CheckAuthStateUseCase
import ru.yeahub.authentication.impl.login.domain.usecase.LoginUseCase
import ru.yeahub.authentication.impl.login.domain.usecase.LogoutUseCase
import ru.yeahub.authentication.impl.login.presentation.mapper.LoginStateMapper
import ru.yeahub.authentication.impl.login.presentation.viewmodel.LoginViewModel

Expand All @@ -38,7 +40,9 @@ val loginFeatureModule = module {
bind<LoginRepositoryApi>()
}

factoryOf(::CheckAuthStateUseCase)
factoryOf(::LoginUseCase)
factoryOf(::LogoutUseCase)

singleOf(::LoginStateMapper)
viewModelOf(::LoginViewModel)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package ru.yeahub.authentication.impl.login.domain.usecase

import ru.yeahub.datastore_api.TokenDataStore

/**
* UseCase проверки авторизации пользователя:
* - возвращает true, если access token сохранён
*/
class CheckAuthStateUseCase(
private val tokenDataStore: TokenDataStore,
) {

suspend operator fun invoke(): Boolean {
return tokenDataStore.getAccessToken().isNullOrBlank().not()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package ru.yeahub.authentication.impl.login.domain.usecase

import ru.yeahub.datastore_api.TokenDataStore

/**
* UseCase выхода из аккаунта:
* - очищает сохранённые токены авторизации
*/
class LogoutUseCase(
private val tokenDataStore: TokenDataStore,
) {

suspend operator fun invoke() {
tokenDataStore.clearTokens()
}
}
4 changes: 4 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ runtimeVersion = "1.10.2"
ui = "1.10.2"
foundation = "1.10.2"
material3 = "1.4.0"
datastorePreferences = "1.2.1"

[libraries]
androidx-compose-material-icons-extended = { module = "androidx.compose.material:material-icons-extended" }
Expand All @@ -59,6 +60,9 @@ androidx-icons = { group = "androidx.compose.material", name = "material-icons-e
compose-markdown = { group = "com.github.jeziellago", name = "compose-markdown", version = "0.5.7" }
#androidx-material = { module = "androidx.compose.material:material", version.ref = "composeBom" }

#DATASTORE
androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "datastorePreferences" }

#RETROFIT
retrofit-core = { group = "com.squareup.retrofit2", name = "retrofit", version.ref = "retrofit" }
retrofit-gsonConverter = { group = "com.squareup.retrofit2", name = "converter-gson", version.ref = "retrofit" }
Expand Down
Loading
Loading