Support invalidation in MealieAuthenticator

This commit is contained in:
Kirill Kamakin
2022-12-11 10:17:13 +01:00
parent ac20105b9b
commit 9c48f1b563
3 changed files with 40 additions and 6 deletions

View File

@@ -4,4 +4,5 @@ interface AuthenticationProvider {
suspend fun getAuthHeader(): String?
suspend fun invalidateAuthHeader()
}

View File

@@ -18,16 +18,26 @@ class MealieAuthenticator @Inject constructor(
override fun authenticate(route: Route?, response: Response): Request? {
val supportsBearer = response.challenges().any { it.scheme == BEARER_SCHEME }
if (!supportsBearer) {
return null
}
val request = response.request
return if (supportsBearer && request.header(HEADER_NAME) == null) {
getAuthHeader()?.let { request.copyWithHeader(HEADER_NAME, it) }
} else {
null // Either Bearer is not supported or we've already tried to authenticate
val previousHeader = request.header(HEADER_NAME)
?: return getAuthHeader()?.let { request.copyWithHeader(HEADER_NAME, it) }
invalidateAuthHeader()
return getAuthHeader()?.takeUnless { it == previousHeader }?.let {
request.copyWithHeader(HEADER_NAME, it)
}
}
private fun getAuthHeader() = runBlocking { authenticationProvider.get().getAuthHeader() }
private fun invalidateAuthHeader() {
runBlocking { authenticationProvider.get().invalidateAuthHeader() }
}
companion object {
@VisibleForTesting
const val HEADER_NAME = "Authorization"