Skip to content

Commit

Permalink
feat: 응답 코드가 401이면 로그인 화면으로 이동하는 기능 구현 (#831)
Browse files Browse the repository at this point in the history
* feat: 응답 코드가 401이면 로그인 화면으로 이동하는 기능 구현

* feat: 토큰이 만료되었을 때 토큰을 제거하는 로직 제거

* refactor: isAccessTokenInvalid로 메서드명 변경
  • Loading branch information
tmdgh1592 authored Nov 8, 2023
1 parent d3060d7 commit 08f8f03
Showing 1 changed file with 27 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -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<AuthInterceptorEntryPoint>(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
Expand Down

0 comments on commit 08f8f03

Please sign in to comment.