|
| 1 | +package co.nimblehq.template.xml.data.service.authenticator |
| 2 | + |
| 3 | +import android.annotation.SuppressLint |
| 4 | +import android.util.Log |
| 5 | +import co.nimblehq.template.xml.data.extensions.parseErrorResponse |
| 6 | +import co.nimblehq.template.xml.data.service.SessionManager |
| 7 | +import co.nimblehq.template.xml.domain.exceptions.NoConnectivityException |
| 8 | +import kotlinx.coroutines.* |
| 9 | +import kotlinx.coroutines.flow.last |
| 10 | +import okhttp3.* |
| 11 | + |
| 12 | +const val REQUEST_HEADER_AUTHORIZATION = "Authorization" |
| 13 | + |
| 14 | +class ApplicationRequestAuthenticator( |
| 15 | + private val tokenRefresher: TokenRefresher, |
| 16 | + private val sessionManager: SessionManager |
| 17 | +) : Authenticator { |
| 18 | + |
| 19 | + lateinit var okHttpClient: OkHttpClient |
| 20 | + |
| 21 | + private var retryCount = 0 |
| 22 | + |
| 23 | + @SuppressLint("CheckResult", "LongMethod", "TooGenericExceptionCaught") |
| 24 | + override fun authenticate(route: Route?, response: Response): Request? = |
| 25 | + runBlocking { |
| 26 | + if (shouldSkipAuthenticationByErrorType(response)) { |
| 27 | + return@runBlocking null |
| 28 | + } |
| 29 | + |
| 30 | + // Due to unable to check the last retry succeeded |
| 31 | + // So reset the retry count on the request first triggered by an automatic retry |
| 32 | + if (response.priorResponse == null && retryCount != 0) { |
| 33 | + retryCount = 0 |
| 34 | + } |
| 35 | + |
| 36 | + if (retryCount >= MAX_ATTEMPTS) { |
| 37 | + // Reset retry count once reached max attempts |
| 38 | + retryCount = 0 |
| 39 | + return@runBlocking null |
| 40 | + } else { |
| 41 | + retryCount++ |
| 42 | + |
| 43 | + val tokenType = sessionManager.getTokenType() |
| 44 | + val failedAccessToken = sessionManager.getAccessToken() |
| 45 | + |
| 46 | + try { |
| 47 | + val refreshTokenResponse = tokenRefresher.refreshToken().last().copy( |
| 48 | + // refreshToken response doesn't send tokenType |
| 49 | + tokenType = tokenType |
| 50 | + ) |
| 51 | + val newAccessToken = refreshTokenResponse.accessToken |
| 52 | + |
| 53 | + if (newAccessToken.isEmpty() || newAccessToken == failedAccessToken) { |
| 54 | + // Avoid infinite loop if the new Token == old (failed) token |
| 55 | + return@runBlocking null |
| 56 | + } |
| 57 | + |
| 58 | + // Update the Interceptor (for future requests) |
| 59 | + sessionManager.refresh(refreshTokenResponse) |
| 60 | + |
| 61 | + // Retry this failed request (401) with the new token |
| 62 | + return@runBlocking response.request |
| 63 | + .newBuilder() |
| 64 | + .header(REQUEST_HEADER_AUTHORIZATION, "$tokenType $newAccessToken") |
| 65 | + .build() |
| 66 | + } catch (e: Exception) { |
| 67 | + Log.w("AUTHENTICATOR", "Failed to refresh token: $e") |
| 68 | + return@runBlocking if (e !is NoConnectivityException) { |
| 69 | + // cancel all pending requests |
| 70 | + okHttpClient.dispatcher.cancelAll() |
| 71 | + response.request |
| 72 | + } else { |
| 73 | + // do nothing |
| 74 | + null |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + private fun shouldSkipAuthenticationByErrorType(response: Response): Boolean { |
| 81 | + val headers = response.request.headers |
| 82 | + val skippingError = headers[HEADER_AUTHENTICATION_SKIPPING_ERROR_TYPE] |
| 83 | + |
| 84 | + if (!skippingError.isNullOrEmpty()) { |
| 85 | + // Clone response body |
| 86 | + // https://github.com/square/okhttp/issues/1240#issuecomment-330813274 |
| 87 | + val responseBody = response.peekBody(Long.MAX_VALUE).toString() |
| 88 | + val error = parseErrorResponse(responseBody) |
| 89 | + |
| 90 | + return error != null && skippingError == error.type |
| 91 | + } |
| 92 | + return false |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +const val HEADER_AUTHENTICATION_SKIPPING_ERROR_TYPE = "Authentication-Skipping-ErrorType" |
| 97 | +private const val MAX_ATTEMPTS = 3 |
0 commit comments