Skip to content

Instantly share code, notes, and snippets.

@tfcporciuncula
Last active March 9, 2024 13:32
Show Gist options
  • Save tfcporciuncula/827416103c692b046ec47725d480d772 to your computer and use it in GitHub Desktop.
Save tfcporciuncula/827416103c692b046ec47725d480d772 to your computer and use it in GitHub Desktop.
class TokenAuthenticator @Inject constructor(
private val api: Api,
private val tokenStore: TokenStore,
private val logoutTrigger: LogoutTrigger
) : Authenticator {
companion object {
const val AUTH_HEADER_NAME = "Authorization"
const val AUTH_HEADER_VALUE_FORMAT = "Bearer %s"
}
override fun authenticate(route: Route?, response: Response): Request? {
Timber.i("Attempting to refresh token.")
if (response.request.url.encodedPath.endsWith("access_token")) {
Timber.e("Failed to refresh token.")
logoutTrigger.run()
return null
}
val refreshToken = tokenStore.refreshToken()
if (refreshToken == null) {
Timber.e("Refresh token is not available.")
logoutTrigger.run()
return null
}
runCatching {
val accessToken = runBlocking { api.accessToken(AccessTokenPayload(refreshToken)).accessToken }
tokenStore.saveAccessToken(accessToken)
return response.request.newBuilder()
.header(AUTH_HEADER_NAME, AUTH_HEADER_VALUE_FORMAT.format(accessToken))
.build()
}.onFailure {
Timber.e(it, "Failed to refresh token.")
}
logoutTrigger.run()
return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment