-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[#228] Add TokenAuthenticator to template-xml
- Loading branch information
1 parent
66b5f5d
commit 8a867f0
Showing
19 changed files
with
328 additions
and
21 deletions.
There are no files selected for viewing
7 changes: 7 additions & 0 deletions
7
template-xml/app/src/main/java/co/nimblehq/template/xml/di/Authenticate.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
package co.nimblehq.template.xml.di | ||
|
||
import javax.inject.Qualifier | ||
|
||
@Qualifier | ||
@Retention(AnnotationRetention.BINARY) | ||
annotation class Authenticate |
22 changes: 22 additions & 0 deletions
22
template-xml/app/src/main/java/co/nimblehq/template/xml/di/modules/AuthModule.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package co.nimblehq.template.xml.di.modules | ||
|
||
import co.nimblehq.template.xml.data.repository.SessionManagerImpl | ||
import co.nimblehq.template.xml.data.repository.TokenRefresherImpl | ||
import co.nimblehq.template.xml.data.service.AuthService | ||
import co.nimblehq.template.xml.data.service.SessionManager | ||
import co.nimblehq.template.xml.data.service.authenticator.TokenRefresher | ||
import dagger.Module | ||
import dagger.Provides | ||
import dagger.hilt.InstallIn | ||
import dagger.hilt.components.SingletonComponent | ||
|
||
@Module | ||
@InstallIn(SingletonComponent::class) | ||
class AuthModule { | ||
|
||
@Provides | ||
fun provideAuthService(authService: AuthService): TokenRefresher = TokenRefresherImpl(authService) | ||
|
||
@Provides | ||
fun provideSessionManager(): SessionManager = SessionManagerImpl() | ||
} |
This file contains 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
This file contains 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
This file contains 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
27 changes: 27 additions & 0 deletions
27
...ate-xml/data/src/main/java/co/nimblehq/template/xml/data/repository/SessionManagerImpl.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package co.nimblehq.template.xml.data.repository | ||
|
||
import co.nimblehq.template.xml.data.response.AuthenticateResponse | ||
import co.nimblehq.template.xml.data.service.SessionManager | ||
|
||
class SessionManagerImpl: SessionManager { | ||
|
||
override suspend fun getAccessToken(): String { | ||
TODO("Not yet implemented") | ||
} | ||
|
||
override suspend fun getRefreshToken(): String { | ||
TODO("Not yet implemented") | ||
} | ||
|
||
override suspend fun getRegistrationToken(): String { | ||
TODO("Not yet implemented") | ||
} | ||
|
||
override suspend fun getTokenType(): String { | ||
TODO("Not yet implemented") | ||
} | ||
|
||
override suspend fun refresh(authenticateResponse: AuthenticateResponse) { | ||
TODO("Not yet implemented") | ||
} | ||
} |
16 changes: 16 additions & 0 deletions
16
...ate-xml/data/src/main/java/co/nimblehq/template/xml/data/repository/TokenRefresherImpl.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package co.nimblehq.template.xml.data.repository | ||
|
||
import co.nimblehq.template.xml.data.extensions.flowTransform | ||
import co.nimblehq.template.xml.data.response.AuthenticateResponse | ||
import co.nimblehq.template.xml.data.service.AuthService | ||
import co.nimblehq.template.xml.data.service.authenticator.TokenRefresher | ||
import kotlinx.coroutines.flow.Flow | ||
|
||
class TokenRefresherImpl constructor( | ||
private val authService: AuthService | ||
) : TokenRefresher { | ||
|
||
override suspend fun refreshToken(): Flow<AuthenticateResponse> = flowTransform { | ||
authService.refreshToken() | ||
} | ||
} |
22 changes: 22 additions & 0 deletions
22
...ate-xml/data/src/main/java/co/nimblehq/template/xml/data/response/AuthenticateResponse.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
package co.nimblehq.template.xml.data.response | ||
|
||
import co.nimblehq.template.xml.domain.model.AuthStatus | ||
import com.squareup.moshi.Json | ||
|
||
data class AuthenticateResponse( | ||
@Json(name = "access_token") | ||
val accessToken: String, | ||
@Json(name = "refresh_token") | ||
val refreshToken: String, | ||
@Json(name = "status") | ||
val status: String, | ||
@Json(name = "token_type") | ||
val tokenType: String? | ||
) | ||
|
||
fun AuthenticateResponse.toAuthenticated() = AuthStatus.Authenticated( | ||
accessToken = accessToken, | ||
refreshToken = refreshToken, | ||
status = status, | ||
tokenType = tokenType | ||
) |
This file contains 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
This file contains 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
10 changes: 10 additions & 0 deletions
10
template-xml/data/src/main/java/co/nimblehq/template/xml/data/service/AuthService.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package co.nimblehq.template.xml.data.service | ||
|
||
import co.nimblehq.template.xml.data.response.AuthenticateResponse | ||
import retrofit2.http.POST | ||
|
||
interface AuthService { | ||
|
||
@POST("refreshToken") | ||
suspend fun refreshToken(): AuthenticateResponse | ||
} |
16 changes: 16 additions & 0 deletions
16
template-xml/data/src/main/java/co/nimblehq/template/xml/data/service/SessionManager.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package co.nimblehq.template.xml.data.service | ||
|
||
import co.nimblehq.template.xml.data.response.AuthenticateResponse | ||
|
||
interface SessionManager { | ||
|
||
suspend fun getAccessToken(): String | ||
|
||
suspend fun getRefreshToken(): String | ||
|
||
suspend fun getRegistrationToken(): String | ||
|
||
suspend fun getTokenType(): String | ||
|
||
suspend fun refresh(authenticateResponse: AuthenticateResponse) | ||
} |
97 changes: 97 additions & 0 deletions
97
...va/co/nimblehq/template/xml/data/service/authenticator/ApplicationRequestAuthenticator.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
package co.nimblehq.template.xml.data.service.authenticator | ||
|
||
import android.annotation.SuppressLint | ||
import android.util.Log | ||
import co.nimblehq.template.xml.data.extensions.parseErrorResponse | ||
import co.nimblehq.template.xml.data.service.SessionManager | ||
import co.nimblehq.template.xml.domain.exceptions.NoConnectivityException | ||
import kotlinx.coroutines.* | ||
import kotlinx.coroutines.flow.last | ||
import okhttp3.* | ||
|
||
const val REQUEST_HEADER_AUTHORIZATION = "Authorization" | ||
|
||
class ApplicationRequestAuthenticator( | ||
private val tokenRefresher: TokenRefresher, | ||
private val sessionManager: SessionManager | ||
) : Authenticator { | ||
|
||
lateinit var okHttpClient: OkHttpClient | ||
|
||
private var retryCount = 0 | ||
|
||
@SuppressLint("CheckResult", "LongMethod", "TooGenericExceptionCaught") | ||
override fun authenticate(route: Route?, response: Response): Request? = | ||
runBlocking { | ||
if (shouldSkipAuthenticationByErrorType(response)) { | ||
return@runBlocking null | ||
} | ||
|
||
// Due to unable to check the last retry succeeded | ||
// So reset the retry count on the request first triggered by an automatic retry | ||
if (response.priorResponse == null && retryCount != 0) { | ||
retryCount = 0 | ||
} | ||
|
||
if (retryCount >= MAX_ATTEMPTS) { | ||
// Reset retry count once reached max attempts | ||
retryCount = 0 | ||
return@runBlocking null | ||
} else { | ||
retryCount++ | ||
|
||
val tokenType = sessionManager.getTokenType() | ||
val failedAccessToken = sessionManager.getAccessToken() | ||
|
||
try { | ||
val refreshTokenResponse = tokenRefresher.refreshToken().last().copy( | ||
// refreshToken response doesn't send tokenType | ||
tokenType = tokenType | ||
) | ||
val newAccessToken = refreshTokenResponse.accessToken | ||
|
||
if (newAccessToken.isEmpty() || newAccessToken == failedAccessToken) { | ||
// Avoid infinite loop if the new Token == old (failed) token | ||
return@runBlocking null | ||
} | ||
|
||
// Update the Interceptor (for future requests) | ||
sessionManager.refresh(refreshTokenResponse) | ||
|
||
// Retry this failed request (401) with the new token | ||
return@runBlocking response.request | ||
.newBuilder() | ||
.header(REQUEST_HEADER_AUTHORIZATION, "$tokenType $newAccessToken") | ||
.build() | ||
} catch (e: Exception) { | ||
Log.w("AUTHENTICATOR", "Failed to refresh token: $e") | ||
return@runBlocking if (e !is NoConnectivityException) { | ||
// cancel all pending requests | ||
okHttpClient.dispatcher.cancelAll() | ||
response.request | ||
} else { | ||
// do nothing | ||
null | ||
} | ||
} | ||
} | ||
} | ||
|
||
private fun shouldSkipAuthenticationByErrorType(response: Response): Boolean { | ||
val headers = response.request.headers | ||
val skippingError = headers[HEADER_AUTHENTICATION_SKIPPING_ERROR_TYPE] | ||
|
||
if (!skippingError.isNullOrEmpty()) { | ||
// Clone response body | ||
// https://github.com/square/okhttp/issues/1240#issuecomment-330813274 | ||
val responseBody = response.peekBody(Long.MAX_VALUE).toString() | ||
val error = parseErrorResponse(responseBody) | ||
|
||
return error != null && skippingError == error.type | ||
} | ||
return false | ||
} | ||
} | ||
|
||
const val HEADER_AUTHENTICATION_SKIPPING_ERROR_TYPE = "Authentication-Skipping-ErrorType" | ||
private const val MAX_ATTEMPTS = 3 |
9 changes: 9 additions & 0 deletions
9
.../data/src/main/java/co/nimblehq/template/xml/data/service/authenticator/TokenRefresher.kt
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
package co.nimblehq.template.xml.data.service.authenticator | ||
|
||
import co.nimblehq.template.xml.data.response.AuthenticateResponse | ||
import kotlinx.coroutines.flow.Flow | ||
|
||
interface TokenRefresher { | ||
|
||
suspend fun refreshToken(): Flow<AuthenticateResponse> | ||
} |
Oops, something went wrong.