Last active
March 9, 2024 13:32
-
-
Save tfcporciuncula/827416103c692b046ec47725d480d772 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 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