Skip to content

Instantly share code, notes, and snippets.

@ColtonIdle
Created April 25, 2022 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ColtonIdle/309472a2f24b935981e1ec17f57e4ed3 to your computer and use it in GitHub Desktop.
Save ColtonIdle/309472a2f24b935981e1ec17f57e4ed3 to your computer and use it in GitHub Desktop.
class ApiTokenRefreshInterceptor(
private val appUserManager: AppUserManager,
private val apiService: Lazy<MyApiService>,
) : Authenticator {
override fun authenticate(route: Route?, response: Response): Request? {
if (appUserManager.refreshToken == null) {
// 401, can't try re-auth flow — no refresh token
refreshFailure()
return null
}
// 401, attempt re-auth flow with refresh token
synchronized(this) {
val refreshToken = appUserManager.refreshToken
val refreshResponse = runBlocking {
apiService.get().refreshAuth(refreshToken!!)
}
return when (refreshResponse) {
is ApiResult.Success -> refreshSuccess(refreshResponse, response)
is ApiResult.Failure -> refreshFailure()
}
}
}
private fun refreshFailure(): Nothing? {
//Re-auth: failure — logging out
appUserManager.logOut()
return null
}
private fun refreshSuccess(
refreshResponse: ApiResult.Success<SuccessResponse<LoginResponse>>,
response: Response
): Request {
//Re-auth: success — re-run network call that 401'd
appUserManager.login(
refreshResponse.value.data.access_token,
refreshResponse.value.data.refresh_token,
)
return response
.request
.newBuilder()
.header("Authorization", "Bearer: ${appUserManager.authToken!!}")
.build()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment