Created
February 16, 2019 10:40
-
-
Save EmmanuelGuther/a023585f2221dc2818ba8811adbc5f55 to your computer and use it in GitHub Desktop.
Refresh token interceptor whit multiple calls at same time supported
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun createClientAuth(): OkHttpClient { | |
//ADD DISPATCHER WITH MAX REQUEST TO 1 | |
val dispatcher = Dispatcher() | |
dispatcher.maxRequests = 1 | |
val okHttpClientBuilder: OkHttpClient.Builder = OkHttpClient.Builder() | |
okHttpClientBuilder.dispatcher(dispatcher) | |
okHttpClientBuilder.addInterceptor(AuthenticationInterceptorRefreshToken(this, UserManager())) | |
return okHttpClientBuilder.build() | |
} | |
} | |
class AuthenticationInterceptorRefreshToken @Inject constructor(private val retrofitBuilder: RetrofitBuilder, private val userManager: UserManager) : Interceptor { | |
@Throws(IOException::class) | |
override fun intercept(chain: Interceptor.Chain): Response? { | |
//MAKE SYNCHRONIZED | |
synchronized(this) { | |
val originalRequest = chain.request() | |
val authenticationRequest = originalRequest.newBuilder() | |
.addHeader("Authorization", "Bearer ${userManager.load()?.accessToken}") | |
.addHeader("appVersion", BuildConfig.VERSION_NAME).build() | |
val initialResponse = chain.proceed(authenticationRequest) | |
when { | |
initialResponse.code() == 403 || initialResponse.code() == 401 -> { | |
//RUN BLOCKING!! | |
val responseNewTokenLoginModel = runBlocking { | |
retrofitBuilder.retrofit().create(ApiRefreshToken::class.java).refreshToken(userManager.load()?.refreshToken).execute() | |
} | |
return when { | |
responseNewTokenLoginModel == null || responseNewTokenLoginModel.code() != 200 -> { | |
AuthManager().authExpiredAndGoLogin(AndroidApplication().getContext()) | |
null | |
} | |
else -> { | |
responseNewTokenLoginModel.body()?.accessToken?.let { | |
userManager.updateToken(it) | |
} | |
val newAuthenticationRequest = originalRequest.newBuilder().addHeader("Authorization", "Bearer " + responseNewTokenLoginModel.body()?.accessToken).build() | |
chain.proceed(newAuthenticationRequest) | |
} | |
} | |
} | |
else -> return initialResponse | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment