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(
private val key: String,
private val name: String,
private val location: ApiKeyLocation,
) : Authenticator {
override fun authenticate(builder: Request.Builder) {
when (location) {
ApiKeyLocation.HEADER -> builder.header(name, key)
ApiKeyLocation.QUERY -> {
val url = builder.build().url.newBuilder()
.addQueryParameter(name, key)
.build()
builder.url(url)
}
}
}
}
enum class ApiKeyLocation {
HEADER,
QUERY,
}