From c6dfeda1620cce6ec0f9a7e13479591b90360ec4 Mon Sep 17 00:00:00 2001 From: Niko Diamadis Date: Tue, 18 Jun 2024 21:09:39 +0200 Subject: [PATCH] Add basic auth support for images via URL --- .../kotlin/com/github/gotify/CoilInstance.kt | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/app/src/main/kotlin/com/github/gotify/CoilInstance.kt b/app/src/main/kotlin/com/github/gotify/CoilInstance.kt index 611e6fb..4f89600 100644 --- a/app/src/main/kotlin/com/github/gotify/CoilInstance.kt +++ b/app/src/main/kotlin/com/github/gotify/CoilInstance.kt @@ -13,7 +13,12 @@ import coil.request.ImageRequest import com.github.gotify.api.CertUtils import com.github.gotify.client.model.Application import java.io.IOException +import okhttp3.Authenticator +import okhttp3.Credentials import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import okhttp3.Route import org.tinylog.kotlin.Logger object CoilInstance { @@ -69,7 +74,9 @@ object CoilInstance { context: Context, sslSettings: SSLSettings ): Pair { - val builder = OkHttpClient.Builder() + val builder = OkHttpClient + .Builder() + .authenticator(BasicAuthAuthenticator()) CertUtils.applySslSettings(builder, sslSettings) val loader = ImageLoader.Builder(context) .okHttpClient(builder.build()) @@ -85,3 +92,22 @@ object CoilInstance { return sslSettings to loader } } + +private class BasicAuthAuthenticator : Authenticator { + override fun authenticate(route: Route?, response: Response): Request? { + // If there's no username, skip the authenticator + if (response.request.url.username.isEmpty()) return null + + val basicAuthString = "${response.request.url.username}:${response.request.url.password}@" + val url = response.request.url.toString().replace(basicAuthString, "") + return response + .request + .newBuilder() + .header( + "Authorization", + Credentials.basic(response.request.url.username, response.request.url.password) + ) + .url(url) + .build() + } +}