-
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 c79ef76
Showing
17 changed files
with
305 additions
and
14 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
19 changes: 19 additions & 0 deletions
19
...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,19 @@ | ||
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 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
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 | ||
} |
12 changes: 12 additions & 0 deletions
12
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,12 @@ | ||
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 refresh(authenticateResponse: AuthenticateResponse) | ||
} |
93 changes: 93 additions & 0 deletions
93
...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,93 @@ | ||
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 failedAccessToken = sessionManager.getAccessToken() | ||
|
||
try { | ||
val refreshTokenResponse = tokenRefresher.refreshToken().last() | ||
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, 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> | ||
} |
5 changes: 5 additions & 0 deletions
5
.../data/src/main/java/co/nimblehq/template/xml/data/service/providers/ApiServiceProvider.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 |
---|---|---|
@@ -1,11 +1,16 @@ | ||
package co.nimblehq.template.xml.data.service.providers | ||
|
||
import co.nimblehq.template.xml.data.service.ApiService | ||
import co.nimblehq.template.xml.data.service.AuthService | ||
import retrofit2.Retrofit | ||
|
||
object ApiServiceProvider { | ||
|
||
fun getApiService(retrofit: Retrofit): ApiService { | ||
return retrofit.create(ApiService::class.java) | ||
} | ||
|
||
fun getAuthService(retrofit: Retrofit): AuthService { | ||
return retrofit.create(AuthService::class.java) | ||
} | ||
} |
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 |
---|---|---|
|
@@ -27,6 +27,7 @@ object MockUtil { | |
} | ||
|
||
val errorResponse = ErrorResponse( | ||
message = "message" | ||
message = "message", | ||
type = null | ||
) | ||
} |
11 changes: 11 additions & 0 deletions
11
template-xml/domain/src/main/java/co/nimblehq/template/xml/domain/model/AuthStatus.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,11 @@ | ||
package co.nimblehq.template.xml.domain.model | ||
|
||
sealed class AuthStatus { | ||
|
||
data class Authenticated( | ||
val accessToken: String, | ||
val refreshToken: String, | ||
val status: String, | ||
val tokenType: String? | ||
) | ||
} |
3 changes: 2 additions & 1 deletion
3
template-xml/domain/src/main/java/co/nimblehq/template/xml/domain/model/Error.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 |
---|---|---|
@@ -1,5 +1,6 @@ | ||
package co.nimblehq.template.xml.domain.model | ||
|
||
data class Error( | ||
val message: String | ||
val message: String, | ||
val type: String? | ||
) |