Skip to content

Instantly share code, notes, and snippets.

@AndSky90
Last active November 16, 2019 13:13
Show Gist options
  • Save AndSky90/7aadbacdfb6c6197949837783f9dc463 to your computer and use it in GitHub Desktop.
Save AndSky90/7aadbacdfb6c6197949837783f9dc463 to your computer and use it in GitHub Desktop.
Okhttp config
class AccessTokenAuthenticator : Authenticator {
@Throws(IOException::class)
override fun authenticate(route: Route?, response: Response): Request? {
val token = AuthProvider.getTokenInfoFromCache()?.refreshToken?.token
val coreNetworkComponent = CoreNetworkComponent.get()
synchronized(this) {
if (token != null) {
log("access-token refreshing")
/**запрос на обновление токена*/
val refreshCall = coreNetworkComponent
.getHttpClientApi()
.getFeatureApiImpl(IRefreshTokenRetrofitApi::class.java)
.refreshAuthToken(Token(token))
val refreshResponse: retrofit2.Response<ResponseData<TokenInfo>>?
refreshResponse = refreshCall.execute()
if (refreshResponse?.body()?.data != null && refreshResponse.body()!!.success) {
/**если токен успешно обновлен*/
AuthProvider.storeTokenInfoToCache(refreshResponse.body()!!.data!!)
/**повторный запрос начального(неудачного) запроса*/
return response.request()
.newBuilder()
.removeHeader("Authorization")
.addHeader("Authorization", AuthProvider.getAuthHeaderValue())
.build()
} else {
/**если обновление токена завершилось неудачей*/
AuthProvider.logoutAndNavigateToSplash()
return null
}
}
AuthProvider.logoutAndNavigateToSplash()
return null
}
}
}
class Network {
private val logging: HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
@Suppress("ConstantConditionIf")
/**LOGGING_ENABLED_BY_GRADLE зависит от типа сборки в "build.gradle" модуля */
level = if (LOGGING_ENABLED_BY_GRADLE && OKHTTP_LOGGING_ENABLED) {
/**подробность лога:*/
HttpLoggingInterceptor.Level.BODY //BODY - HEADERS - BASIC
} else {
HttpLoggingInterceptor.Level.NONE
}
}
private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.addInterceptor(logging)
.connectTimeout(10, TimeUnit.SECONDS)
.callTimeout(20, TimeUnit.SECONDS)
.addInterceptor { chain ->
val builder = chain.request().newBuilder()
// Добавляем тенант клиента
if (TenantProvider.tenant != "") builder.addHeader("tenant", TenantProvider.tenant)
if (AuthProvider.isAuthorized) builder.addHeader("Authorization", AuthProvider.getAuthHeaderValue())
val response = chain.proceed(builder.build())
response
}
.authenticator(AccessTokenAuthenticator())
.build()
fun providesRetrofit(): Retrofit {
return Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(CURRENT_BASE_URL)
.client(okHttpClient)
.build()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment