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] errorcode 추출 방법 수정 #69

Merged
merged 9 commits into from
Jan 10, 2024
41 changes: 28 additions & 13 deletions app/src/main/java/com/going/doorip/di/AuthInterceptor.kt
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package com.going.doorip.di

import android.content.Context
import com.going.data.dto.BaseResponse
import com.going.data.local.GoingDataStore
import com.going.domain.entity.response.AuthTokenModel
import com.going.domain.repository.TokenRepository
import com.going.doorip.BuildConfig.BASE_URL
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.serialization.json.Json
import okhttp3.Interceptor
import okhttp3.Request
Expand All @@ -16,15 +14,17 @@ import javax.inject.Inject

class AuthInterceptor @Inject constructor(
private val json: Json,
private val dataStore: GoingDataStore,
@ApplicationContext private val context: Context,
private val tokenRepository: TokenRepository,
) : Interceptor {

override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()

Timber.d("GET ACCESS TOKEN : ${dataStore.accessToken}")
Timber.d("GET ACCESS TOKEN : ${tokenRepository.getAccessToken()}")

val authRequest = if (dataStore.accessToken.isNotBlank()) {
val authRequest = if (tokenRepository.getAccessToken()
.isNotBlank()
) {
originalRequest.newAuthBuilder().build()
} else {
originalRequest
Expand All @@ -34,9 +34,17 @@ class AuthInterceptor @Inject constructor(
when (response.code) {
CODE_TOKEN_EXPIRED -> {
try {
// refreshToken을 얻기 위해서 인터셉터 내부에서 직접적으로 통신을 하는게 맞을까?
// app 레이어에서 data layer에 직접 접근하는 것도 맘에 안들고, 직접 통신하는게 아키텍쳐 구조를 헤친다는 생각이 듦
// 속도를 측정해보고 repository를 사용한 통신방법이 속도가 느리지 않다면
// 추후 repository를 활용한 통신으로 수정할 예정
// 앱잼 기간내에 수정하는게 목표라 주석을 남겨두겠습니다. 수정 못할거 같으면 주석만 지울게용
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ아

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기가 팀블로그인듯

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

항상 고민하면서 코드 짜는 거 멋있습니다~!

val refreshTokenRequest = originalRequest.newBuilder().post("".toRequestBody())
.url("$BASE_URL/api/users/reissue")
.addHeader(AUTHORIZATION, dataStore.refreshToken)
.addHeader(
AUTHORIZATION,
tokenRepository.getRefreshToken(),
)
.build()
val refreshTokenResponse = chain.proceed(refreshTokenRequest)
Timber.d("GET REFRESH TOKEN : $refreshTokenResponse")
Expand All @@ -46,15 +54,21 @@ class AuthInterceptor @Inject constructor(
refreshTokenResponse.body?.string().toString(),
) as BaseResponse<AuthTokenModel>

with(dataStore) {
accessToken = responseToken.data.accessToken
refreshToken = responseToken.data.refreshToken
}
tokenRepository.setTokens(
accessToken = responseToken.data.accessToken,
refreshToken = responseToken.data.refreshToken,
)
refreshTokenResponse.close()
val newRequest = originalRequest.newAuthBuilder().build()
return chain.proceed(newRequest)
}

tokenRepository.clearTokens()

// refreshToken 만료 처리를 위한 리프레시 토큰 만료 코드 포함 리스폰스 리턴
return refreshTokenResponse
} catch (t: Throwable) {
tokenRepository.clearTokens()
Timber.e(t)
}
}
Expand All @@ -63,10 +77,11 @@ class AuthInterceptor @Inject constructor(
}

private fun Request.newAuthBuilder() =
this.newBuilder().addHeader(AUTHORIZATION, "Bearer ${dataStore.accessToken}")
this.newBuilder().addHeader(AUTHORIZATION, "$BEARER ${tokenRepository.getAccessToken()}")

companion object {
private const val CODE_TOKEN_EXPIRED = 401
private const val BEARER = "Bearer"
private const val AUTHORIZATION = "Authorization"
}
}
3 changes: 1 addition & 2 deletions app/src/main/java/com/going/doorip/di/RetrofitModule.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package com.going.doorip.di

import com.going.doorip.BuildConfig.BASE_URL
import com.going.going.di.AuthInterceptor
import com.going.going.di.qualifier.JWT
import com.going.doorip.di.qualifier.JWT
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import dagger.Module
import dagger.Provides
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ interface TokenRepository {
fun getRefreshToken(): String

fun setTokens(accessToken: String, refreshToken: String)

fun clearTokens()
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import com.going.presentation.R
import com.going.presentation.databinding.ActivitySigninBinding
import com.going.presentation.onboarding.signup.OnboardingProfileSettingActivity
import com.going.presentation.tendencytest.TendencyTestActivity
import com.going.presentation.tendencytest.TendencyTestSplashActivity
import com.going.ui.base.BaseActivity
import com.going.ui.extension.setOnSingleClickListener
import com.going.ui.extension.toast
Expand Down Expand Up @@ -84,7 +85,7 @@ class SignInActivity : BaseActivity<ActivitySigninBinding>(R.layout.activity_sig
}

private fun navigateToTendencyScreen() {
Intent(this, TendencyTestActivity::class.java).apply {
Intent(this, TendencyTestSplashActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(this)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class SplashActivity : BaseActivity<ActivitySplashBinding>(R.layout.activity_spl
if (viewModel.getHasAccessToken()) {
navigateToMainScreen()
} else {
// api 호출로 변경 예정
navigateToSignInScreen()
}
}, 3000)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,4 @@ class SplashViewModel @Inject constructor(
private val tokenRepository: TokenRepository,
) : ViewModel() {
fun getHasAccessToken(): Boolean = tokenRepository.getAccessToken().isNotBlank()

fun clearTokens() = tokenRepository.clearTokens()
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.going.presentation.tendencytest

import android.content.Intent
import android.os.Bundle
import com.going.presentation.R
import com.going.presentation.databinding.ActivityTendencyTestSplashBinding
Expand All @@ -16,7 +17,13 @@ class TendencyTestSplashActivity :

private fun initStartBtnClickListener() {
binding.btnTendencySplashStart.setOnSingleClickListener {
// 페이지 이동~
navigateToTendencyTestScreen()
}
}

private fun navigateToTendencyTestScreen() {
Intent(this, TendencyTestActivity::class.java).apply {
startActivity(this)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
package com.going.presentation.util

import android.util.Log
import org.json.JSONObject
import retrofit2.HttpException

fun toErrorCode(throwable: Throwable): String = if (throwable is HttpException) {
val jsonTemp = throwable.response()?.errorBody()?.byteString().toString()
Log.e("TAG", "toErrorCode: $jsonTemp", )
val json = jsonTemp.slice(6 until jsonTemp.length - 2) + "}"
Log.e("TAG", "toErrorCode: $json", )
JSONObject(json).getString("code")
val codeIndex = jsonTemp.indexOf("code")
var errorCode = jsonTemp.slice(codeIndex + 7..codeIndex + 12)

if (errorCode.endsWith('\"')) errorCode = errorCode.slice(0 until errorCode.length - 1)

errorCode
} else {
"NOT_HTTP"
}

// 기능 오류 발견!!!! 반드시 수정 필요!!!!!!
2 changes: 1 addition & 1 deletion presentation/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<string name="will_be_update">해당 기능은 추후 업데이트 예정이에요 :)</string>

<string name="sign_in_tv_title">여행을 시작해보세요</string>
<string name="sign_in_tv_terms"><u>개인정보처리방침</u></string>
<string name="sign_in_tv_terms">개인정보처리방침</string>

<string name="counter">%1$d/%2$d</string>

Expand Down