Skip to content

Instantly share code, notes, and snippets.

@anhoang241998
Last active March 3, 2022 05:09
Show Gist options
  • Save anhoang241998/7683274bd55350070a8a7aa3ef6cac1e to your computer and use it in GitHub Desktop.
Save anhoang241998/7683274bd55350070a8a7aa3ef6cac1e to your computer and use it in GitHub Desktop.
Generate a new token by log in again.
import com.greenvity.llp.newapp.api.auth.AuthRetrofitInstance
import com.greenvity.llp.newapp.models.auth.login.LoginRequest
import com.greenvity.llp.newapp.utils.shared_pref.AppPreferences
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.net.HttpURLConnection.*
class RequestInterceptor : Interceptor {
private val mutex = Mutex()
private var token: String = ""
private var userName: String = ""
private var password: String = ""
override fun intercept(chain: Interceptor.Chain): Response {
AppPreferences.apply {
token = tokenSharedPref ?: ""
userName = userNameSharedPref ?: ""
password = passwordSharedPref ?: ""
}
val req = chain.request()
val res = chain.proceedWithToken(req, token)
if ((res.code != HTTP_UNAUTHORIZED && res.code != HTTP_BAD_REQUEST) || token.isEmpty()) {
return res
}
res.close()
val newToken: String? = runBlocking {
mutex.withLock {
getNewToken(userName, password)
}
}
return if (newToken != null) chain.proceedWithToken(req, newToken) else res
}
private fun Interceptor.Chain.proceedWithToken(req: Request, token: String): Response =
req.newBuilder()
.apply {
if (token.isNotEmpty()) {
addHeader("Authorization", "Bearer $token")
}
}
.build()
.let(::proceed)
private suspend fun getNewToken(userName: String, password: String): String? {
if (userName.isEmpty() || password.isEmpty()) return null
// * Handle your Log in here to get a new token
val refreshTokenRes =
AuthRetrofitInstance.apiAuthentication.loginAccount(LoginRequest(userName, password))
return if (refreshTokenRes.code() == HTTP_OK) {
refreshTokenRes.body()?.token.also {
AppPreferences.tokenSharedPref = it
}
} else {
null
}
}
}
import com.greenvity.llp.newapp.api.interceptor.RequestInterceptor
import com.greenvity.llp.newapp.api.osLavieDevices.OsLavieDevicesApi
import com.greenvity.llp.newcloud.constants.URLsNewCloud.CLOUD_URL_NEWCLOUD
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitInstance {
private val client = OkHttpClient.Builder().apply {
val interceptor = RequestInterceptor()
val logging = HttpLoggingInterceptor().apply {
setLevel(HttpLoggingInterceptor.Level.BODY)
}
addInterceptor(logging)
addInterceptor(interceptor)
}.build()
private val retrofit by lazy {
Retrofit.Builder()
.baseUrl(CLOUD_URL_NEWCLOUD)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val apiForUserSettingsProfile: UserSettingsProfileApi by lazy {
retrofit.create(UserSettingsProfileApi::class.java)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment