Add AccessTokenInterceptor and LoggingInterceptor

This commit is contained in:
ganfra 2018-10-03 18:16:11 +02:00
parent b406e8301a
commit d69b2ba930
3 changed files with 40 additions and 1 deletions

View file

@ -13,6 +13,7 @@ dependencies {
implementation 'com.squareup.retrofit2:converter-moshi:2.4.0'
implementation 'com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
implementation 'com.squareup.okio:okio:1.15.0'
implementation 'com.squareup.moshi:moshi-kotlin:1.7.0'
kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.7.0'

View file

@ -0,0 +1,22 @@
package im.vector.matrix.core.internal.network
import im.vector.matrix.core.api.login.CredentialsStore
import okhttp3.Interceptor
import okhttp3.Response
class AccessTokenInterceptor(private val credentialsStore: CredentialsStore) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
val newRequestBuilder = request.newBuilder()
// Add the access token to all requests if it is set
val credentials = credentialsStore.getAll().firstOrNull()
credentials?.let {
newRequestBuilder.addHeader("Authorization", "Bearer " + it.accessToken)
}
request = newRequestBuilder.build()
return chain.proceed(request)
}
}

View file

@ -4,6 +4,7 @@ import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterF
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.dsl.context.ModuleDefinition
import org.koin.dsl.module.Module
import org.koin.dsl.module.module
@ -15,7 +16,20 @@ class NetworkModule() : Module {
override fun invoke(): ModuleDefinition = module {
single { OkHttpClient.Builder().build() }
single {
AccessTokenInterceptor(get())
}
single {
HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }
}
single {
OkHttpClient.Builder()
.addInterceptor(get() as AccessTokenInterceptor)
.addInterceptor(get() as HttpLoggingInterceptor)
.build()
}
single { Moshi.Builder().add(KotlinJsonAdapterFactory()).build() }
@ -26,5 +40,7 @@ class NetworkModule() : Module {
single {
CoroutineCallAdapterFactory() as CallAdapter.Factory
}
}.invoke()
}