Skip to content
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

[Fix/reissue api exception]: 토큰 만료 시 Exception 발생 수정 #287

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@
<br />
</div>

![Alt](https://repobeats.axiom.co/api/embed/d2c401ae723c367a03ed9fb81ea6e6e7cfbee2ea.svg "Repobeats analytics image")

![Alt](https://repobeats.axiom.co/api/embed/d2c401ae723c367a03ed9fb81ea6e6e7cfbee2ea.svg "Repobeats analytics image")

<h2>Tech Stack</h2>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.hmh.hamyeonham.core.network.auth.authenticator

import android.content.Context
import android.util.Log
import com.hmh.hamyeonham.common.navigation.NavigationProvider
import com.hmh.hamyeonham.core.database.manger.DatabaseManager
import com.hmh.hamyeonham.core.network.auth.api.RefreshService
Expand All @@ -10,10 +9,13 @@ import com.jakewharton.processphoenix.ProcessPhoenix
import com.kakao.sdk.user.UserApiClient
import dagger.hilt.android.qualifiers.ApplicationContext
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
import javax.inject.Singleton

Expand All @@ -25,37 +27,50 @@ class HMHAuthenticator @Inject constructor(
private val databaseManager: DatabaseManager,
private val navigationProvider: NavigationProvider,
) : Authenticator {
private val mutex = Mutex()

override fun authenticate(route: Route?, response: Response): Request? {
if (response.request.header("Authorization") == null) {
val originalRequest = response.request
if (originalRequest.header("Authorization") == null) {
return null
}

// 401 상태 처리
if (response.code == 401) {
val refreshToken = dataStore.refreshToken
val newTokens = runCatching {
runBlocking {
api.refreshToken("Bearer $refreshToken")
}
}.onSuccess {
val data = it.data
dataStore.refreshToken = data.refreshToken.orEmpty()
dataStore.accessToken = data.accessToken.orEmpty()
}.onFailure {
Log.e("Authenticator", it.toString())
runBlocking {
dataStore.clear()
databaseManager.deleteAll()
UserApiClient.instance.logout { error ->
Log.e("Authenticator", error.toString())
ProcessPhoenix.triggerRebirth(context, navigationProvider.toLogin())
return runBlocking {
mutex.withLock {
try {
// 토큰 갱신 호출
val refreshToken = dataStore.refreshToken
val newTokens = api.refreshToken("Bearer $refreshToken").data

// 토큰 저장
dataStore.accessToken = newTokens.accessToken.orEmpty()
dataStore.refreshToken = newTokens.refreshToken.orEmpty()

// 새로운 요청 반환
originalRequest.newBuilder()
.header("Authorization", "Bearer ${newTokens.accessToken}")
.build()
} catch (e: Exception) {
Timber.tag("Authenticator").e("Token refresh failed: ${e.message}")
handleLogout()
null
}
}
}.getOrThrow()

return response.request.newBuilder()
.header("Authorization", "Bearer ${newTokens.data.accessToken}")
.build()
}
}
return null
}
}

private fun handleLogout() {
runBlocking {
dataStore.clear()
databaseManager.deleteAll()
UserApiClient.instance.logout { error ->
Timber.tag("Authenticator").e("Logout error: $error")
ProcessPhoenix.triggerRebirth(context, navigationProvider.toLogin())
}
}
}
}
Loading