openapi-nexus 0.2.0

OpenAPI 3.x multi-language code generator
Documentation
package runtime

import okhttp3.Request

interface Authenticator {
    fun authenticate(builder: Request.Builder)
}

class BearerAuth : Authenticator {
    private val token: String?
    private val tokenProvider: (() -> String)?

    constructor(token: String) {
        this.token = token
        this.tokenProvider = null
    }

    constructor(tokenProvider: () -> String) {
        this.token = null
        this.tokenProvider = tokenProvider
    }

    override fun authenticate(builder: Request.Builder) {
        val t = tokenProvider?.invoke() ?: token!!
        builder.header("Authorization", "Bearer $t")
    }
}

class ApiKeyAuth : Authenticator {
    private val key: String?
    private val keyProvider: (() -> String)?
    private val name: String
    private val location: ApiKeyLocation

    constructor(key: String, name: String, location: ApiKeyLocation) {
        this.key = key
        this.keyProvider = null
        this.name = name
        this.location = location
    }

    constructor(keyProvider: () -> String, name: String, location: ApiKeyLocation) {
        this.key = null
        this.keyProvider = keyProvider
        this.name = name
        this.location = location
    }

    override fun authenticate(builder: Request.Builder) {
        val k = keyProvider?.invoke() ?: key!!
        when (location) {
            ApiKeyLocation.HEADER -> builder.header(name, k)
            ApiKeyLocation.QUERY -> {
                val url = builder.build().url.newBuilder()
                    .addQueryParameter(name, k)
                    .build()
                builder.url(url)
            }
        }
    }
}

enum class ApiKeyLocation {
    HEADER,
    QUERY,
}