Created
May 28, 2020 08:56
-
-
Save trunghq3101/4636f31b3c302e7019e624e9f41204bd to your computer and use it in GitHub Desktop.
Refresh token interceptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class AuthenticateInterceptor( | |
| private val dataStorage: DataStorage, | |
| private val authService: AuthService | |
| ) : Interceptor { | |
| | |
| override fun intercept(chain: Chain): Response { | |
| val newRequest = buildAuthorizedRequest(chain) | |
| val response = chain.proceed(newRequest) | |
| | |
| return if (response.code == CODE_TOKEN_EXPIRED) { | |
| isRefreshingToken = true | |
| synchronized(this) { | |
| if (isRefreshingToken) { | |
| isRefreshingToken = false | |
| refreshToken() | |
| } | |
| chain.proceed(buildAuthorizedRequest(chain)) | |
| } | |
| } else { | |
| response | |
| } | |
| | |
| // proceed request | |
| // if (expired) { | |
| // lock { | |
| // if (expired) { | |
| // request new token | |
| // save token | |
| // } | |
| // proceed request | |
| // } | |
| // } else { | |
| // response | |
| // } | |
| } | |
| | |
| private fun refreshToken() { | |
| val refreshToken = dataStorage.get(KEY_REFRESH_TOKEN, String::class).orEmpty() | |
| runBlocking { | |
| withContext(Dispatchers.IO) { | |
| authService.refreshToken(refreshToken) | |
| }.let { | |
| dataStorage.set(KEY_TOKEN, it.accessToken) | |
| dataStorage.set(KEY_REFRESH_TOKEN, it.refreshToken) | |
| } | |
| } | |
| } | |
| | |
| private fun buildAuthorizedRequest(chain: Chain): Request { | |
| return chain.request() | |
| .newBuilder() | |
| .apply { | |
| dataStorage.get(KEY_TOKEN, String::class)?.let { | |
| addHeader("Authorization", it) | |
| } | |
| } | |
| .build() | |
| } | |
| } | |
| | |
| var isRefreshingToken = false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment