-
Notifications
You must be signed in to change notification settings - Fork 1
Добавлено локальное хранение токена авторизации #149
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Gaileks
wants to merge
3
commits into
epic/ANDR-81
Choose a base branch
from
feature/ANDR-87-local-storage
base: epic/ANDR-81
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
16 changes: 16 additions & 0 deletions
16
core/datastore-api/src/main/java/ru/yeahub/datastore_api/TokenDataStore.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
13 changes: 13 additions & 0 deletions
13
core/datastore-api/src/main/java/ru/yeahub/datastore_api/TokenStorageResult.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
76 changes: 76 additions & 0 deletions
76
core/datastore-impl/src/main/java/ru/yeahub/datastore_impl/TokenDataStoreImpl.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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>, | ||
| 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") | ||
| } | ||
| } | ||
13 changes: 13 additions & 0 deletions
13
core/datastore-impl/src/main/java/ru/yeahub/datastore_impl/crypto/CryptoManager.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Немного неправильно выражаюсь - у тебя же не shared preferences, а datastore. Datastore держит данные в файлике, по дефолту он без шифрования