Skip to content

Instantly share code, notes, and snippets.

@EmmanuelGuther
Last active May 15, 2023 09:01
Show Gist options
  • Save EmmanuelGuther/d943afb2ff60371bbfb531e7b03a8614 to your computer and use it in GitHub Desktop.
Save EmmanuelGuther/d943afb2ff60371bbfb531e7b03a8614 to your computer and use it in GitHub Desktop.
Retrofit builder to handle calls with authorization requirements and interceptor with refresh token.
interface ApiRefreshToken {
companion object {
private const val REFRESH_TOKEN = "/refreshToken"
}
@FormUrlEncoded
@POST(REFRESH_TOKEN)
fun refreshToken(@Field("refreshToken") refreshToken: String?): Call<TokenModel>
}
class AuthenticationInterceptorRefreshToken @Inject constructor(private val retrofitBuilder: RetrofitBuilder, private val userManager: UserManager) : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response? {
val originalRequest = chain.request()
val authenticationRequest = request(originalRequest)
val initialResponse = chain.proceed(authenticationRequest)
when {
initialResponse.code() == 403 || initialResponse.code() == 401 -> {
val responseNewTokenLoginModel = retrofitBuilder.retrofit().create(ApiRefreshToken::class.java).refreshToken(userManager.load()?.refreshToken).execute()
return when {
responseNewTokenLoginModel == null || responseNewTokenLoginModel.code() != 200 -> {
AuthManager().authExpiredAndGoLogin(AndroidApplication().getContext())
null
}
else -> {
responseNewTokenLoginModel.body()?.accessToken?.let {
userManager.updateToken(it)
}
val newAuthenticationRequest = originalRequest.newBuilder().addHeader("Authorization", "Bearer " + responseNewTokenLoginModel.body()?.accessToken).build()
chain.proceed(newAuthenticationRequest)
}
}
}
else -> return initialResponse
}
}
private fun request(originalRequest: Request): Request {
return originalRequest.newBuilder()
.addHeader("Authorization", "Bearer ${userManager.load()?.accessToken}")
.addHeader("appVersion", BuildConfig.VERSION_NAME).build()
}
class RetrofitBuilder {
fun retrofitAuth(): Retrofit {
return Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(createClientAuth())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
private fun createClientAuth(): OkHttpClient {
val okHttpClientBuilder: OkHttpClient.Builder = OkHttpClient.Builder()
okHttpClientBuilder.addInterceptor(AuthenticationInterceptorRefreshToken(this, UserManager()))
return okHttpClientBuilder.build()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment