Kotlin multiplatform auth (#4284)

* Includes support for the Javascript platform

* Fixes enum serialization with non-string values

* Updates to expose api dependencies to consumers

* Uses explicit class name for Kotlin collection classes

* Maps unknown object type to Kotlin String

The Kotlinx serialization library uses reflectionless serialization and
requires compile-time serialization declarations. As a result, unknown
objects are mapped to Kotlin String instances to enable compilation
where object types are not explicitly defined.

* Improves support for binary objects

Previously, objects that contained binary data were assigned the
InputProvider data type. This was suitable for a binary input form
parameter, but unsuitable for Base64 or octet binary strings. These
binary strings are now assigned a more suitable object.

* Includes Kotlin Multiplatform auth classes

Includes support for:
- api key
- http basic
- http bearer
- oauth (partial support)

https://github.com/OpenAPITools/openapi-generator/issues/4283

* Updates Kotlin samples
This commit is contained in:
Andrew Emery
2019-10-28 19:03:49 +11:00
committed by William Cheng
parent 0f2272d9a4
commit d92d84bb12
154 changed files with 1858 additions and 533 deletions

View File

@@ -30,6 +30,7 @@ kotlin {
jvm()
iosArm64() { binaries { framework { freeCompilerArgs.add("-Xobjc-generics") } } }
iosX64() { binaries { framework { freeCompilerArgs.add("-Xobjc-generics") } } }
js()
sourceSets {
commonMain {
@@ -37,9 +38,9 @@ kotlin {
implementation "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-common:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serialization_version"
implementation "io.ktor:ktor-client-core:$ktor_version"
implementation "io.ktor:ktor-client-json:$ktor_version"
implementation "io.ktor:ktor-client-serialization:$ktor_version"
api "io.ktor:ktor-client-core:$ktor_version"
api "io.ktor:ktor-client-json:$ktor_version"
api "io.ktor:ktor-client-serialization:$ktor_version"
}
}
@@ -57,9 +58,9 @@ kotlin {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:$serialization_version"
implementation "io.ktor:ktor-client-core-jvm:$ktor_version"
implementation "io.ktor:ktor-client-json-jvm:$ktor_version"
implementation "io.ktor:ktor-client-serialization-jvm:$ktor_version"
api "io.ktor:ktor-client-core-jvm:$ktor_version"
api "io.ktor:ktor-client-json-jvm:$ktor_version"
api "io.ktor:ktor-client-serialization-jvm:$ktor_version"
}
}
@@ -77,7 +78,7 @@ kotlin {
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-native:$serialization_version"
implementation "io.ktor:ktor-client-ios:$ktor_version"
api "io.ktor:ktor-client-ios:$ktor_version"
}
}
@@ -91,9 +92,9 @@ kotlin {
iosArm64().compilations.main.defaultSourceSet {
dependsOn iosMain
dependencies {
implementation "io.ktor:ktor-client-ios-iosarm64:$ktor_version"
implementation "io.ktor:ktor-client-json-iosarm64:$ktor_version"
implementation "io.ktor:ktor-client-serialization-iosarm64:$ktor_version"
api "io.ktor:ktor-client-ios-iosarm64:$ktor_version"
api "io.ktor:ktor-client-json-iosarm64:$ktor_version"
api "io.ktor:ktor-client-serialization-iosarm64:$ktor_version"
}
}
@@ -104,9 +105,31 @@ kotlin {
iosX64().compilations.main.defaultSourceSet {
dependsOn iosMain
dependencies {
implementation "io.ktor:ktor-client-ios-iosx64:$ktor_version"
implementation "io.ktor:ktor-client-json-iosx64:$ktor_version"
implementation "io.ktor:ktor-client-serialization-iosx64:$ktor_version"
api "io.ktor:ktor-client-ios-iosx64:$ktor_version"
api "io.ktor:ktor-client-json-iosx64:$ktor_version"
api "io.ktor:ktor-client-serialization-iosx64:$ktor_version"
}
}
jsMain {
dependsOn commonMain
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-js:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-js:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:$serialization_version"
api "io.ktor:ktor-client-js:$ktor_version"
api "io.ktor:ktor-client-json-js:$ktor_version"
api "io.ktor:ktor-client-serialization-js:$ktor_version"
}
}
jsTest {
dependsOn commonTest
dependencies {
implementation "io.ktor:ktor-client-mock-js:$ktor_version"
implementation "io.ktor:ktor-client-js:$ktor_version"
implementation "io.ktor:ktor-client-json:$ktor_version"
implementation "io.ktor:ktor-client-serialization-js:$ktor_version"
}
}

View File

@@ -46,6 +46,8 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor(
*/
suspend fun addPet(body: Pet) : HttpResponse<Unit> {
val localVariableAuthNames = listOf<String>("petstore_auth")
val localVariableBody = body
val localVariableQuery = mutableMapOf<String, List<String>>()
@@ -61,7 +63,8 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor(
return jsonRequest(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -76,6 +79,8 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor(
*/
suspend fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?) : HttpResponse<Unit> {
val localVariableAuthNames = listOf<String>("petstore_auth")
val localVariableBody =
io.ktor.client.utils.EmptyContent
@@ -93,7 +98,8 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor(
return request(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -107,6 +113,8 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor(
@Suppress("UNCHECKED_CAST")
suspend fun findPetsByStatus(status: kotlin.Array<kotlin.String>) : HttpResponse<kotlin.Array<Pet>> {
val localVariableAuthNames = listOf<String>("petstore_auth")
val localVariableBody =
io.ktor.client.utils.EmptyContent
@@ -124,7 +132,8 @@ class PetApi @UseExperimental(UnstableDefault::class) constructor(
return request(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap<FindPetsByStatusResponse>().map { value.toTypedArray() }
}
@@ -148,6 +157,8 @@ private class FindPetsByStatusResponse(val value: List<Pet>) {
@Suppress("UNCHECKED_CAST")
suspend fun findPetsByTags(tags: kotlin.Array<kotlin.String>) : HttpResponse<kotlin.Array<Pet>> {
val localVariableAuthNames = listOf<String>("petstore_auth")
val localVariableBody =
io.ktor.client.utils.EmptyContent
@@ -165,7 +176,8 @@ private class FindPetsByStatusResponse(val value: List<Pet>) {
return request(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap<FindPetsByTagsResponse>().map { value.toTypedArray() }
}
@@ -189,6 +201,8 @@ private class FindPetsByTagsResponse(val value: List<Pet>) {
@Suppress("UNCHECKED_CAST")
suspend fun getPetById(petId: kotlin.Long) : HttpResponse<Pet> {
val localVariableAuthNames = listOf<String>("api_key")
val localVariableBody =
io.ktor.client.utils.EmptyContent
@@ -205,7 +219,8 @@ private class FindPetsByTagsResponse(val value: List<Pet>) {
return request(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -218,6 +233,8 @@ private class FindPetsByTagsResponse(val value: List<Pet>) {
*/
suspend fun updatePet(body: Pet) : HttpResponse<Unit> {
val localVariableAuthNames = listOf<String>("petstore_auth")
val localVariableBody = body
val localVariableQuery = mutableMapOf<String, List<String>>()
@@ -233,7 +250,8 @@ private class FindPetsByTagsResponse(val value: List<Pet>) {
return jsonRequest(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -249,6 +267,8 @@ private class FindPetsByTagsResponse(val value: List<Pet>) {
*/
suspend fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : HttpResponse<Unit> {
val localVariableAuthNames = listOf<String>("petstore_auth")
val localVariableBody =
ParametersBuilder().also {
name?.apply { it.append("name", name.toString()) }
@@ -268,7 +288,8 @@ private class FindPetsByTagsResponse(val value: List<Pet>) {
return urlEncodedFormRequest(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -284,6 +305,8 @@ private class FindPetsByTagsResponse(val value: List<Pet>) {
@Suppress("UNCHECKED_CAST")
suspend fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: io.ktor.client.request.forms.InputProvider?) : HttpResponse<ApiResponse> {
val localVariableAuthNames = listOf<String>("petstore_auth")
val localVariableBody =
formData {
additionalMetadata?.apply { append("additionalMetadata", additionalMetadata) }
@@ -303,7 +326,8 @@ private class FindPetsByTagsResponse(val value: List<Pet>) {
return multipartFormRequest(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}

View File

@@ -45,6 +45,8 @@ class StoreApi @UseExperimental(UnstableDefault::class) constructor(
*/
suspend fun deleteOrder(orderId: kotlin.String) : HttpResponse<Unit> {
val localVariableAuthNames = listOf<String>()
val localVariableBody =
io.ktor.client.utils.EmptyContent
@@ -61,7 +63,8 @@ class StoreApi @UseExperimental(UnstableDefault::class) constructor(
return request(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -74,6 +77,8 @@ class StoreApi @UseExperimental(UnstableDefault::class) constructor(
@Suppress("UNCHECKED_CAST")
suspend fun getInventory() : HttpResponse<kotlin.collections.Map<kotlin.String, kotlin.Int>> {
val localVariableAuthNames = listOf<String>("api_key")
val localVariableBody =
io.ktor.client.utils.EmptyContent
@@ -90,7 +95,8 @@ class StoreApi @UseExperimental(UnstableDefault::class) constructor(
return request(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap<GetInventoryResponse>().map { value }
}
@@ -114,6 +120,8 @@ private class GetInventoryResponse(val value: Map<kotlin.String, kotlin.Int>) {
@Suppress("UNCHECKED_CAST")
suspend fun getOrderById(orderId: kotlin.Long) : HttpResponse<Order> {
val localVariableAuthNames = listOf<String>()
val localVariableBody =
io.ktor.client.utils.EmptyContent
@@ -130,7 +138,8 @@ private class GetInventoryResponse(val value: Map<kotlin.String, kotlin.Int>) {
return request(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -144,6 +153,8 @@ private class GetInventoryResponse(val value: Map<kotlin.String, kotlin.Int>) {
@Suppress("UNCHECKED_CAST")
suspend fun placeOrder(body: Order) : HttpResponse<Order> {
val localVariableAuthNames = listOf<String>()
val localVariableBody = body
val localVariableQuery = mutableMapOf<String, List<String>>()
@@ -159,7 +170,8 @@ private class GetInventoryResponse(val value: Map<kotlin.String, kotlin.Int>) {
return jsonRequest(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}

View File

@@ -45,6 +45,8 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor(
*/
suspend fun createUser(body: User) : HttpResponse<Unit> {
val localVariableAuthNames = listOf<String>()
val localVariableBody = body
val localVariableQuery = mutableMapOf<String, List<String>>()
@@ -60,7 +62,8 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor(
return jsonRequest(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -74,6 +77,8 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor(
*/
suspend fun createUsersWithArrayInput(body: kotlin.Array<User>) : HttpResponse<Unit> {
val localVariableAuthNames = listOf<String>()
val localVariableBody = CreateUsersWithArrayInputRequest(body.asList())
val localVariableQuery = mutableMapOf<String, List<String>>()
@@ -89,7 +94,8 @@ class UserApi @UseExperimental(UnstableDefault::class) constructor(
return jsonRequest(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -112,6 +118,8 @@ private class CreateUsersWithArrayInputRequest(val value: List<User>) {
*/
suspend fun createUsersWithListInput(body: kotlin.Array<User>) : HttpResponse<Unit> {
val localVariableAuthNames = listOf<String>()
val localVariableBody = CreateUsersWithListInputRequest(body.asList())
val localVariableQuery = mutableMapOf<String, List<String>>()
@@ -127,7 +135,8 @@ private class CreateUsersWithArrayInputRequest(val value: List<User>) {
return jsonRequest(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -150,6 +159,8 @@ private class CreateUsersWithListInputRequest(val value: List<User>) {
*/
suspend fun deleteUser(username: kotlin.String) : HttpResponse<Unit> {
val localVariableAuthNames = listOf<String>()
val localVariableBody =
io.ktor.client.utils.EmptyContent
@@ -166,7 +177,8 @@ private class CreateUsersWithListInputRequest(val value: List<User>) {
return request(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -180,6 +192,8 @@ private class CreateUsersWithListInputRequest(val value: List<User>) {
@Suppress("UNCHECKED_CAST")
suspend fun getUserByName(username: kotlin.String) : HttpResponse<User> {
val localVariableAuthNames = listOf<String>()
val localVariableBody =
io.ktor.client.utils.EmptyContent
@@ -196,7 +210,8 @@ private class CreateUsersWithListInputRequest(val value: List<User>) {
return request(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -211,6 +226,8 @@ private class CreateUsersWithListInputRequest(val value: List<User>) {
@Suppress("UNCHECKED_CAST")
suspend fun loginUser(username: kotlin.String, password: kotlin.String) : HttpResponse<kotlin.String> {
val localVariableAuthNames = listOf<String>()
val localVariableBody =
io.ktor.client.utils.EmptyContent
@@ -229,7 +246,8 @@ private class CreateUsersWithListInputRequest(val value: List<User>) {
return request(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -241,6 +259,8 @@ private class CreateUsersWithListInputRequest(val value: List<User>) {
*/
suspend fun logoutUser() : HttpResponse<Unit> {
val localVariableAuthNames = listOf<String>()
val localVariableBody =
io.ktor.client.utils.EmptyContent
@@ -257,7 +277,8 @@ private class CreateUsersWithListInputRequest(val value: List<User>) {
return request(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}
@@ -271,6 +292,8 @@ private class CreateUsersWithListInputRequest(val value: List<User>) {
*/
suspend fun updateUser(username: kotlin.String, body: User) : HttpResponse<Unit> {
val localVariableAuthNames = listOf<String>()
val localVariableBody = body
val localVariableQuery = mutableMapOf<String, List<String>>()
@@ -286,7 +309,8 @@ private class CreateUsersWithListInputRequest(val value: List<User>) {
return jsonRequest(
localVariableConfig,
localVariableBody
localVariableBody,
localVariableAuthNames
).wrap()
}

View File

@@ -0,0 +1,16 @@
package org.openapitools.client.auth
class ApiKeyAuth(private val location: String, val paramName: String) : Authentication {
var apiKey: String? = null
var apiKeyPrefix: String? = null
override fun apply(query: MutableMap<String, List<String>>, headers: MutableMap<String, String>) {
val key: String = apiKey ?: return
val prefix: String? = apiKeyPrefix
val value: String = if (prefix != null) "$prefix $key" else key
when (location) {
"query" -> query[paramName] = listOf(value)
"header" -> headers[paramName] = value
}
}
}

View File

@@ -0,0 +1,13 @@
package org.openapitools.client.auth
interface Authentication {
/**
* Apply authentication settings to header and query params.
*
* @param query Query parameters.
* @param headers Header parameters.
*/
fun apply(query: MutableMap<String, List<String>>, headers: MutableMap<String, String>)
}

View File

@@ -0,0 +1,17 @@
package org.openapitools.client.auth
import io.ktor.util.InternalAPI
import io.ktor.util.encodeBase64
class HttpBasicAuth : Authentication {
var username: String? = null
var password: String? = null
@InternalAPI
override fun apply(query: MutableMap<String, List<String>>, headers: MutableMap<String, String>) {
if (username == null && password == null) return
val str = (username ?: "") + ":" + (password ?: "")
val auth = str.encodeBase64()
headers["Authorization"] = "Basic $auth"
}
}

View File

@@ -0,0 +1,14 @@
package org.openapitools.client.auth
class HttpBearerAuth(private val scheme: String?) : Authentication {
var bearerToken: String? = null
override fun apply(query: MutableMap<String, List<String>>, headers: MutableMap<String, String>) {
val token: String = bearerToken ?: return
headers["Authorization"] = (if (scheme != null) upperCaseBearer(scheme)!! + " " else "") + token
}
private fun upperCaseBearer(scheme: String): String? {
return if ("bearer".equals(scheme, ignoreCase = true)) "Bearer" else scheme
}
}

View File

@@ -0,0 +1,10 @@
package org.openapitools.client.auth
class OAuth : Authentication {
var accessToken: String? = null
override fun apply(query: MutableMap<String, List<String>>, headers: MutableMap<String, String>) {
val token: String = accessToken ?: return
headers["Authorization"] = "Bearer $token"
}
}

View File

@@ -1,6 +1,6 @@
package org.openapitools.client.infrastructure
typealias MultiValueMap = Map<String,List<String>>
typealias MultiValueMap = MutableMap<String,List<String>>
fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) {
"csv" -> ","

View File

@@ -23,6 +23,7 @@ import kotlinx.serialization.json.JsonConfiguration
import org.openapitools.client.apis.*
import org.openapitools.client.models.*
import org.openapitools.client.auth.*
open class ApiClient(
private val baseUrl: String,
@@ -46,6 +47,12 @@ open class ApiClient(
httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig)
}
private val authentications: kotlin.collections.Map<String, Authentication> by lazy {
mapOf(
"api_key" to ApiKeyAuth("header", "api_key"),
"petstore_auth" to OAuth())
}
companion object {
protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType)
@@ -57,31 +64,100 @@ open class ApiClient(
UserApi.setMappers(serializer)
serializer.setMapper(ApiResponse::class, ApiResponse.serializer())
serializer.setMapper(Category::class, Category.serializer())
serializer.setMapper(Order::class, Order.serializer())
serializer.setMapper(Pet::class, Pet.serializer())
serializer.setMapper(Tag::class, Tag.serializer())
serializer.setMapper(User::class, User.serializer())
serializer.setMapper(org.openapitools.client.models.ApiResponse::class, org.openapitools.client.models.ApiResponse.serializer())
serializer.setMapper(org.openapitools.client.models.Category::class, org.openapitools.client.models.Category.serializer())
serializer.setMapper(org.openapitools.client.models.Order::class, org.openapitools.client.models.Order.serializer())
serializer.setMapper(org.openapitools.client.models.Pet::class, org.openapitools.client.models.Pet.serializer())
serializer.setMapper(org.openapitools.client.models.Tag::class, org.openapitools.client.models.Tag.serializer())
serializer.setMapper(org.openapitools.client.models.User::class, org.openapitools.client.models.User.serializer())
}
}
protected suspend fun multipartFormRequest(requestConfig: RequestConfig, body: List<PartData>?): HttpResponse {
return request(requestConfig, MultiPartFormDataContent(body ?: listOf()))
/**
* Set the username for the first HTTP basic authentication.
*
* @param username Username
*/
fun setUsername(username: String) {
val auth = authentications.values.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth?
?: throw Exception("No HTTP basic authentication configured")
auth.username = username
}
protected suspend fun urlEncodedFormRequest(requestConfig: RequestConfig, body: Parameters?): HttpResponse {
return request(requestConfig, FormDataContent(body ?: Parameters.Empty))
/**
* Set the password for the first HTTP basic authentication.
*
* @param password Password
*/
fun setPassword(password: String) {
val auth = authentications.values.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth?
?: throw Exception("No HTTP basic authentication configured")
auth.password = password
}
protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null): HttpResponse {
/**
* Set the API key value for the first API key authentication.
*
* @param apiKey API key
* @param paramName The name of the API key parameter, or null or set the first key.
*/
fun setApiKey(apiKey: String, paramName: String? = null) {
val auth = authentications.values.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth?
?: throw Exception("No API key authentication configured")
auth.apiKey = apiKey
}
/**
* Set the API key prefix for the first API key authentication.
*
* @param apiKeyPrefix API key prefix
* @param paramName The name of the API key parameter, or null or set the first key.
*/
fun setApiKeyPrefix(apiKeyPrefix: String, paramName: String? = null) {
val auth = authentications.values.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth?
?: throw Exception("No API key authentication configured")
auth.apiKeyPrefix = apiKeyPrefix
}
/**
* Set the access token for the first OAuth2 authentication.
*
* @param accessToken Access token
*/
fun setAccessToken(accessToken: String) {
val auth = authentications.values.firstOrNull { it is OAuth } as OAuth?
?: throw Exception("No OAuth2 authentication configured")
auth.accessToken = accessToken
}
/**
* Set the access token for the first Bearer authentication.
*
* @param bearerToken The bearer token.
*/
fun setBearerToken(bearerToken: String) {
val auth = authentications.values.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth?
?: throw Exception("No Bearer authentication configured")
auth.bearerToken = bearerToken
}
protected suspend fun multipartFormRequest(requestConfig: RequestConfig, body: kotlin.collections.List<PartData>?, authNames: kotlin.collections.List<String>): HttpResponse {
return request(requestConfig, MultiPartFormDataContent(body ?: listOf()), authNames)
}
protected suspend fun urlEncodedFormRequest(requestConfig: RequestConfig, body: Parameters?, authNames: kotlin.collections.List<String>): HttpResponse {
return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames)
}
protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List<String>): HttpResponse {
val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) }
?: ContentType.Application.Json)
return if (body != null) request(requestConfig, serializer.write(body, contentType))
else request(requestConfig)
return if (body != null) request(requestConfig, serializer.write(body, contentType), authNames)
else request(requestConfig, authNames = authNames)
}
protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent): HttpResponse {
protected suspend fun request(requestConfig: RequestConfig, body: OutgoingContent = EmptyContent, authNames: kotlin.collections.List<String>): HttpResponse {
requestConfig.updateForAuth(authNames)
val headers = requestConfig.headers
return client.call {
@@ -102,7 +178,14 @@ open class ApiClient(
}.response
}
private fun URLBuilder.appendPath(components: List<String>): URLBuilder = apply {
private fun RequestConfig.updateForAuth(authNames: kotlin.collections.List<String>) {
for (authName in authNames) {
val auth = authentications[authName] ?: throw Exception("Authentication undefined: $authName")
auth.apply(query, headers)
}
}
private fun URLBuilder.appendPath(components: kotlin.collections.List<String>): URLBuilder = apply {
encodedPath = encodedPath.trimEnd('/') + components.joinToString("/", prefix = "/") { it.encodeURLQueryComponent() }
}

View File

@@ -0,0 +1,29 @@
package org.openapitools.client.infrastructure
import kotlinx.serialization.*
import kotlinx.serialization.internal.StringDescriptor
@Serializable
class Base64ByteArray(val value: ByteArray) {
@Serializer(Base64ByteArray::class)
companion object : KSerializer<Base64ByteArray> {
override val descriptor = StringDescriptor.withName("Base64ByteArray")
override fun serialize(encoder: Encoder, obj: Base64ByteArray) = encoder.encodeString(obj.value.encodeBase64())
override fun deserialize(decoder: Decoder) = Base64ByteArray(decoder.decodeString().decodeBase64Bytes())
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as Base64ByteArray
return value.contentEquals(other.value)
}
override fun hashCode(): Int {
return value.contentHashCode()
}
override fun toString(): String {
return "Base64ByteArray(${hex(value)})"
}
}

View File

@@ -0,0 +1,102 @@
package org.openapitools.client.infrastructure
import kotlinx.io.core.*
import kotlin.experimental.and
private val digits = "0123456789abcdef".toCharArray()
private const val BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
private const val BASE64_MASK: Byte = 0x3f
private const val BASE64_PAD = '='
private val BASE64_INVERSE_ALPHABET = IntArray(256) { BASE64_ALPHABET.indexOf(it.toChar()) }
private fun String.toCharArray(): CharArray = CharArray(length) { get(it) }
private fun ByteArray.clearFrom(from: Int) = (from until size).forEach { this[it] = 0 }
private fun Int.toBase64(): Char = BASE64_ALPHABET[this]
private fun Byte.fromBase64(): Byte = BASE64_INVERSE_ALPHABET[toInt() and 0xff].toByte() and BASE64_MASK
internal fun ByteArray.encodeBase64(): String = buildPacket { writeFully(this@encodeBase64) }.encodeBase64()
internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { writeStringUtf8(dropLastWhile { it == BASE64_PAD }) }.decodeBase64Bytes().readBytes()
/**
* Encode [bytes] as a HEX string with no spaces, newlines and `0x` prefixes.
*
* Taken from https://github.com/ktorio/ktor/blob/master/ktor-utils/common/src/io/ktor/util/Crypto.kt
*/
internal fun hex(bytes: ByteArray): String {
val result = CharArray(bytes.size * 2)
var resultIndex = 0
val digits = digits
for (element in bytes) {
val b = element.toInt() and 0xff
result[resultIndex++] = digits[b shr 4]
result[resultIndex++] = digits[b and 0x0f]
}
return String(result)
}
/**
* Decode bytes from HEX string. It should be no spaces and `0x` prefixes.
*
* Taken from https://github.com/ktorio/ktor/blob/master/ktor-utils/common/src/io/ktor/util/Crypto.kt
*/
internal fun hex(s: String): ByteArray {
val result = ByteArray(s.length / 2)
for (idx in result.indices) {
val srcIdx = idx * 2
val high = s[srcIdx].toString().toInt(16) shl 4
val low = s[srcIdx + 1].toString().toInt(16)
result[idx] = (high or low).toByte()
}
return result
}
/**
* Encode [ByteReadPacket] in base64 format.
*
* Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt
*/
private fun ByteReadPacket.encodeBase64(): String = buildString {
val data = ByteArray(3)
while (remaining > 0) {
val read = readAvailable(data)
data.clearFrom(read)
val padSize = (data.size - read) * 8 / 6
val chunk = ((data[0].toInt() and 0xFF) shl 16) or
((data[1].toInt() and 0xFF) shl 8) or
(data[2].toInt() and 0xFF)
for (index in data.size downTo padSize) {
val char = (chunk shr (6 * index)) and BASE64_MASK.toInt()
append(char.toBase64())
}
repeat(padSize) { append(BASE64_PAD) }
}
}
/**
* Decode [ByteReadPacket] from base64 format
*
* Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt
*/
private fun ByteReadPacket.decodeBase64Bytes(): Input = buildPacket {
val data = ByteArray(4)
while (remaining > 0) {
val read = readAvailable(data)
val chunk = data.foldIndexed(0) { index, result, current ->
result or (current.fromBase64().toInt() shl ((3 - index) * 6))
}
for (index in data.size - 2 downTo (data.size - read)) {
val origin = (chunk shr (8 * index)) and 0xff
writeByte(origin.toByte())
}
}
}

View File

@@ -0,0 +1,29 @@
package org.openapitools.client.infrastructure
import kotlinx.serialization.*
import kotlinx.serialization.internal.StringDescriptor
@Serializable
class OctetByteArray(val value: ByteArray) {
@Serializer(OctetByteArray::class)
companion object : KSerializer<OctetByteArray> {
override val descriptor = StringDescriptor.withName("OctetByteArray")
override fun serialize(encoder: Encoder, obj: OctetByteArray) = encoder.encodeString(hex(obj.value))
override fun deserialize(decoder: Decoder) = OctetByteArray(hex(decoder.decodeString()))
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as OctetByteArray
return value.contentEquals(other.value)
}
override fun hashCode(): Int {
return value.contentHashCode()
}
override fun toString(): String {
return "OctetByteArray(${hex(value)})"
}
}

View File

@@ -12,5 +12,5 @@ data class RequestConfig(
val method: RequestMethod,
val path: String,
val headers: MutableMap<String, String> = mutableMapOf(),
val query: Map<String, List<String>> = mapOf()
val query: MutableMap<String, List<String>> = mutableMapOf()
)

View File

@@ -46,7 +46,7 @@ data class Order (
approved("approved"),
delivered("delivered");
object Serializer : CommonEnumSerializer<Status>("Status", values(), values().map { it.value }.toTypedArray())
object Serializer : CommonEnumSerializer<Status>("Status", values(), values().map { it.value.toString() }.toTypedArray())
}
}

View File

@@ -48,7 +48,7 @@ data class Pet (
pending("pending"),
sold("sold");
object Serializer : CommonEnumSerializer<Status>("Status", values(), values().map { it.value }.toTypedArray())
object Serializer : CommonEnumSerializer<Status>("Status", values(), values().map { it.value.toString() }.toTypedArray())
}
}

View File

@@ -0,0 +1,7 @@
package util
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.promise
actual fun <T> runTest(block: suspend (scope : CoroutineScope) -> T): dynamic = GlobalScope.promise { block(this) }