-
-
Save ColtonIdle/309472a2f24b935981e1ec17f57e4ed3 to your computer and use it in GitHub Desktop.
This file contains 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
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