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
6 changes: 3 additions & 3 deletions app/src/main/java/com/going/doorip/di/RetrofitModule.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package com.going.doorip.di

import com.going.data.interceptor.AuthInterceptor
import com.going.doorip.BuildConfig.BASE_URL
import com.going.doorip.di.qualifier.JWT
import com.going.ui.extension.isJsonArray
import com.going.ui.extension.isJsonObject
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import dagger.Module
import dagger.Provides
Expand Down Expand Up @@ -79,6 +82,3 @@ object RetrofitModule {
.addConverterFactory(factory)
.build()
}

fun String?.isJsonObject(): Boolean = this?.startsWith("{") == true && this.endsWith("}")
fun String?.isJsonArray(): Boolean = this?.startsWith("[") == true && this.endsWith("]")
5 changes: 5 additions & 0 deletions core-ui/src/main/java/com/going/ui/extension/StringExt.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.going.ui.extension

fun String?.isJsonObject(): Boolean = this?.startsWith("{") == true && this.endsWith("}")

fun String?.isJsonArray(): Boolean = this?.startsWith("[") == true && this.endsWith("]")
9 changes: 8 additions & 1 deletion data/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ android {

testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles("consumer-rules.pro")

buildConfigField(
"String",
"BASE_URL",
com.android.build.gradle.internal.cxx.configure.gradleLocalProperties(rootDir)
.getProperty("base.url"),
)
}

compileOptions {
Expand Down Expand Up @@ -60,4 +67,4 @@ dependencies {
androidTestImplementation(androidTest)
androidTestImplementation(espresso)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package com.going.doorip.di
package com.going.data.interceptor

import android.content.Context
import com.going.data.BuildConfig.BASE_URL
import com.going.data.dto.BaseResponse
import com.going.data.local.GoingDataStore
import com.going.domain.entity.response.AuthTokenModel
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 @@ -17,8 +15,8 @@ import javax.inject.Inject
class AuthInterceptor @Inject constructor(
private val json: Json,
private val dataStore: GoingDataStore,
@ApplicationContext private val context: Context,
) : Interceptor {

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

Expand All @@ -34,9 +32,17 @@ class AuthInterceptor @Inject constructor(
when (response.code) {
CODE_TOKEN_EXPIRED -> {
try {
// refreshToken을 얻기 위해서 인터셉터 내부에서 직접적으로 통신을 하는게 맞을까?
// 직접 통신하는게 기존의 통신방법과 차이가 있기 때문에 통일성을 해친다는 생각이 듦
// 그리고 이렇게 되면 Base Url이 App모듈에도 필요하고, Data모듈에도 필요함
// 그래서 지금 생각으론 Retrofit 관련 모듈이 data 모듈에 있어야 할 것 같음
// 앱잼 기간내에 수정하는게 목표라 주석을 남겨두겠습니다. 수정 못할거 같으면 주석만 지울게용
val refreshTokenRequest = originalRequest.newBuilder().post("".toRequestBody())
.url("$BASE_URL/api/users/reissue")
.addHeader(AUTHORIZATION, dataStore.refreshToken)
.addHeader(
AUTHORIZATION,
dataStore.refreshToken,
)
.build()
val refreshTokenResponse = chain.proceed(refreshTokenRequest)
Timber.d("GET REFRESH TOKEN : $refreshTokenResponse")
Expand All @@ -46,15 +52,30 @@ class AuthInterceptor @Inject constructor(
refreshTokenResponse.body?.string().toString(),
) as BaseResponse<AuthTokenModel>

with(dataStore) {
dataStore.apply {
accessToken = responseToken.data.accessToken
refreshToken = responseToken.data.refreshToken
}

refreshTokenResponse.close()

val newRequest = originalRequest.newAuthBuilder().build()
return chain.proceed(newRequest)
}

dataStore.apply {
accessToken = ""
refreshToken = ""
}

// refreshToken 만료 처리를 위한 리프레시 토큰 만료 코드 포함 리스폰스 리턴
return refreshTokenResponse
} catch (t: Throwable) {
dataStore.apply {
accessToken = ""
refreshToken = ""
}

Timber.e(t)
}
}
Expand All @@ -63,10 +84,11 @@ class AuthInterceptor @Inject constructor(
}

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

companion object {
private const val CODE_TOKEN_EXPIRED = 401
private const val BEARER = "Bearer"
private const val AUTHORIZATION = "Authorization"
}
}
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