Skip to content

Instantly share code, notes, and snippets.

@robertlevonyan
Created March 30, 2022 12:31
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 robertlevonyan/f159883d7107dfe2934510d96e46766a to your computer and use it in GitHub Desktop.
Save robertlevonyan/f159883d7107dfe2934510d96e46766a to your computer and use it in GitHub Desktop.
class TokenInterceptor(
private val preferencesService: PreferencesService, // shared prefs or data store
private val retrofit: Retrofit,
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response = runBlocking {
val request: Request = chain.request()
val response = chain.proceed(request = request)
if (!response.isSuccessful && response.code == 401) {
response.close()
// API service to get refresh token
val tokenService: TokenService = retrofit.create(TokenService::class.java)
val apiToken = when (val refreshTokenResult = tokenService.refreshToken(refreshTokenService)) {
is Success -> refreshTokenResult.data
is ActionResult.Error -> tokenService.generateToken()
}
preferencesService.setToken(token = apiToken.token)
preferencesService.setRefreshToken(token = apiToken.refreshToken)
val newRequest = request.newBuilder()
.removeHeader("Authorization")
.addHeader("Authorization", "Bearer " + apiToken.token)
.build()
chain.proceed(request = newRequest)
} else {
response
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment