Skip to content

Instantly share code, notes, and snippets.

@prokash-sarkar
Last active January 27, 2021 09:18
Show Gist options
  • Save prokash-sarkar/c926ca3fd3129b564884f107ae906d89 to your computer and use it in GitHub Desktop.
Save prokash-sarkar/c926ca3fd3129b564884f107ae906d89 to your computer and use it in GitHub Desktop.
Example of runtime modification of an auth token and base URL of the okHttp client using Interceptor and Dagger injection.
class AuthenticationInterceptor @Inject constructor(baseUrl: String, jwtToken: String) :
Interceptor {
private var baseUrl: HttpUrl
private var jwtToken: String
companion object {
private const val LOG_TAG = "AuthenticationInterceptor:"
private const val AUTHORIZATION = "Authorization"
private const val BEARER = "Bearer"
}
init {
this.baseUrl = baseUrl.toHttpUrlOrNull() ?: HttpUrl.Builder().scheme("https")
//.host()
//.port()
.build()
this.jwtToken = jwtToken
}
fun setBaseUrlAndJwtToken(baseUrl: String, jwtToken: String) {
baseUrl.toHttpUrlOrNull()?.let {
this.baseUrl = it
this.jwtToken = jwtToken
Timber.d(
"$LOG_TAG New base url -> scheme: %s | host: %s | port: %d",
this.baseUrl.scheme,
this.baseUrl.host,
this.baseUrl.port
)
}
}
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val url = originalRequest.url.newBuilder()
.scheme(baseUrl.scheme)
.host(baseUrl.host)
.port(baseUrl.port)
.build()
val request = originalRequest.newBuilder()
.url(url)
.header(AUTHORIZATION, "$BEARER $jwtToken")
.build()
return chain.proceed(request)
}
}
package com.example.dagger.ui.login
import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.dagger.R
import com.example.dagger.data.string.StringProvider
import com.example.dagger.databinding.ActivityLoginBinding
import com.example.dagger.network.AuthenticationInterceptor
import dagger.android.support.DaggerAppCompatActivity
import javax.inject.Inject
class DynamicAuthTokenActivity : DaggerAppCompatActivity() {
@Inject
lateinit var authenticationInterceptor: AuthenticationInterceptor
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
authenticationInterceptor.setBaseUrlAndJwtToken("https://api.github.com/", "")
}
}
@Module
class NetworkModule {
@Singleton
@Provides
@BaseUrlQualifier
fun provideBaseUrl(): String {
return "http://prokashsarkar.com"
}
@Singleton
@Provides
fun provideOkHttpCache(context: Context): Cache {
val cacheSize: Long = 10 * 1024 * 1024 // 10 MB
return Cache(context.cacheDir, cacheSize)
}
@Singleton
@Provides
fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor {
return HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)
}
@Singleton
@Provides
fun providesAuthenticationInterceptor(@BaseUrlQualifier baseUrl: String): AuthenticationInterceptor {
return AuthenticationInterceptor(baseUrl, "")
}
@Singleton
@Provides
fun provideOkHttpClient(
cache: Cache,
loggingInterceptor: HttpLoggingInterceptor,
authInterceptor: AuthenticationInterceptor
): OkHttpClient {
return OkHttpClient.Builder()
.cache(cache)
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(40, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
.addInterceptor(authInterceptor)
.build()
}
@Singleton
@Provides
fun provideGson(): Gson {
val gson = GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create()
return gson
}
@Singleton
@Provides
fun provideMoshi(): Moshi {
val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
return moshi
}
@Singleton
@Provides
fun provideRetrofit(
@BaseUrlQualifier baseUrl: String,
gson: Gson,
moshi: Moshi,
okHttpClient: OkHttpClient,
): Retrofit {
return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(baseUrl)
.client(okHttpClient)
.build()
}
@Singleton
@Provides
fun provideApiClient(retrofit: Retrofit): ApiService = retrofit.create(ApiService::class.java)
}
class RemoteDataSource @Inject constructor(
private val apiService: ApiService,
private val authenticationInterceptor: AuthenticationInterceptor
) : DataSource {
private val IN_QUALIFIER = "in:name,description"
override suspend fun getSearchResponse(
query: String,
page: Int,
itemsPerPage: Int
): RepoSearchResponse {
authenticationInterceptor.setBaseUrlAndJwtToken("https://api.github.com/", "")
return apiService.searchRepos(
"$query $IN_QUALIFIER",
page,
itemsPerPage
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment