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

feat: 응답 코드가 401이면 로그인 화면으로 이동하는 기능 구현 #831

Merged
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
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
Loading