-
Notifications
You must be signed in to change notification settings - Fork 1
[Feature/#8] AuthToken 저장을 위한 DataStore 구현 #15
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
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
b67eebb
Feat: AuthToken 데이터 클래스 추가
wjdrjs00 33004c6
Refactor: keystore 패키지 추가 및 관련 파일 이동
wjdrjs00 db6731f
Refactor: Crypto 클래스 리팩토링 및 테스트 코드 수정
wjdrjs00 397a912
Feat: security DI 모듈 추가
wjdrjs00 8852dff
Feat: AuthTokenSerializer 추가 및 테스트 코드 작성
wjdrjs00 0d7bac0
Feat: AuthTokenDataStore 구현
wjdrjs00 278c3ea
Feat: datastore DI 모듈 추가
wjdrjs00 dce3786
Chore: ktlintFormat 적용
wjdrjs00 3f3d93c
Chore: 오타 수정
wjdrjs00 cb9fd02
Chore: AuthTokenSerializerTest 테스트명 수정
wjdrjs00 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
Empty file.
37 changes: 37 additions & 0 deletions
37
core/datastore/src/main/java/com/threegap/bitnagil/datastore/di/DataStoreModule.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,37 @@ | ||
| package com.threegap.bitnagil.datastore.di | ||
|
|
||
| import android.content.Context | ||
| import androidx.datastore.core.DataStore | ||
| import androidx.datastore.core.DataStoreFactory | ||
| import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler | ||
| import androidx.datastore.dataStoreFile | ||
| import com.threegap.bitnagil.datastore.model.AuthToken | ||
| import com.threegap.bitnagil.datastore.serializer.AuthTokenSerializer | ||
| import com.threegap.bitnagil.datastore.serializer.TokenSerializer | ||
| import com.threegap.bitnagil.security.crypto.Crypto | ||
| import dagger.Module | ||
| import dagger.Provides | ||
| import dagger.hilt.InstallIn | ||
| import dagger.hilt.android.qualifiers.ApplicationContext | ||
| import dagger.hilt.components.SingletonComponent | ||
| import javax.inject.Singleton | ||
|
|
||
| @Module | ||
| @InstallIn(SingletonComponent::class) | ||
| object DataStoreModule { | ||
| @Provides | ||
| @Singleton | ||
| fun provideTokenSerializer(crypto: Crypto): TokenSerializer = AuthTokenSerializer(crypto) | ||
|
|
||
| @Provides | ||
| @Singleton | ||
| fun provideAuthTokenDataStore( | ||
| @ApplicationContext context: Context, | ||
| tokenSerializer: TokenSerializer, | ||
| ): DataStore<AuthToken> = | ||
| DataStoreFactory.create( | ||
| serializer = tokenSerializer, | ||
| produceFile = { context.dataStoreFile("auth-token.enc") }, | ||
| corruptionHandler = ReplaceFileCorruptionHandler { AuthToken() }, | ||
| ) | ||
| } |
9 changes: 9 additions & 0 deletions
9
core/datastore/src/main/java/com/threegap/bitnagil/datastore/model/AuthToken.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,9 @@ | ||
| package com.threegap.bitnagil.datastore.model | ||
|
|
||
| import kotlinx.serialization.Serializable | ||
|
|
||
| @Serializable | ||
| data class AuthToken( | ||
| val accessToken: String? = null, | ||
| val refreshToken: String? = null, | ||
| ) | ||
|
wjdrjs00 marked this conversation as resolved.
|
||
50 changes: 50 additions & 0 deletions
50
...datastore/src/main/java/com/threegap/bitnagil/datastore/serializer/AuthTokenSerializer.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,50 @@ | ||
| package com.threegap.bitnagil.datastore.serializer | ||
|
|
||
| import com.threegap.bitnagil.datastore.model.AuthToken | ||
| import com.threegap.bitnagil.security.crypto.Crypto | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.withContext | ||
| import kotlinx.serialization.json.Json | ||
| import java.io.InputStream | ||
| import java.io.OutputStream | ||
| import java.util.Base64 | ||
| import javax.inject.Inject | ||
|
|
||
| internal class AuthTokenSerializer | ||
| @Inject | ||
| constructor( | ||
| private val crypto: Crypto, | ||
| ) : TokenSerializer { | ||
| override val defaultValue: AuthToken | ||
| get() = AuthToken() | ||
|
|
||
| override suspend fun readFrom(input: InputStream): AuthToken { | ||
| return try { | ||
| val encryptedBytes = | ||
| withContext(Dispatchers.IO) { | ||
| input.use { it.readBytes() } | ||
| } | ||
| val decodedBytes = Base64.getDecoder().decode(encryptedBytes) | ||
| val decryptedBytes = crypto.decrypt(decodedBytes) | ||
| val decodedJsonString = decryptedBytes.decodeToString() | ||
| Json.decodeFromString(decodedJsonString) | ||
| } catch (e: Exception) { | ||
| AuthToken() | ||
| } | ||
| } | ||
|
|
||
| override suspend fun writeTo( | ||
| t: AuthToken, | ||
| output: OutputStream, | ||
| ) { | ||
| val json = Json.encodeToString(t) | ||
| val bytes = json.toByteArray() | ||
| val encryptedBytes = crypto.encrypt(bytes) | ||
| val encryptedBytesBase64 = Base64.getEncoder().encode(encryptedBytes) | ||
| withContext(Dispatchers.IO) { | ||
| output.use { | ||
| it.write(encryptedBytesBase64) | ||
| } | ||
| } | ||
| } | ||
| } |
6 changes: 6 additions & 0 deletions
6
core/datastore/src/main/java/com/threegap/bitnagil/datastore/serializer/TokenSerializer.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,6 @@ | ||
| package com.threegap.bitnagil.datastore.serializer | ||
|
|
||
| import androidx.datastore.core.Serializer | ||
| import com.threegap.bitnagil.datastore.model.AuthToken | ||
|
|
||
| interface TokenSerializer : Serializer<AuthToken> |
16 changes: 16 additions & 0 deletions
16
core/datastore/src/main/java/com/threegap/bitnagil/datastore/storage/AuthTokenDataStore.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 com.threegap.bitnagil.datastore.storage | ||
|
|
||
| import com.threegap.bitnagil.datastore.model.AuthToken | ||
| import kotlinx.coroutines.flow.Flow | ||
|
|
||
| interface AuthTokenDataStore { | ||
| val tokenFlow: Flow<AuthToken> | ||
|
|
||
| suspend fun updateAuthToken(authToken: AuthToken): AuthToken | ||
|
|
||
| suspend fun updateAccessToken(accessToken: String): AuthToken | ||
|
|
||
| suspend fun updateRefreshToken(refreshToken: String): AuthToken | ||
|
|
||
| suspend fun clearAuthToken(): AuthToken | ||
| } |
67 changes: 67 additions & 0 deletions
67
...datastore/src/main/java/com/threegap/bitnagil/datastore/storage/AuthTokenDataStoreImpl.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,67 @@ | ||
| package com.threegap.bitnagil.datastore.storage | ||
|
|
||
| import android.util.Log | ||
| import androidx.datastore.core.DataStore | ||
| import com.threegap.bitnagil.datastore.model.AuthToken | ||
| import kotlinx.coroutines.flow.Flow | ||
| import javax.inject.Inject | ||
|
|
||
| internal class AuthTokenDataStoreImpl | ||
| @Inject | ||
| constructor( | ||
| private val dataStore: DataStore<AuthToken>, | ||
| ) : AuthTokenDataStore { | ||
| override val tokenFlow: Flow<AuthToken> = dataStore.data | ||
|
|
||
| override suspend fun updateAuthToken(authToken: AuthToken): AuthToken = | ||
| runCatching { | ||
| dataStore.updateData { authToken } | ||
| }.fold( | ||
| onSuccess = { it }, | ||
| onFailure = { | ||
| Log.e(TAG, "updateAuthToken failed:", it) | ||
| throw it | ||
| }, | ||
| ) | ||
|
|
||
| override suspend fun updateAccessToken(accessToken: String): AuthToken = | ||
| runCatching { | ||
| dataStore.updateData { authToken -> | ||
| authToken.copy(accessToken = accessToken) | ||
| } | ||
| }.fold( | ||
| onSuccess = { it }, | ||
| onFailure = { | ||
| Log.e(TAG, "updateAccessToken failed:", it) | ||
| throw it | ||
| }, | ||
| ) | ||
|
|
||
| override suspend fun updateRefreshToken(refreshToken: String): AuthToken = | ||
| runCatching { | ||
| dataStore.updateData { authToken -> | ||
| authToken.copy(refreshToken = refreshToken) | ||
| } | ||
| }.fold( | ||
| onSuccess = { it }, | ||
| onFailure = { | ||
| Log.e(TAG, "updateRefreshToken failed:", it) | ||
| throw it | ||
| }, | ||
| ) | ||
|
|
||
| override suspend fun clearAuthToken(): AuthToken = | ||
| runCatching { | ||
| dataStore.updateData { AuthToken() } | ||
| }.fold( | ||
| onSuccess = { it }, | ||
| onFailure = { | ||
| Log.e(TAG, "clearAuthToken failed:", it) | ||
| throw it | ||
| }, | ||
| ) | ||
|
|
||
| companion object { | ||
| private const val TAG = "AuthTokenDataStore" | ||
| } | ||
| } |
96 changes: 96 additions & 0 deletions
96
...store/src/test/java/com/threegap/bitnagil/datastore/serializer/AuthTokenSerializerTest.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,96 @@ | ||
| package com.threegap.bitnagil.datastore.serializer | ||
|
|
||
| import com.threegap.bitnagil.datastore.model.AuthToken | ||
| import com.threegap.bitnagil.security.crypto.Crypto | ||
| import kotlinx.coroutines.test.runTest | ||
| import kotlinx.serialization.json.Json | ||
| import org.junit.Assert.assertEquals | ||
| import org.junit.Before | ||
| import org.junit.Test | ||
| import java.io.ByteArrayInputStream | ||
| import java.io.ByteArrayOutputStream | ||
| import java.util.Base64 | ||
|
|
||
| class AuthTokenSerializerTest { | ||
| private lateinit var serializer: AuthTokenSerializer | ||
| private lateinit var crypto: FakeCrypto | ||
| private lateinit var fakeToken: AuthToken | ||
| private lateinit var encrypted: ByteArray | ||
| private lateinit var json: String | ||
|
|
||
| private class FakeCrypto( | ||
| private val encryptResult: ByteArray, | ||
| private val decryptResult: ByteArray, | ||
| private val shouldFailDecrypt: Boolean = false, | ||
| ) : Crypto { | ||
| override fun encrypt(bytes: ByteArray): ByteArray = encryptResult | ||
|
|
||
| override fun decrypt(bytes: ByteArray): ByteArray { | ||
| if (shouldFailDecrypt) throw RuntimeException("복호화 실패") | ||
| return decryptResult | ||
| } | ||
| } | ||
|
|
||
| @Before | ||
| fun setUp() { | ||
| fakeToken = AuthToken("access", "refresh") | ||
| json = Json.encodeToString(fakeToken) | ||
| encrypted = "암호화된값".toByteArray() | ||
|
|
||
| crypto = | ||
| FakeCrypto( | ||
| encryptResult = encrypted, | ||
| decryptResult = json.toByteArray(), | ||
| ) | ||
|
|
||
| serializer = AuthTokenSerializer(crypto) | ||
| } | ||
|
|
||
| @Test | ||
| fun `writeTo는 AuthToken을 직렬화하여 기록한다`() = | ||
| runTest { | ||
| // given | ||
| val outputStream = ByteArrayOutputStream() | ||
|
|
||
| // when | ||
| serializer.writeTo(fakeToken, outputStream) | ||
|
|
||
| // then | ||
| val expected = Base64.getEncoder().encode(encrypted) | ||
| assertEquals(expected.toList(), outputStream.toByteArray().toList()) | ||
| } | ||
|
|
||
| @Test | ||
| fun `readFrom은 InputStream을 역직렬화하여 AuthToken으로 복원한다`() = | ||
| runTest { | ||
| // given | ||
| val input = Base64.getEncoder().encode(encrypted) | ||
| val inputStream = ByteArrayInputStream(input) | ||
|
|
||
| // when | ||
| val result = serializer.readFrom(inputStream) | ||
|
|
||
| // then | ||
| assertEquals(fakeToken, result) | ||
| } | ||
|
|
||
| @Test | ||
| fun `readFrom에서 예외 발생시 기본값을 반환한다`() = | ||
| runTest { | ||
| // given | ||
| val brokenCrypto = | ||
| FakeCrypto( | ||
| encryptResult = byteArrayOf(), | ||
| decryptResult = byteArrayOf(), | ||
| shouldFailDecrypt = true, | ||
| ) | ||
| val brokenSerializer = AuthTokenSerializer(brokenCrypto) | ||
| val inputStream = ByteArrayInputStream(Base64.getEncoder().encode(encrypted)) | ||
|
|
||
| // when | ||
| val result = brokenSerializer.readFrom(inputStream) | ||
|
|
||
| // then | ||
| assertEquals(AuthToken(), result) | ||
| } | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.