Skip to content

Instantly share code, notes, and snippets.

@viroth-ty
Last active January 24, 2022 15:23
Show Gist options
  • Save viroth-ty/0f2478fbae4d1d10c8b4e0208c500962 to your computer and use it in GitHub Desktop.
Save viroth-ty/0f2478fbae4d1d10c8b4e0208c500962 to your computer and use it in GitHub Desktop.
Refresh token
package com.cg.pandago.vender.data.http
import com.cg.pandago.vender.BuildConfig
import com.cg.pandago.vender.PandaGoVendorApp
import com.cg.pandago.vender.data.local.SharedPreferenceHelper
import com.cg.pandago.vender.model.Authorize
import com.cg.pandago.vender.util.Constant
import com.google.gson.Gson
import com.google.gson.JsonObject
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.internal.synchronized
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import org.json.JSONObject
class AuthInterceptor : Interceptor {
@InternalCoroutinesApi
override fun intercept(chain: Interceptor.Chain): Response {
var request: Request = chain.request()
val builder: Request.Builder = request.newBuilder()
builder
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/x-www-form-urlencoded")
val accessToken: String = SharedPreferenceHelper.getInstance(PandaGoVendorApp.appContext).getAccessToken()
val privateToken : String = SharedPreferenceHelper.getInstance(PandaGoVendorApp.appContext).getPrivateAccessToken()
builder.header("Authorize", accessToken)
builder.header("Auth", privateToken)
request = builder.build()
val response = chain.proceed(request)
if (response.code == 401) {
response.close()
synchronized(this) {
val currentToken: String = SharedPreferenceHelper.getInstance(PandaGoVendorApp.appContext).getAccessToken()
if (currentToken == accessToken) {
builder.header("Authorize", refreshToken())
request = builder.build()
return chain.proceed(request)
}
}
}
return response
}
private fun refreshToken(): String {
val jsonObject = JsonObject()
jsonObject.addProperty(Constant.Device.DEVICE_OS, Constant.Device.ANDROID)
jsonObject.addProperty(Constant.Device.DEVICE_NAME, android.os.Build.MODEL)
val mediaType = "application/json; charset=utf-8".toMediaType()
val body: RequestBody = RequestBody.create(mediaType, jsonObject.toString())
val client: OkHttpClient = OkHttpClient.Builder().build()
val request: Request = Request.Builder()
.url(BuildConfig.BASE_URL + "authorize")
.post(body = body)
.build()
val response = client.newCall(request).execute()
return if(response.code == 200) {
val json = JSONObject(response.body!!.string())
val data = Gson().fromJson(json["data"].toString(), Authorize::class.java)
data.token.toString()
} else {
""
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment