From 08f8f034facf6ce75f2986065c05e24f86a662e8 Mon Sep 17 00:00:00 2001 From: BuNa <56534241+tmdgh1592@users.noreply.github.com> Date: Wed, 8 Nov 2023 16:17:40 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=9D=91=EB=8B=B5=20=EC=BD=94=EB=93=9C?= =?UTF-8?q?=EA=B0=80=20401=EC=9D=B4=EB=A9=B4=20=EB=A1=9C=EA=B7=B8=EC=9D=B8?= =?UTF-8?q?=20=ED=99=94=EB=A9=B4=EC=9C=BC=EB=A1=9C=20=EC=9D=B4=EB=8F=99?= =?UTF-8?q?=ED=95=98=EB=8A=94=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?(#831)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: 응답 코드가 401이면 로그인 화면으로 이동하는 기능 구현 * feat: 토큰이 만료되었을 때 토큰을 제거하는 로직 제거 * refactor: isAccessTokenInvalid로 메서드명 변경 --- .../data/common/retrofit/AuthInterceptor.kt | 32 ++++++++++++++++--- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/android/2023-emmsale/app/src/main/java/com/emmsale/data/common/retrofit/AuthInterceptor.kt b/android/2023-emmsale/app/src/main/java/com/emmsale/data/common/retrofit/AuthInterceptor.kt index 9508e40ed..326c77553 100644 --- a/android/2023-emmsale/app/src/main/java/com/emmsale/data/common/retrofit/AuthInterceptor.kt +++ b/android/2023-emmsale/app/src/main/java/com/emmsale/data/common/retrofit/AuthInterceptor.kt @@ -1,25 +1,47 @@ package com.emmsale.data.common.retrofit import android.content.Context +import android.content.Intent import com.emmsale.data.repository.interfaces.TokenRepository +import com.emmsale.presentation.ui.login.LoginActivity import dagger.hilt.EntryPoint import dagger.hilt.InstallIn import dagger.hilt.android.EntryPointAccessors import dagger.hilt.components.SingletonComponent import okhttp3.Interceptor +import okhttp3.Request import okhttp3.Response -class AuthInterceptor(context: Context) : Interceptor { +class AuthInterceptor(private val context: Context) : Interceptor { private val tokenRepository = EntryPointAccessors .fromApplication(context) .getTokenRepository() override fun intercept(chain: Interceptor.Chain): Response { val token = tokenRepository.getToken() - val newRequest = chain.request().newBuilder() - .addHeader(ACCESS_TOKEN_HEADER, ACCESS_TOKEN_FORMAT.format(token?.accessToken)) - .build() - return chain.proceed(newRequest) + val tokenAddedRequest = chain.request().putAccessToken(token?.accessToken) + + val response = chain.proceed(tokenAddedRequest) + if (response.isAccessTokenInvalid()) { + navigateToLogin() + } + return response + } + + private fun Response.isAccessTokenInvalid(): Boolean = (code == 401) + + private fun Request.putAccessToken(token: String?): Request = + putHeader(ACCESS_TOKEN_HEADER, ACCESS_TOKEN_FORMAT.format(token)) + + private fun Request.putHeader( + key: String, + value: String, + ): Request = newBuilder().addHeader(key, value).build() + + private fun navigateToLogin() { + val loginStartIntent = Intent(context, LoginActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(loginStartIntent) } @EntryPoint