-
Notifications
You must be signed in to change notification settings - Fork 1
[Feature/#179] authenticator 구현 #180
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
Closed
Closed
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
a01d87b
#179 [move] : move directory
chanubc d4c772d
#179 [remove] : remove ununsed annotation
chanubc 968e3dd
#179 [feat] : authenticator 구현
chanubc d5117e5
#179 [feat] : App 재시작 및 토스트 출력을 위한 AppReStarter 구현 및 DI 설정
chanubc b818d23
#179 [add] : add common module dependency in network module
chanubc 5e024dd
#179 [mod] : use app restarter interface in authenticator, fragment
chanubc 13442b9
#179 [mod] : 무한 401 루프 방지용 custom header 추가
chanubc 683fb27
#179 [chore] : remove unncessary scope
chanubc 32861c3
#179 [chore] : remove unnecessary di provides in tokenInterceptor
chanubc 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
7 changes: 7 additions & 0 deletions
7
core/common/src/main/java/com/teamwable/common/restarter/AppReStarter.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,7 @@ | ||
| package com.teamwable.common.restarter | ||
|
|
||
| interface AppReStarter { | ||
| fun restartApp() | ||
|
|
||
| fun makeToast(message: String) | ||
| } |
17 changes: 17 additions & 0 deletions
17
core/common/src/main/java/com/teamwable/common/restarter/AppReStarterModule.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,17 @@ | ||
| package com.teamwable.common.restarter | ||
|
|
||
| import dagger.Binds | ||
| import dagger.Module | ||
| import dagger.hilt.InstallIn | ||
| import dagger.hilt.components.SingletonComponent | ||
| import javax.inject.Singleton | ||
|
|
||
| @Module | ||
| @InstallIn(SingletonComponent::class) | ||
| abstract class AppReStarterModule { | ||
| @Binds | ||
| @Singleton | ||
| abstract fun bindsAppRestarter( | ||
| appRestarter: DefaultAppReStarter, | ||
| ): AppReStarter | ||
| } |
36 changes: 36 additions & 0 deletions
36
core/common/src/main/java/com/teamwable/common/restarter/DefaultAppReStarter.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,36 @@ | ||
| package com.teamwable.common.restarter | ||
|
|
||
| import android.content.Context | ||
| import android.content.Intent | ||
| import android.widget.Toast | ||
| import dagger.hilt.android.qualifiers.ApplicationContext | ||
| import kotlinx.coroutines.CoroutineScope | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.launch | ||
| import javax.inject.Inject | ||
|
|
||
| class DefaultAppReStarter @Inject constructor( | ||
| @ApplicationContext private val context: Context, | ||
| ) : AppReStarter { | ||
| private var currentToast: Toast? = null | ||
| private val scope = CoroutineScope(Dispatchers.Main) | ||
|
|
||
| override fun restartApp() { | ||
| scope.launch { | ||
| val restartIntent = context.packageManager | ||
| .getLaunchIntentForPackage(context.packageName) | ||
| ?.component | ||
| ?.let(Intent::makeRestartActivityTask) | ||
|
|
||
| context.startActivity(restartIntent) | ||
| } | ||
| } | ||
|
|
||
| override fun makeToast(message: String) { | ||
| scope.launch { | ||
| currentToast?.cancel() | ||
| currentToast = Toast.makeText(context, message, Toast.LENGTH_SHORT) | ||
| currentToast?.show() | ||
| } | ||
| } | ||
| } | ||
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
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
65 changes: 65 additions & 0 deletions
65
core/network/src/main/java/com/teamwable/network/TokenAuthenticator.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,65 @@ | ||
| package com.teamwable.network | ||
|
|
||
| import com.teamwable.common.restarter.AppReStarter | ||
| import com.teamwable.datastore.datasource.WablePreferencesDataSource | ||
| import com.teamwable.network.datasource.AuthService | ||
| import com.teamwable.network.util.runSuspendCatching | ||
| import kotlinx.coroutines.flow.first | ||
| import kotlinx.coroutines.runBlocking | ||
| import kotlinx.coroutines.sync.Mutex | ||
| import kotlinx.coroutines.sync.withLock | ||
| import okhttp3.Authenticator | ||
| import okhttp3.Request | ||
| import okhttp3.Response | ||
| import okhttp3.Route | ||
| import timber.log.Timber | ||
| import javax.inject.Inject | ||
|
|
||
| class TokenAuthenticator @Inject constructor( | ||
| private val dataStore: WablePreferencesDataSource, | ||
| private val authService: AuthService, | ||
| private val appRestarter: AppReStarter, | ||
| ) : Authenticator { | ||
| private val mutex = Mutex() | ||
|
|
||
| override fun authenticate(route: Route?, response: Response): Request? { | ||
| if (response.code != 401) return null | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 토큰 만료만 401로 오나요?! 따로 토큰 만료인지 확인하는 분기가 없어도 되는지 궁금합니다! |
||
|
|
||
| if (response.request.header("Authorization-Retry") != null) return null | ||
|
|
||
| return runBlocking { | ||
| val newAccessToken = refreshToken() ?: return@runBlocking null | ||
| response.request | ||
| .newBuilder() | ||
| .header("Authorization", newAccessToken) | ||
| .header("Authorization-Retry", "true") | ||
| .build() | ||
| } | ||
| } | ||
|
|
||
| private suspend fun refreshToken(): String? { | ||
| return mutex.withLock { | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 👍 👍 👍 👍 👍 |
||
| val accessToken = dataStore.accessToken.first() | ||
| val refreshToken = dataStore.refreshToken.first() | ||
|
|
||
| runSuspendCatching { | ||
| authService.getReissueToken(accessToken, refreshToken) | ||
| }.onSuccess { | ||
| val newAccess = "Bearer ${it.data.accessToken}" | ||
| dataStore.updateAccessToken(newAccess) | ||
| dataStore.updateRefreshToken(it.data.refreshToken) | ||
| return newAccess | ||
| }.onFailure { | ||
| Timber.e(it) | ||
| dataStore.clear() | ||
| notifyReLoginRequired() | ||
| } | ||
| null | ||
| } | ||
| } | ||
|
|
||
| private fun notifyReLoginRequired() { | ||
| appRestarter.makeToast("재 로그인이 필요해요") | ||
| appRestarter.restartApp() | ||
| } | ||
| } | ||
102 changes: 6 additions & 96 deletions
102
core/network/src/main/java/com/teamwable/network/TokenInterceptor.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 |
|---|---|---|
| @@ -1,112 +1,22 @@ | ||
| package com.teamwable.network | ||
|
|
||
| import android.app.Application | ||
| import android.content.Intent | ||
| import android.widget.Toast | ||
| import com.teamwable.datastore.datasource.WablePreferencesDataSource | ||
| import com.teamwable.network.datasource.AuthService | ||
| import kotlinx.coroutines.CoroutineScope | ||
| import kotlinx.coroutines.Dispatchers | ||
| import kotlinx.coroutines.flow.first | ||
| import kotlinx.coroutines.launch | ||
| import kotlinx.coroutines.runBlocking | ||
| import kotlinx.coroutines.sync.Mutex | ||
| import kotlinx.coroutines.sync.withLock | ||
| import kotlinx.coroutines.withContext | ||
| import okhttp3.Interceptor | ||
| import okhttp3.Request | ||
| import okhttp3.Response | ||
| import javax.inject.Inject | ||
| import javax.inject.Singleton | ||
|
|
||
| @Singleton | ||
| class TokenInterceptor @Inject constructor( | ||
| private val wablePreferencesDataSource: WablePreferencesDataSource, | ||
| private val context: Application, | ||
| private val authService: AuthService, | ||
| private val dataStore: WablePreferencesDataSource, | ||
| ) : Interceptor { | ||
| private val mutex = Mutex() | ||
| private var currentToast: Toast? = null | ||
|
|
||
| override fun intercept(chain: Interceptor.Chain): Response { | ||
| val originalRequest = chain.request() | ||
| var response = chain.proceed(originalRequest.newAuthBuilder()) | ||
|
|
||
| if (response.code == CODE_TOKEN_EXPIRE) { | ||
| response.close() | ||
| val tokenRefreshed = runBlocking { | ||
| refreshTokenIfNeeded() | ||
| } | ||
| if (tokenRefreshed) { | ||
| response = chain.proceed(originalRequest.newAuthBuilder()) | ||
| } else { | ||
| handleFailedTokenReissue() | ||
| } | ||
| } | ||
| return response | ||
| } | ||
|
|
||
| private suspend fun refreshTokenIfNeeded(): Boolean { | ||
| mutex.withLock { | ||
| val accessToken = wablePreferencesDataSource.accessToken.first() | ||
| val refreshToken = wablePreferencesDataSource.refreshToken.first() | ||
|
|
||
| return try { | ||
| val tokenResult = runBlocking(Dispatchers.IO) { | ||
| authService.getReissueToken(accessToken, refreshToken) | ||
| } | ||
|
|
||
| when (tokenResult.success) { | ||
| true -> { | ||
| wablePreferencesDataSource.updateAccessToken( | ||
| BEARER + tokenResult.data.accessToken, | ||
| ) | ||
| true | ||
| } | ||
|
|
||
| false -> false | ||
| } | ||
| } catch (e: Exception) { | ||
| false | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private fun handleFailedTokenReissue() = CoroutineScope(Dispatchers.Main).launch { | ||
| showToast() | ||
| withContext(Dispatchers.IO) { | ||
| wablePreferencesDataSource.clear() | ||
| } | ||
| restartActivity() | ||
| } | ||
|
|
||
| private fun showToast() { | ||
| currentToast?.cancel() | ||
| currentToast = Toast.makeText(context, "재 로그인이 필요해요", Toast.LENGTH_SHORT) | ||
| currentToast?.show() | ||
| } | ||
|
|
||
| private suspend fun restartActivity() = with(context) { | ||
| mutex.withLock { | ||
| startActivity( | ||
| Intent.makeRestartActivityTask( | ||
| packageManager.getLaunchIntentForPackage(packageName)?.component, | ||
| ), | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| private fun Request.newAuthBuilder() = newBuilder() | ||
| .addHeader( | ||
| name = AUTHORIZATION, | ||
| value = runBlocking { | ||
| wablePreferencesDataSource.accessToken.first() | ||
| }, | ||
| ).build() | ||
| val accessToken = runBlocking { dataStore.accessToken.first() } | ||
| val authRequest: Request = chain.request().newBuilder() | ||
| .addHeader("Authorization", accessToken) | ||
| .build() | ||
|
|
||
| companion object { | ||
| const val CODE_TOKEN_EXPIRE = 401 | ||
| const val AUTHORIZATION = "Authorization" | ||
| const val BEARER = "Bearer " | ||
| return chain.proceed(authRequest) | ||
| } | ||
| } |
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
3 changes: 1 addition & 2 deletions
3
...teamwable/data/util/runSuspendCatching.kt → ...mwable/network/util/runSuspendCatching.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
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.
🛠️ Refactor suggestion
앱 재시작 시 null 안전성 개선 필요
getLaunchIntentForPackage()가 null을 반환할 경우startActivity(null)로 인한 예외가 발생할 수 있습니다.다음과 같이 null 체크를 추가하세요:
override fun restartApp() { scope.launch { val restartIntent = context.packageManager .getLaunchIntentForPackage(context.packageName) ?.component ?.let(Intent::makeRestartActivityTask) - - context.startActivity(restartIntent) + + restartIntent?.let { + context.startActivity(it) + } ?: run { + // 로그 출력 또는 다른 처리 + } } }🤖 Prompt for AI Agents