Skip to content

Commit

Permalink
feat: Adding user-agent header to http requests (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
dhudec authored Dec 16, 2022
1 parent 050ac70 commit 9ee9593
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
2 changes: 2 additions & 0 deletions lib/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ android {
targetSdk 32
versionName = '0.11.0'

buildConfigField 'String', 'VERSION_NAME', "\"${defaultConfig.versionName}\""

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package com.basistheory.android.service
import com.basistheory.ApiClient
import com.basistheory.Configuration
import com.basistheory.TokenizeApi
import com.basistheory.android.BuildConfig
import com.basistheory.auth.ApiKeyAuth

internal class ApiClientProvider(
Expand All @@ -20,6 +21,9 @@ internal class ApiClientProvider(
return Configuration.getDefaultApiClient().also { client ->
client.basePath = apiUrl

val userAgent = "basistheory-android/${BuildConfig.VERSION_NAME} ${System.getProperty("http.agent") ?: ""}".trim()
client.setUserAgent(userAgent)

(client.getAuthentication("ApiKey") as ApiKeyAuth).also { auth ->
auth.apiKey = apiKey
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
package com.basistheory.android.service

import com.basistheory.android.BuildConfig
import com.basistheory.auth.ApiKeyAuth
import com.github.javafaker.Faker
import org.junit.Test
import strikt.api.expectCatching
import strikt.api.expectThat
import strikt.assertions.isA
import strikt.assertions.isEqualTo
import strikt.assertions.isFailure
import strikt.assertions.*
import java.util.UUID

class ApiClientProviderTests {
Expand Down Expand Up @@ -56,4 +55,29 @@ class ApiClientProviderTests {
}
}
}

@Test
fun `getApiClient configures client with user-agent header`() {
val apiUrl = Faker().internet().url()
val defaultApiKey = UUID.randomUUID().toString()
val apiKeyOverride = UUID.randomUUID().toString()

val provider = ApiClientProvider(apiUrl, defaultApiKey)

val client = provider.getTokenizeApi(apiKeyOverride)

// the java openapi generator doesn't publicly expose default headers
// using reflection as a workaround
val defaultHeadersField = client.apiClient::class.java
.getDeclaredField("defaultHeaderMap")
.apply { isAccessible = true }

@Suppress("UNCHECKED_CAST")
val defaultHeaders: Map<String, String>? =
defaultHeadersField.get(client.apiClient) as? Map<String, String>

val defaultUserAgent = defaultHeaders?.get("User-Agent")
expectThat(defaultUserAgent).isNotNull()
.startsWith("basistheory-android/${BuildConfig.VERSION_NAME}")
}
}

0 comments on commit 9ee9593

Please sign in to comment.