-
Notifications
You must be signed in to change notification settings - Fork 1
[FEAT] 유저 로그인, 회원 가입, 토큰 갱신, 자동 로그인, 로그아웃, Authorization 전역 헤더 구현 #20
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
5 commits
Select commit
Hold shift + click to select a range
53efebb
[FEAT] 유저 로그인, 회원 가입, 토큰 갱신, 자동 로그인, 로그아웃, Authorization 전역 헤더 구현
Sangyoon98 95ff3c5
[FIX] 코드 래빗 리뷰 사항 수정
Sangyoon98 d9036e2
[FIX] 코드 래빗 리뷰 사항 수정
Sangyoon98 85b24b5
[FIX] 버전 수정
Sangyoon98 3f7780c
[FIX] 코드 래빗 리뷰 사항 수정
Sangyoon98 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
Empty file.
118 changes: 118 additions & 0 deletions
118
app/src/main/java/com/sampoom/android/core/datastore/AuthPreferences.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,118 @@ | ||
| package com.sampoom.android.core.datastore | ||
|
|
||
| import android.content.Context | ||
| import androidx.datastore.preferences.core.Preferences | ||
| import androidx.datastore.preferences.core.edit | ||
| import androidx.datastore.preferences.core.longPreferencesKey | ||
| import androidx.datastore.preferences.core.stringPreferencesKey | ||
| import androidx.datastore.preferences.preferencesDataStore | ||
| import com.sampoom.android.feature.user.domain.model.User | ||
| import dagger.hilt.android.qualifiers.ApplicationContext | ||
| import javax.inject.Inject | ||
| import javax.inject.Singleton | ||
| import kotlinx.coroutines.flow.first | ||
| import kotlinx.coroutines.runBlocking | ||
|
|
||
| // Per official guidance, DataStore instance should be single and at top-level. | ||
| private val Context.authDataStore by preferencesDataStore(name = "auth_prefs") | ||
|
|
||
| @Singleton | ||
| class AuthPreferences @Inject constructor( | ||
| @param:ApplicationContext private val context: Context, | ||
| private val cryptoManager: CryptoManager | ||
| ){ | ||
| private val dataStore = context.authDataStore | ||
|
|
||
| private object Keys { | ||
| val ACCESS_TOKEN: Preferences.Key<String> = stringPreferencesKey("access_token") | ||
| val REFRESH_TOKEN: Preferences.Key<String> = stringPreferencesKey("refresh_token") | ||
| val TOKEN_EXPIRES_AT: Preferences.Key<Long> = longPreferencesKey("token_expires_at") | ||
| val USER_ID: Preferences.Key<String> = stringPreferencesKey("user_id") | ||
| val USER_NAME: Preferences.Key<String> = stringPreferencesKey("user_name") | ||
| val USER_ROLE: Preferences.Key<String> = stringPreferencesKey("user_role") | ||
| } | ||
|
|
||
| suspend fun saveUser(user: User) { | ||
| val expiresAt = System.currentTimeMillis() + (user.expiresIn * 1000) | ||
| dataStore.edit { prefs -> | ||
| prefs[Keys.ACCESS_TOKEN] = cryptoManager.encrypt(user.accessToken) | ||
| prefs[Keys.REFRESH_TOKEN] = cryptoManager.encrypt(user.refreshToken) | ||
| prefs[Keys.TOKEN_EXPIRES_AT] = expiresAt | ||
| prefs[Keys.USER_ID] = cryptoManager.encrypt(user.userId.toString()) | ||
| prefs[Keys.USER_NAME] = cryptoManager.encrypt(user.userName) | ||
| prefs[Keys.USER_ROLE] = cryptoManager.encrypt(user.role) | ||
| } | ||
| } | ||
|
Sangyoon98 marked this conversation as resolved.
|
||
|
|
||
| suspend fun saveToken(accessToken: String, refreshToken: String, expiresIn: Long) { | ||
| val expiresAt = System.currentTimeMillis() + (expiresIn * 1000) | ||
| dataStore.edit { prefs -> | ||
| prefs[Keys.ACCESS_TOKEN] = cryptoManager.encrypt(accessToken) | ||
| prefs[Keys.REFRESH_TOKEN] = cryptoManager.encrypt(refreshToken) | ||
| prefs[Keys.TOKEN_EXPIRES_AT] = expiresAt | ||
| } | ||
| } | ||
|
|
||
| suspend fun getStoredUser(): User? { | ||
| val prefs = dataStore.data.first() | ||
| val userId = prefs[Keys.USER_ID] | ||
| val userName = prefs[Keys.USER_NAME] | ||
| val userRole = prefs[Keys.USER_ROLE] | ||
| val accessToken = prefs[Keys.ACCESS_TOKEN] | ||
| val refreshToken = prefs[Keys.REFRESH_TOKEN] | ||
| val expiresAt = prefs[Keys.TOKEN_EXPIRES_AT] | ||
|
|
||
| if (userId != null && userName != null && userRole != null && | ||
| accessToken != null && refreshToken != null) { | ||
| try { | ||
| val remaining = expiresAt?.let { | ||
| kotlin.math.max(0L, (it - System.currentTimeMillis()) / 1000) | ||
| } ?: 0L | ||
|
|
||
| return User( | ||
| cryptoManager.decrypt(userId).toLong(), | ||
| cryptoManager.decrypt(userName), | ||
| cryptoManager.decrypt(userRole), | ||
| cryptoManager.decrypt(accessToken), | ||
| cryptoManager.decrypt(refreshToken), | ||
| remaining | ||
| ) | ||
| } catch (e: Exception) { | ||
| return null | ||
| } | ||
| } else return null | ||
| } | ||
|
|
||
| suspend fun getAccessToken(): String? { | ||
| val encrypted = dataStore.data.first()[Keys.ACCESS_TOKEN] ?: return null | ||
| return try { | ||
| cryptoManager.decrypt(encrypted) | ||
| } catch (e: Exception) { | ||
| null | ||
| } | ||
| } | ||
|
|
||
| suspend fun getRefreshToken(): String? { | ||
| val encrypted = dataStore.data.first()[Keys.REFRESH_TOKEN] ?: return null | ||
| return try { | ||
| cryptoManager.decrypt(encrypted) | ||
| } catch (e: Exception) { | ||
| null | ||
| } | ||
| } | ||
|
|
||
| suspend fun isTokenExpired(): Boolean { | ||
| val expiresAt = dataStore.data.first()[Keys.TOKEN_EXPIRES_AT] | ||
| return expiresAt == null || System.currentTimeMillis() > expiresAt | ||
| } | ||
|
|
||
| suspend fun clear() { | ||
| dataStore.edit { it.clear() } | ||
| } | ||
|
|
||
| suspend fun hasToken(): Boolean { | ||
| val accessToken = getAccessToken() | ||
| val refreshToken = getRefreshToken() | ||
| return !accessToken.isNullOrEmpty() && !refreshToken.isNullOrEmpty() | ||
| } | ||
| } | ||
62 changes: 62 additions & 0 deletions
62
app/src/main/java/com/sampoom/android/core/datastore/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,62 @@ | ||
| package com.sampoom.android.core.datastore | ||
|
|
||
| import android.content.Context | ||
| import android.security.keystore.KeyGenParameterSpec | ||
| import android.security.keystore.KeyProperties | ||
| import android.util.Base64 | ||
| import dagger.hilt.android.qualifiers.ApplicationContext | ||
| import java.security.KeyStore | ||
| import javax.crypto.Cipher | ||
| import javax.crypto.KeyGenerator | ||
| import javax.crypto.spec.GCMParameterSpec | ||
| import javax.inject.Inject | ||
| import javax.inject.Singleton | ||
|
|
||
| @Singleton | ||
| class CryptoManager @Inject constructor( | ||
| @param:ApplicationContext private val context: Context | ||
| ) { | ||
| private val keyAlias = "AuthTokenKey" | ||
| private val keyStore = KeyStore.getInstance("AndroidKeyStore") | ||
|
|
||
| init { | ||
| keyStore.load(null) | ||
| createKeyIfNeeded() | ||
| } | ||
|
|
||
| private fun createKeyIfNeeded() { | ||
| if (!keyStore.containsAlias(keyAlias)) { | ||
| val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") | ||
| val keyGenParameterSpec = KeyGenParameterSpec.Builder( | ||
| keyAlias, | ||
| KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT | ||
| ) | ||
| .setBlockModes(KeyProperties.BLOCK_MODE_GCM) | ||
| .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) | ||
| .setUserAuthenticationRequired(false) | ||
| .setRandomizedEncryptionRequired(true) | ||
| .build() | ||
| keyGenerator.init(keyGenParameterSpec) | ||
| keyGenerator.generateKey() | ||
| } | ||
| } | ||
|
|
||
| fun encrypt(plaintext: String): String { | ||
| val cipher = Cipher.getInstance("AES/GCM/NoPadding") | ||
| cipher.init(Cipher.ENCRYPT_MODE, keyStore.getKey(keyAlias, null)) | ||
| val iv = cipher.iv | ||
| val encrypted = cipher.doFinal(plaintext.toByteArray()) | ||
| return Base64.encodeToString(iv + encrypted, Base64.DEFAULT) | ||
| } | ||
|
|
||
| fun decrypt(encryptedText: String): String { | ||
| val encrypted = Base64.decode(encryptedText, Base64.DEFAULT) | ||
| val iv = encrypted.sliceArray(0..11) | ||
| val ciphertext = encrypted.sliceArray(12 until encrypted.size) | ||
|
|
||
| val cipher = Cipher.getInstance("AES/GCM/NoPadding") | ||
| val spec = GCMParameterSpec(128, iv) | ||
| cipher.init(Cipher.DECRYPT_MODE, keyStore.getKey(keyAlias, null), spec) | ||
| return String(cipher.doFinal(ciphertext)) | ||
| } | ||
| } |
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
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.