diff --git a/docs/generators/kotlin-server.md b/docs/generators/kotlin-server.md index 24bcf36d81d2..07d1410f481d 100644 --- a/docs/generators/kotlin-server.md +++ b/docs/generators/kotlin-server.md @@ -28,8 +28,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl |featureCompression|Adds ability to compress outgoing content using gzip, deflate or custom encoder and thus reduce size of the response.| |true| |featureConditionalHeaders|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |false| |featureHSTS|Avoid sending content if client already has same content, by checking ETag or LastModified properties.| |true| -|featureLocations|Generates routes in a typed way, for both: constructing URLs and reading the parameters.| |true| |featureMetrics|Enables metrics feature.| |true| +|featureResources|Generates routes in a typed way, for both: constructing URLs and reading the parameters.| |true| |groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| |interfaceOnly|Whether to generate only API interface stubs without the server files. This option is currently supported only when using jaxrs-spec library.| |false| |library|library template (sub-template)|
**ktor**
ktor framework
**jaxrs-spec**
JAX-RS spec only
|ktor| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java index ffaef1dc137f..261fedc12c99 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java @@ -47,7 +47,7 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen implements BeanVa private Boolean hstsFeatureEnabled = true; private Boolean corsFeatureEnabled = false; private Boolean compressionFeatureEnabled = true; - private Boolean locationsFeatureEnabled = true; + private Boolean resourcesFeatureEnabled = true; private Boolean metricsFeatureEnabled = true; private boolean interfaceOnly = false; private boolean useBeanValidation = false; @@ -62,7 +62,7 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen implements BeanVa Constants.HSTS, Constants.CORS, Constants.COMPRESSION, - Constants.LOCATIONS, + Constants.RESOURCES, Constants.METRICS )) .build(); @@ -126,7 +126,7 @@ public KotlinServerCodegen() { addSwitch(Constants.HSTS, Constants.HSTS_DESC, getHstsFeatureEnabled()); addSwitch(Constants.CORS, Constants.CORS_DESC, getCorsFeatureEnabled()); addSwitch(Constants.COMPRESSION, Constants.COMPRESSION_DESC, getCompressionFeatureEnabled()); - addSwitch(Constants.LOCATIONS, Constants.LOCATIONS_DESC, getLocationsFeatureEnabled()); + addSwitch(Constants.RESOURCES, Constants.RESOURCES_DESC, getResourcesFeatureEnabled()); addSwitch(Constants.METRICS, Constants.METRICS_DESC, getMetricsFeatureEnabled()); cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files. This option is currently supported only when using jaxrs-spec library.").defaultValue(String.valueOf(interfaceOnly))); @@ -179,12 +179,12 @@ public void setHstsFeatureEnabled(Boolean hstsFeatureEnabled) { this.hstsFeatureEnabled = hstsFeatureEnabled; } - public Boolean getLocationsFeatureEnabled() { - return locationsFeatureEnabled; + public Boolean getResourcesFeatureEnabled() { + return resourcesFeatureEnabled; } - public void setLocationsFeatureEnabled(Boolean locationsFeatureEnabled) { - this.locationsFeatureEnabled = locationsFeatureEnabled; + public void setResourcesFeatureEnabled(Boolean resourcesFeatureEnabled) { + this.resourcesFeatureEnabled = resourcesFeatureEnabled; } public Boolean getMetricsFeatureEnabled() { @@ -279,10 +279,10 @@ public void processOpts() { additionalProperties.put(Constants.COMPRESSION, getCompressionFeatureEnabled()); } - if (additionalProperties.containsKey(Constants.LOCATIONS)) { - setLocationsFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.LOCATIONS)); + if (additionalProperties.containsKey(Constants.RESOURCES)) { + setResourcesFeatureEnabled(convertPropertyToBooleanAndWriteBack(Constants.RESOURCES)); } else { - additionalProperties.put(Constants.LOCATIONS, getLocationsFeatureEnabled()); + additionalProperties.put(Constants.RESOURCES, getResourcesFeatureEnabled()); } if (additionalProperties.containsKey(Constants.METRICS)) { @@ -308,7 +308,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("AppMain.kt.mustache", packageFolder, "AppMain.kt")); supportingFiles.add(new SupportingFile("Configuration.kt.mustache", packageFolder, "Configuration.kt")); - if (generateApis && locationsFeatureEnabled) { + if (generateApis && resourcesFeatureEnabled) { supportingFiles.add(new SupportingFile("Paths.kt.mustache", packageFolder, "Paths.kt")); } @@ -339,8 +339,8 @@ public static class Constants { public final static String CORS_DESC = "Ktor by default provides an interceptor for implementing proper support for Cross-Origin Resource Sharing (CORS). See enable-cors.org."; public final static String COMPRESSION = "featureCompression"; public final static String COMPRESSION_DESC = "Adds ability to compress outgoing content using gzip, deflate or custom encoder and thus reduce size of the response."; - public final static String LOCATIONS = "featureLocations"; - public final static String LOCATIONS_DESC = "Generates routes in a typed way, for both: constructing URLs and reading the parameters."; + public final static String RESOURCES = "featureResources"; + public final static String RESOURCES_DESC = "Generates routes in a typed way, for both: constructing URLs and reading the parameters."; public final static String METRICS = "featureMetrics"; public final static String METRICS_DESC = "Enables metrics feature."; } diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/ApiKeyAuth.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/ApiKeyAuth.kt.mustache index a0abbcddfd04..c2cad7fe7a7f 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/ApiKeyAuth.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/ApiKeyAuth.kt.mustache @@ -1,10 +1,10 @@ -package {{packageName}}.infrastructure +package org.openapitools.server.infrastructure -import io.ktor.application.* -import io.ktor.auth.* import io.ktor.http.auth.* -import io.ktor.request.* -import io.ktor.response.* +import io.ktor.server.application.* +import io.ktor.server.auth.* +import io.ktor.server.request.* +import io.ktor.server.response.* enum class ApiKeyLocation(val location: String) { QUERY("query"), @@ -15,8 +15,7 @@ data class ApiKeyCredential(val value: String) : Credential data class ApiPrincipal(val apiKeyCredential: ApiKeyCredential?) : Principal /** -* Represents a Api Key authentication provider -* @param name is the name of the provider, or `null` for a default provider +* Represents an Api Key authentication provider */ class ApiKeyAuthenticationProvider(configuration: Configuration) : AuthenticationProvider(configuration) { @@ -26,39 +25,38 @@ class ApiKeyAuthenticationProvider(configuration: Configuration) : Authenticatio private val apiKeyLocation: ApiKeyLocation = configuration.apiKeyLocation - internal fun install() { - pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> - val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) - val principal = credentials?.let { authenticationFunction(call, it) } + override suspend fun onAuthenticate(context: AuthenticationContext) { + val call = context.call + val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) + val principal = credentials?.let { authenticationFunction.invoke(call, it) } - val cause = when { - credentials == null -> AuthenticationFailedCause.NoCredentials - principal == null -> AuthenticationFailedCause.InvalidCredentials - else -> null - } + val cause = when { + credentials == null -> AuthenticationFailedCause.NoCredentials + principal == null -> AuthenticationFailedCause.InvalidCredentials + else -> null + } - if (cause != null) { - context.challenge(apiKeyName, cause) { - call.respond( - UnauthorizedResponse( - HttpAuthHeader.Parameterized( - "API_KEY", - mapOf("key" to apiKeyName), - HeaderValueEncoding.QUOTED_ALWAYS - ) + if (cause != null) { + context.challenge(apiKeyName, cause) { challenge, call -> + call.respond( + UnauthorizedResponse( + HttpAuthHeader.Parameterized( + "API_KEY", + mapOf("key" to apiKeyName), + HeaderValueEncoding.QUOTED_ALWAYS ) ) - it.complete() - } + ) + challenge.complete() } + } - if (principal != null) { - context.principal(principal) - } + if (principal != null) { + context.principal(principal) } } - class Configuration internal constructor(name: String?) : AuthenticationProvider.Configuration(name) { + class Configuration internal constructor(name: String?) : Config(name) { internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { throw NotImplementedError( @@ -80,13 +78,12 @@ class ApiKeyAuthenticationProvider(configuration: Configuration) : Authenticatio } } -fun Authentication.Configuration.apiKeyAuth( +fun AuthenticationConfig.apiKeyAuth( name: String? = null, configure: ApiKeyAuthenticationProvider.Configuration.() -> Unit ) { val configuration = ApiKeyAuthenticationProvider.Configuration(name).apply(configure) val provider = ApiKeyAuthenticationProvider(configuration) - provider.install() register(provider) } diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache index 1dc57ad3b381..cd541791456e 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/AppMain.kt.mustache @@ -1,27 +1,40 @@ package {{packageName}} -{{#featureMetrics}} -import com.codahale.metrics.Slf4jReporter -{{/featureMetrics}} -import io.ktor.application.* -import io.ktor.features.* -import io.ktor.gson.* +import io.ktor.server.application.* +import io.ktor.serialization.gson.* import io.ktor.http.* -{{#featureLocations}} -import io.ktor.locations.* -{{/featureLocations}} +{{#featureResources}} +import io.ktor.server.resources.* +{{/featureResources}} +{{#featureCORS}} +import io.ktor.server.plugins.cors.routing.* +{{/featureCORS}} +{{#featureAutoHead}} +import io.ktor.server.plugins.autohead.* +{{/featureAutoHead}} +{{#featureConditionalHeaders}} +import io.ktor.server.plugins.conditionalheaders.* +{{/featureConditionalHeaders}} +{{#featureCompression}} +import io.ktor.server.plugins.compression.* +{{/featureCompression}} +import io.ktor.server.plugins.contentnegotiation.* +import io.ktor.server.plugins.defaultheaders.* +{{#featureHSTS}} +import io.ktor.server.plugins.hsts.* +{{/featureHSTS}} {{#featureMetrics}} -import io.ktor.metrics.dropwizard.* +import com.codahale.metrics.Slf4jReporter +import io.ktor.server.metrics.dropwizard.* import java.util.concurrent.TimeUnit {{/featureMetrics}} -import io.ktor.routing.* -import io.ktor.util.* +import io.ktor.server.routing.* {{#hasAuthMethods}} import com.typesafe.config.ConfigFactory -import io.ktor.auth.* import io.ktor.client.HttpClient import io.ktor.client.engine.apache.Apache -import io.ktor.config.HoconApplicationConfig +import io.ktor.server.config.HoconApplicationConfig +import io.ktor.server.auth.* import org.openapitools.server.infrastructure.* {{/hasAuthMethods}} {{#generateApis}}{{#apiInfo}}{{#apis}}import {{apiPackage}}.{{classname}} @@ -35,16 +48,12 @@ object HTTP { } {{/hasAuthMethods}} -@KtorExperimentalAPI -{{#featureLocations}} -@KtorExperimentalLocationsAPI -{{/featureLocations}} fun Application.main() { install(DefaultHeaders) {{#featureMetrics}} install(DropwizardMetrics) { val reporter = Slf4jReporter.forRegistry(registry) - .outputTo(log) + .outputTo(this@main.log) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build() @@ -70,9 +79,9 @@ fun Application.main() { {{#featureHSTS}} install(HSTS, ApplicationHstsConfiguration()) // see https://ktor.io/docs/hsts.html {{/featureHSTS}} - {{#featureLocations}} - install(Locations) // see https://ktor.io/docs/features-locations.html - {{/featureLocations}} + {{#featureResources}} + install(Resources) + {{/featureResources}} {{#hasAuthMethods}} install(Authentication) { {{#authMethods}} @@ -105,7 +114,7 @@ fun Application.main() { {{^bodyAllowed}} oauth("{{name}}") { client = HttpClient(Apache) - providerLookup = { ApplicationAuthProviders["{{{name}}}"] } + providerLookup = { applicationAuthProvider(this@main.environment.config) } urlProvider = { _ -> // TODO: define a callback url here. "/" diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache index 76a07ce208fa..0c81bee193ef 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Configuration.kt.mustache @@ -1,23 +1,33 @@ package {{packageName}} // Use this file to hold package-level internal functions that return receiver object passed to the `install` method. -import io.ktor.auth.* -import io.ktor.features.* import io.ktor.http.* +import io.ktor.server.auth.* +import io.ktor.server.config.* import io.ktor.util.* import java.time.Duration import java.util.concurrent.TimeUnit {{#featureCORS}} +import io.ktor.server.plugins.cors.routing.* +import io.ktor.server.plugins.cors.* +{{/featureCORS}} +{{#featureCompression}} +import io.ktor.server.plugins.compression.* +{{/featureCompression}} +{{#featureHSTS}} +import io.ktor.server.plugins.hsts.* +{{/featureHSTS}} +{{#featureCORS}} /** * Application block for [CORS] configuration. * * This file may be excluded in .openapi-generator-ignore, - * and application specific configuration can be applied in this function. + * and application-specific configuration can be applied in this function. * * See http://ktor.io/features/cors.html */ -internal fun ApplicationCORSConfiguration(): CORS.Configuration.() -> Unit { +internal fun ApplicationCORSConfiguration(): CORSConfig.() -> Unit { return { // method(HttpMethod.Options) // header(HttpHeaders.XForwardedProto) @@ -37,11 +47,11 @@ internal fun ApplicationCORSConfiguration(): CORS.Configuration.() -> Unit { * Application block for [HSTS] configuration. * * This file may be excluded in .openapi-generator-ignore, - * and application specific configuration can be applied in this function. + * and application-specific configuration can be applied in this function. * * See http://ktor.io/features/hsts.html */ -internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { +internal fun ApplicationHstsConfiguration(): HSTSConfig.() -> Unit { return { maxAgeInSeconds = TimeUnit.DAYS.toSeconds(365) includeSubDomains = true @@ -58,11 +68,11 @@ internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { * Application block for [Compression] configuration. * * This file may be excluded in .openapi-generator-ignore, - * and application specific configuration can be applied in this function. + * and application-specific configuration can be applied in this function. * * See http://ktor.io/features/compression.html */ -internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() -> Unit { +internal fun ApplicationCompressionConfiguration(): CompressionConfig.() -> Unit { return { gzip { priority = 1.0 @@ -76,29 +86,13 @@ internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() {{/featureCompression}} // Defines authentication mechanisms used throughout the application. -val ApplicationAuthProviders: Map = listOf( -{{#authMethods}} - {{#isOAuth}} - OAuthServerSettings.OAuth2ServerSettings( - name = "{{name}}", - authorizeUrl = "{{authorizationUrl}}", - accessTokenUrl = "{{tokenUrl}}", - requestMethod = HttpMethod.Get, - {{! TODO: flow, doesn't seem to be supported yet by ktor }} - clientId = settings.property("auth.oauth.{{name}}.clientId").getString(), - clientSecret = settings.property("auth.oauth.{{name}}.clientSecret").getString(), - defaultScopes = listOf({{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}}) - ){{^-last}},{{/-last}} - {{/isOAuth}} -{{/authMethods}} -// OAuthServerSettings.OAuth2ServerSettings( -// name = "facebook", -// authorizeUrl = "https://graph.facebook.com/oauth/authorize", -// accessTokenUrl = "https://graph.facebook.com/oauth/access_token", -// requestMethod = HttpMethod.Post, -// -// clientId = settings.property("auth.oauth.facebook.clientId").getString(), -// clientSecret = settings.property("auth.oauth.facebook.clientSecret").getString(), -// defaultScopes = listOf("public_profile") -// ) -).associateBy { it.name } +fun applicationAuthProvider(config: ApplicationConfig): OAuthServerSettings = + OAuthServerSettings.OAuth2ServerSettings( + name = "petstore_auth", + authorizeUrl = "http://petstore.swagger.io/api/oauth/dialog", + accessTokenUrl = "", + requestMethod = HttpMethod.Get, + clientId = config.property("auth.oauth.petstore_auth.clientId").getString(), + clientSecret = config.property("auth.oauth.petstore_auth.clientSecret").getString(), + defaultScopes = listOf("write:pets", "read:pets") + ) diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Paths.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Paths.kt.mustache index 78bad0f29893..487563c17755 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Paths.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/Paths.kt.mustache @@ -1,13 +1,13 @@ {{>licenseInfo}} package {{packageName}} -import io.ktor.locations.* +import io.ktor.resources.* +import kotlinx.serialization.* import {{packageName}}.models.* {{#imports}}import {{import}} {{/imports}} {{#apiInfo}} -@KtorExperimentalLocationsAPI object Paths { {{#apis}} {{#operations}} @@ -18,10 +18,10 @@ object Paths { {{#allParams}}* @param {{paramName}} {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} {{/allParams}}*/ {{#hasParams}} - @Location("{{path}}") class {{operationId}}({{#allParams}}val {{paramName}}: {{{dataType}}}{{^required}}? = null{{/required}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + @Serializable @Resource("{{path}}") class {{operationId}}({{#allParams}}val {{paramName}}: {{{dataType}}}{{^required}}? = null{{/required}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) {{/hasParams}} {{^hasParams}} - @Location("{{path}}") object {{operationId}} + @Serializable @Resource("{{path}}") class {{operationId}} {{/hasParams}} {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/README.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/README.mustache index b8c366686180..2e9f2f4c9889 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/README.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/README.mustache @@ -8,8 +8,8 @@ Generated by OpenAPI Generator {{generatorVersion}}{{^hideGenerationTimestamp}} ## Requires -* Kotlin 1.4.32 -* Gradle 6.9 +* Kotlin 1.7.20 +* Gradle 7.4.2 ## Build diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache index ba7eccdee567..eb1da3bd527d 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/api.mustache @@ -2,23 +2,26 @@ package {{apiPackage}} import com.google.gson.Gson -import io.ktor.application.* -import io.ktor.auth.* import io.ktor.http.* -import io.ktor.response.* -{{#featureLocations}} +import io.ktor.server.application.* +import io.ktor.server.auth.* +import io.ktor.server.response.* +{{#featureResources}} import {{packageName}}.Paths -import io.ktor.locations.* -{{/featureLocations}} -import io.ktor.routing.* +import io.ktor.server.resources.options +import io.ktor.server.resources.get +import io.ktor.server.resources.post +import io.ktor.server.resources.put +import io.ktor.server.resources.delete +import io.ktor.server.resources.head +import io.ktor.server.resources.patch +{{/featureResources}} +import io.ktor.server.routing.* import {{packageName}}.infrastructure.ApiPrincipal {{#imports}}import {{import}} {{/imports}} {{#operations}} -{{#featureLocations}} -@KtorExperimentalLocationsAPI -{{/featureLocations}} fun Route.{{classname}}() { val gson = Gson() val empty = mutableMapOf() @@ -29,18 +32,18 @@ fun Route.{{classname}}() { authenticate("{{{name}}}") { {{/authMethods}} {{/hasAuthMethods}} - {{^featureLocations}} + {{^featureResources}} route("{{path}}") { {{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}} { {{#lambda.indented_12}}{{>libraries/ktor/_api_body}}{{/lambda.indented_12}} } } - {{/featureLocations}} - {{#featureLocations}} + {{/featureResources}} + {{#featureResources}} {{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}} { {{#lambda.indented_8}}{{>libraries/ktor/_api_body}}{{/lambda.indented_8}} } - {{/featureLocations}} + {{/featureResources}} {{#hasAuthMethods}} } {{/hasAuthMethods}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache index 8d8948d689c5..a4547b0469ff 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-server/libraries/ktor/build.gradle.mustache @@ -2,13 +2,13 @@ group "{{groupId}}" version "{{artifactVersion}}" wrapper { - gradleVersion = "6.9" + gradleVersion = "7.4.2" distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = "1.4.32" - ext.ktor_version = "1.5.4" + ext.kotlin_version = "1.7.20" + ext.ktor_version = "2.2.1" ext.shadow_version = "6.1.0" repositories { @@ -55,21 +55,38 @@ repositories { dependencies { implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version") - implementation("ch.qos.logback:logback-classic:1.2.1") + implementation("ch.qos.logback:logback-classic:1.2.9") {{#hasAuthMethods}} implementation("com.typesafe:config:1.4.1") {{/hasAuthMethods}} - implementation("io.ktor:ktor-auth:$ktor_version") + implementation("io.ktor:ktor-server-auth:$ktor_version") {{#hasAuthMethods}} implementation("io.ktor:ktor-client-apache:$ktor_version") {{/hasAuthMethods}} - implementation("io.ktor:ktor-gson:$ktor_version") -{{#featureLocations}} - implementation("io.ktor:ktor-locations:$ktor_version") -{{/featureLocations}} +{{#featureAutoHead}} + implementation("io.ktor:ktor-server-auto-head-response:$ktor_version") +{{/featureAutoHead}} + implementation("io.ktor:ktor-server-default-headers:$ktor_version") + implementation("io.ktor:ktor-server-content-negotiation:$ktor_version") + implementation("io.ktor:ktor-serialization-gson:$ktor_version") +{{#featureResources}} + implementation("io.ktor:ktor-server-resources:$ktor_version") +{{/featureResources}} +{{#featureHSTS}} + implementation("io.ktor:ktor-server-hsts:$ktor_version") +{{/featureHSTS}} +{{#featureCORS}} + implementation("io.ktor:ktor-server-cors:$ktor_version") +{{/featureCORS}} +{{#featureConditionalHeaders}} + implementation("io.ktor:ktor-server-conditional-headers:$ktor_version") +{{/featureConditionalHeaders}} +{{#featureCompression}} + implementation("io.ktor:ktor-server-compression:$ktor_version") +{{/featureCompression}} {{#featureMetrics}} implementation("io.dropwizard.metrics:metrics-core:4.1.18") - implementation("io.ktor:ktor-metrics:$ktor_version") + implementation("io.ktor:ktor-server-metrics:$ktor_version") {{/featureMetrics}} implementation("io.ktor:ktor-server-netty:$ktor_version") diff --git a/samples/server/petstore/kotlin-server-modelMutable/README.md b/samples/server/petstore/kotlin-server-modelMutable/README.md index 1bcd7feac5a1..cb749cfddd5b 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/README.md +++ b/samples/server/petstore/kotlin-server-modelMutable/README.md @@ -6,8 +6,8 @@ Generated by OpenAPI Generator 7.0.0-SNAPSHOT. ## Requires -* Kotlin 1.4.32 -* Gradle 6.9 +* Kotlin 1.7.20 +* Gradle 7.4.2 ## Build diff --git a/samples/server/petstore/kotlin-server-modelMutable/build.gradle b/samples/server/petstore/kotlin-server-modelMutable/build.gradle index ebf0c9880680..bd883dc22910 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/build.gradle +++ b/samples/server/petstore/kotlin-server-modelMutable/build.gradle @@ -2,13 +2,13 @@ group "org.openapitools" version "1.0.0" wrapper { - gradleVersion = "6.9" + gradleVersion = "7.4.2" distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = "1.4.32" - ext.ktor_version = "1.5.4" + ext.kotlin_version = "1.7.20" + ext.ktor_version = "2.2.1" ext.shadow_version = "6.1.0" repositories { @@ -55,14 +55,19 @@ repositories { dependencies { implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version") - implementation("ch.qos.logback:logback-classic:1.2.1") + implementation("ch.qos.logback:logback-classic:1.2.9") implementation("com.typesafe:config:1.4.1") - implementation("io.ktor:ktor-auth:$ktor_version") + implementation("io.ktor:ktor-server-auth:$ktor_version") implementation("io.ktor:ktor-client-apache:$ktor_version") - implementation("io.ktor:ktor-gson:$ktor_version") - implementation("io.ktor:ktor-locations:$ktor_version") + implementation("io.ktor:ktor-server-auto-head-response:$ktor_version") + implementation("io.ktor:ktor-server-default-headers:$ktor_version") + implementation("io.ktor:ktor-server-content-negotiation:$ktor_version") + implementation("io.ktor:ktor-serialization-gson:$ktor_version") + implementation("io.ktor:ktor-server-resources:$ktor_version") + implementation("io.ktor:ktor-server-hsts:$ktor_version") + implementation("io.ktor:ktor-server-compression:$ktor_version") implementation("io.dropwizard.metrics:metrics-core:4.1.18") - implementation("io.ktor:ktor-metrics:$ktor_version") + implementation("io.ktor:ktor-server-metrics:$ktor_version") implementation("io.ktor:ktor-server-netty:$ktor_version") testImplementation("junit:junit:4.13.2") diff --git a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/AppMain.kt b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/AppMain.kt index 3244ed0ba8cd..2de9d58ce937 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/AppMain.kt +++ b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/AppMain.kt @@ -1,20 +1,23 @@ package org.openapitools.server -import com.codahale.metrics.Slf4jReporter -import io.ktor.application.* -import io.ktor.features.* -import io.ktor.gson.* +import io.ktor.server.application.* +import io.ktor.serialization.gson.* import io.ktor.http.* -import io.ktor.locations.* -import io.ktor.metrics.dropwizard.* +import io.ktor.server.resources.* +import io.ktor.server.plugins.autohead.* +import io.ktor.server.plugins.compression.* +import io.ktor.server.plugins.contentnegotiation.* +import io.ktor.server.plugins.defaultheaders.* +import io.ktor.server.plugins.hsts.* +import com.codahale.metrics.Slf4jReporter +import io.ktor.server.metrics.dropwizard.* import java.util.concurrent.TimeUnit -import io.ktor.routing.* -import io.ktor.util.* +import io.ktor.server.routing.* import com.typesafe.config.ConfigFactory -import io.ktor.auth.* import io.ktor.client.HttpClient import io.ktor.client.engine.apache.Apache -import io.ktor.config.HoconApplicationConfig +import io.ktor.server.config.HoconApplicationConfig +import io.ktor.server.auth.* import org.openapitools.server.infrastructure.* import org.openapitools.server.apis.PetApi import org.openapitools.server.apis.StoreApi @@ -27,13 +30,11 @@ object HTTP { val client = HttpClient(Apache) } -@KtorExperimentalAPI -@KtorExperimentalLocationsAPI fun Application.main() { install(DefaultHeaders) install(DropwizardMetrics) { val reporter = Slf4jReporter.forRegistry(registry) - .outputTo(log) + .outputTo(this@main.log) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build() @@ -45,11 +46,11 @@ fun Application.main() { install(AutoHeadResponse) // see https://ktor.io/docs/autoheadresponse.html install(Compression, ApplicationCompressionConfiguration()) // see https://ktor.io/docs/compression.html install(HSTS, ApplicationHstsConfiguration()) // see https://ktor.io/docs/hsts.html - install(Locations) // see https://ktor.io/docs/features-locations.html + install(Resources) install(Authentication) { oauth("petstore_auth") { client = HttpClient(Apache) - providerLookup = { ApplicationAuthProviders["petstore_auth"] } + providerLookup = { applicationAuthProvider(this@main.environment.config) } urlProvider = { _ -> // TODO: define a callback url here. "/" diff --git a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/Configuration.kt b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/Configuration.kt index 604eb33677be..f78654c60f0f 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/Configuration.kt +++ b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/Configuration.kt @@ -1,22 +1,25 @@ package org.openapitools.server // Use this file to hold package-level internal functions that return receiver object passed to the `install` method. -import io.ktor.auth.* -import io.ktor.features.* import io.ktor.http.* +import io.ktor.server.auth.* +import io.ktor.server.config.* import io.ktor.util.* import java.time.Duration import java.util.concurrent.TimeUnit +import io.ktor.server.plugins.compression.* +import io.ktor.server.plugins.hsts.* + /** * Application block for [HSTS] configuration. * * This file may be excluded in .openapi-generator-ignore, - * and application specific configuration can be applied in this function. + * and application-specific configuration can be applied in this function. * * See http://ktor.io/features/hsts.html */ -internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { +internal fun ApplicationHstsConfiguration(): HSTSConfig.() -> Unit { return { maxAgeInSeconds = TimeUnit.DAYS.toSeconds(365) includeSubDomains = true @@ -31,11 +34,11 @@ internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { * Application block for [Compression] configuration. * * This file may be excluded in .openapi-generator-ignore, - * and application specific configuration can be applied in this function. + * and application-specific configuration can be applied in this function. * * See http://ktor.io/features/compression.html */ -internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() -> Unit { +internal fun ApplicationCompressionConfiguration(): CompressionConfig.() -> Unit { return { gzip { priority = 1.0 @@ -48,24 +51,13 @@ internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() } // Defines authentication mechanisms used throughout the application. -val ApplicationAuthProviders: Map = listOf( - OAuthServerSettings.OAuth2ServerSettings( - name = "petstore_auth", - authorizeUrl = "http://petstore.swagger.io/api/oauth/dialog", - accessTokenUrl = "", - requestMethod = HttpMethod.Get, - clientId = settings.property("auth.oauth.petstore_auth.clientId").getString(), - clientSecret = settings.property("auth.oauth.petstore_auth.clientSecret").getString(), - defaultScopes = listOf("write:pets", "read:pets") - ), -// OAuthServerSettings.OAuth2ServerSettings( -// name = "facebook", -// authorizeUrl = "https://graph.facebook.com/oauth/authorize", -// accessTokenUrl = "https://graph.facebook.com/oauth/access_token", -// requestMethod = HttpMethod.Post, -// -// clientId = settings.property("auth.oauth.facebook.clientId").getString(), -// clientSecret = settings.property("auth.oauth.facebook.clientSecret").getString(), -// defaultScopes = listOf("public_profile") -// ) -).associateBy { it.name } +fun applicationAuthProvider(config: ApplicationConfig): OAuthServerSettings = + OAuthServerSettings.OAuth2ServerSettings( + name = "petstore_auth", + authorizeUrl = "http://petstore.swagger.io/api/oauth/dialog", + accessTokenUrl = "", + requestMethod = HttpMethod.Get, + clientId = config.property("auth.oauth.petstore_auth.clientId").getString(), + clientSecret = config.property("auth.oauth.petstore_auth.clientSecret").getString(), + defaultScopes = listOf("write:pets", "read:pets") + ) diff --git a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/Paths.kt b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/Paths.kt index 71bc64b1cc28..effea4faa7aa 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/Paths.kt +++ b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/Paths.kt @@ -11,17 +11,17 @@ */ package org.openapitools.server -import io.ktor.locations.* +import io.ktor.resources.* +import kotlinx.serialization.* import org.openapitools.server.models.* -@KtorExperimentalLocationsAPI object Paths { /** * Add a new pet to the store * * @param body Pet object that needs to be added to the store */ - @Location("/pet") class addPet(val body: Pet) + @Serializable @Resource("/pet") class addPet(val body: Pet) /** * Deletes a pet @@ -29,35 +29,35 @@ object Paths { * @param petId Pet id to delete * @param apiKey (optional) */ - @Location("/pet/{petId}") class deletePet(val petId: kotlin.Long, val apiKey: kotlin.String? = null) + @Serializable @Resource("/pet/{petId}") class deletePet(val petId: kotlin.Long, val apiKey: kotlin.String? = null) /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - @Location("/pet/findByStatus") class findPetsByStatus(val status: kotlin.collections.MutableList) + @Serializable @Resource("/pet/findByStatus") class findPetsByStatus(val status: kotlin.collections.MutableList) /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - @Location("/pet/findByTags") class findPetsByTags(val tags: kotlin.collections.MutableList) + @Serializable @Resource("/pet/findByTags") class findPetsByTags(val tags: kotlin.collections.MutableList) /** * Find pet by ID * Returns a single pet * @param petId ID of pet to return */ - @Location("/pet/{petId}") class getPetById(val petId: kotlin.Long) + @Serializable @Resource("/pet/{petId}") class getPetById(val petId: kotlin.Long) /** * Update an existing pet * * @param body Pet object that needs to be added to the store */ - @Location("/pet") class updatePet(val body: Pet) + @Serializable @Resource("/pet") class updatePet(val body: Pet) /** * Updates a pet in the store with form data @@ -66,7 +66,7 @@ object Paths { * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) */ - @Location("/pet/{petId}") class updatePetWithForm(val petId: kotlin.Long, val name: kotlin.String? = null, val status: kotlin.String? = null) + @Serializable @Resource("/pet/{petId}") class updatePetWithForm(val petId: kotlin.Long, val name: kotlin.String? = null, val status: kotlin.String? = null) /** * uploads an image @@ -75,69 +75,69 @@ object Paths { * @param additionalMetadata Additional data to pass to server (optional) * @param file file to upload (optional) */ - @Location("/pet/{petId}/uploadImage") class uploadFile(val petId: kotlin.Long, val additionalMetadata: kotlin.String? = null, val file: java.io.File? = null) + @Serializable @Resource("/pet/{petId}/uploadImage") class uploadFile(val petId: kotlin.Long, val additionalMetadata: kotlin.String? = null, val file: java.io.File? = null) /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted */ - @Location("/store/order/{orderId}") class deleteOrder(val orderId: kotlin.String) + @Serializable @Resource("/store/order/{orderId}") class deleteOrder(val orderId: kotlin.String) /** * Returns pet inventories by status * Returns a map of status codes to quantities */ - @Location("/store/inventory") object getInventory + @Serializable @Resource("/store/inventory") class getInventory /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions * @param orderId ID of pet that needs to be fetched */ - @Location("/store/order/{orderId}") class getOrderById(val orderId: kotlin.Long) + @Serializable @Resource("/store/order/{orderId}") class getOrderById(val orderId: kotlin.Long) /** * Place an order for a pet * * @param body order placed for purchasing the pet */ - @Location("/store/order") class placeOrder(val body: Order) + @Serializable @Resource("/store/order") class placeOrder(val body: Order) /** * Create user * This can only be done by the logged in user. * @param body Created user object */ - @Location("/user") class createUser(val body: User) + @Serializable @Resource("/user") class createUser(val body: User) /** * Creates list of users with given input array * * @param body List of user object */ - @Location("/user/createWithArray") class createUsersWithArrayInput(val body: kotlin.collections.MutableList) + @Serializable @Resource("/user/createWithArray") class createUsersWithArrayInput(val body: kotlin.collections.MutableList) /** * Creates list of users with given input array * * @param body List of user object */ - @Location("/user/createWithList") class createUsersWithListInput(val body: kotlin.collections.MutableList) + @Serializable @Resource("/user/createWithList") class createUsersWithListInput(val body: kotlin.collections.MutableList) /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - @Location("/user/{username}") class deleteUser(val username: kotlin.String) + @Serializable @Resource("/user/{username}") class deleteUser(val username: kotlin.String) /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. */ - @Location("/user/{username}") class getUserByName(val username: kotlin.String) + @Serializable @Resource("/user/{username}") class getUserByName(val username: kotlin.String) /** * Logs user into the system @@ -145,13 +145,13 @@ object Paths { * @param username The user name for login * @param password The password for login in clear text */ - @Location("/user/login") class loginUser(val username: kotlin.String, val password: kotlin.String) + @Serializable @Resource("/user/login") class loginUser(val username: kotlin.String, val password: kotlin.String) /** * Logs out current logged in user session * */ - @Location("/user/logout") object logoutUser + @Serializable @Resource("/user/logout") class logoutUser /** * Updated user @@ -159,6 +159,6 @@ object Paths { * @param username name that need to be deleted * @param body Updated user object */ - @Location("/user/{username}") class updateUser(val username: kotlin.String, val body: User) + @Serializable @Resource("/user/{username}") class updateUser(val username: kotlin.String, val body: User) } diff --git a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/PetApi.kt b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/PetApi.kt index cce96c458768..0743d1d24f8f 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/PetApi.kt +++ b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/PetApi.kt @@ -12,18 +12,23 @@ package org.openapitools.server.apis import com.google.gson.Gson -import io.ktor.application.* -import io.ktor.auth.* import io.ktor.http.* -import io.ktor.response.* +import io.ktor.server.application.* +import io.ktor.server.auth.* +import io.ktor.server.response.* import org.openapitools.server.Paths -import io.ktor.locations.* -import io.ktor.routing.* +import io.ktor.server.resources.options +import io.ktor.server.resources.get +import io.ktor.server.resources.post +import io.ktor.server.resources.put +import io.ktor.server.resources.delete +import io.ktor.server.resources.head +import io.ktor.server.resources.patch +import io.ktor.server.routing.* import org.openapitools.server.infrastructure.ApiPrincipal import org.openapitools.server.models.ModelApiResponse import org.openapitools.server.models.Pet -@KtorExperimentalLocationsAPI fun Route.PetApi() { val gson = Gson() val empty = mutableMapOf() diff --git a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt index b195797a0203..c8ae307e1033 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt +++ b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt @@ -12,17 +12,22 @@ package org.openapitools.server.apis import com.google.gson.Gson -import io.ktor.application.* -import io.ktor.auth.* import io.ktor.http.* -import io.ktor.response.* +import io.ktor.server.application.* +import io.ktor.server.auth.* +import io.ktor.server.response.* import org.openapitools.server.Paths -import io.ktor.locations.* -import io.ktor.routing.* +import io.ktor.server.resources.options +import io.ktor.server.resources.get +import io.ktor.server.resources.post +import io.ktor.server.resources.put +import io.ktor.server.resources.delete +import io.ktor.server.resources.head +import io.ktor.server.resources.patch +import io.ktor.server.routing.* import org.openapitools.server.infrastructure.ApiPrincipal import org.openapitools.server.models.Order -@KtorExperimentalLocationsAPI fun Route.StoreApi() { val gson = Gson() val empty = mutableMapOf() diff --git a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/UserApi.kt b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/UserApi.kt index 1871c4b30975..a180d715fe77 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/UserApi.kt +++ b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/UserApi.kt @@ -12,17 +12,22 @@ package org.openapitools.server.apis import com.google.gson.Gson -import io.ktor.application.* -import io.ktor.auth.* import io.ktor.http.* -import io.ktor.response.* +import io.ktor.server.application.* +import io.ktor.server.auth.* +import io.ktor.server.response.* import org.openapitools.server.Paths -import io.ktor.locations.* -import io.ktor.routing.* +import io.ktor.server.resources.options +import io.ktor.server.resources.get +import io.ktor.server.resources.post +import io.ktor.server.resources.put +import io.ktor.server.resources.delete +import io.ktor.server.resources.head +import io.ktor.server.resources.patch +import io.ktor.server.routing.* import org.openapitools.server.infrastructure.ApiPrincipal import org.openapitools.server.models.User -@KtorExperimentalLocationsAPI fun Route.UserApi() { val gson = Gson() val empty = mutableMapOf() diff --git a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt index de09ba8b6b62..c2cad7fe7a7f 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt +++ b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt @@ -1,10 +1,10 @@ package org.openapitools.server.infrastructure -import io.ktor.application.* -import io.ktor.auth.* import io.ktor.http.auth.* -import io.ktor.request.* -import io.ktor.response.* +import io.ktor.server.application.* +import io.ktor.server.auth.* +import io.ktor.server.request.* +import io.ktor.server.response.* enum class ApiKeyLocation(val location: String) { QUERY("query"), @@ -15,8 +15,7 @@ data class ApiKeyCredential(val value: String) : Credential data class ApiPrincipal(val apiKeyCredential: ApiKeyCredential?) : Principal /** -* Represents a Api Key authentication provider -* @param name is the name of the provider, or `null` for a default provider +* Represents an Api Key authentication provider */ class ApiKeyAuthenticationProvider(configuration: Configuration) : AuthenticationProvider(configuration) { @@ -26,39 +25,38 @@ class ApiKeyAuthenticationProvider(configuration: Configuration) : Authenticatio private val apiKeyLocation: ApiKeyLocation = configuration.apiKeyLocation - internal fun install() { - pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> - val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) - val principal = credentials?.let { authenticationFunction(call, it) } + override suspend fun onAuthenticate(context: AuthenticationContext) { + val call = context.call + val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) + val principal = credentials?.let { authenticationFunction.invoke(call, it) } - val cause = when { - credentials == null -> AuthenticationFailedCause.NoCredentials - principal == null -> AuthenticationFailedCause.InvalidCredentials - else -> null - } + val cause = when { + credentials == null -> AuthenticationFailedCause.NoCredentials + principal == null -> AuthenticationFailedCause.InvalidCredentials + else -> null + } - if (cause != null) { - context.challenge(apiKeyName, cause) { - call.respond( - UnauthorizedResponse( - HttpAuthHeader.Parameterized( - "API_KEY", - mapOf("key" to apiKeyName), - HeaderValueEncoding.QUOTED_ALWAYS - ) + if (cause != null) { + context.challenge(apiKeyName, cause) { challenge, call -> + call.respond( + UnauthorizedResponse( + HttpAuthHeader.Parameterized( + "API_KEY", + mapOf("key" to apiKeyName), + HeaderValueEncoding.QUOTED_ALWAYS ) ) - it.complete() - } + ) + challenge.complete() } + } - if (principal != null) { - context.principal(principal) - } + if (principal != null) { + context.principal(principal) } } - class Configuration internal constructor(name: String?) : AuthenticationProvider.Configuration(name) { + class Configuration internal constructor(name: String?) : Config(name) { internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { throw NotImplementedError( @@ -80,13 +78,12 @@ class ApiKeyAuthenticationProvider(configuration: Configuration) : Authenticatio } } -fun Authentication.Configuration.apiKeyAuth( +fun AuthenticationConfig.apiKeyAuth( name: String? = null, configure: ApiKeyAuthenticationProvider.Configuration.() -> Unit ) { val configuration = ApiKeyAuthenticationProvider.Configuration(name).apply(configure) val provider = ApiKeyAuthenticationProvider(configuration) - provider.install() register(provider) } diff --git a/samples/server/petstore/kotlin-server/jaxrs-spec/gradle/wrapper/gradle-wrapper.jar b/samples/server/petstore/kotlin-server/jaxrs-spec/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..249e5832f090 Binary files /dev/null and b/samples/server/petstore/kotlin-server/jaxrs-spec/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/server/petstore/kotlin-server/jaxrs-spec/gradle/wrapper/gradle-wrapper.properties b/samples/server/petstore/kotlin-server/jaxrs-spec/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..7665b0fa93ae --- /dev/null +++ b/samples/server/petstore/kotlin-server/jaxrs-spec/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/server/petstore/kotlin-server/jaxrs-spec/gradlew b/samples/server/petstore/kotlin-server/jaxrs-spec/gradlew new file mode 100755 index 000000000000..a69d9cb6c206 --- /dev/null +++ b/samples/server/petstore/kotlin-server/jaxrs-spec/gradlew @@ -0,0 +1,240 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/server/petstore/kotlin-server/jaxrs-spec/gradlew.bat b/samples/server/petstore/kotlin-server/jaxrs-spec/gradlew.bat new file mode 100644 index 000000000000..f127cfd49d40 --- /dev/null +++ b/samples/server/petstore/kotlin-server/jaxrs-spec/gradlew.bat @@ -0,0 +1,91 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/server/petstore/kotlin-server/ktor/README.md b/samples/server/petstore/kotlin-server/ktor/README.md index 1bcd7feac5a1..cb749cfddd5b 100644 --- a/samples/server/petstore/kotlin-server/ktor/README.md +++ b/samples/server/petstore/kotlin-server/ktor/README.md @@ -6,8 +6,8 @@ Generated by OpenAPI Generator 7.0.0-SNAPSHOT. ## Requires -* Kotlin 1.4.32 -* Gradle 6.9 +* Kotlin 1.7.20 +* Gradle 7.4.2 ## Build diff --git a/samples/server/petstore/kotlin-server/ktor/build.gradle b/samples/server/petstore/kotlin-server/ktor/build.gradle index ebf0c9880680..bd883dc22910 100644 --- a/samples/server/petstore/kotlin-server/ktor/build.gradle +++ b/samples/server/petstore/kotlin-server/ktor/build.gradle @@ -2,13 +2,13 @@ group "org.openapitools" version "1.0.0" wrapper { - gradleVersion = "6.9" + gradleVersion = "7.4.2" distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" } buildscript { - ext.kotlin_version = "1.4.32" - ext.ktor_version = "1.5.4" + ext.kotlin_version = "1.7.20" + ext.ktor_version = "2.2.1" ext.shadow_version = "6.1.0" repositories { @@ -55,14 +55,19 @@ repositories { dependencies { implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version") - implementation("ch.qos.logback:logback-classic:1.2.1") + implementation("ch.qos.logback:logback-classic:1.2.9") implementation("com.typesafe:config:1.4.1") - implementation("io.ktor:ktor-auth:$ktor_version") + implementation("io.ktor:ktor-server-auth:$ktor_version") implementation("io.ktor:ktor-client-apache:$ktor_version") - implementation("io.ktor:ktor-gson:$ktor_version") - implementation("io.ktor:ktor-locations:$ktor_version") + implementation("io.ktor:ktor-server-auto-head-response:$ktor_version") + implementation("io.ktor:ktor-server-default-headers:$ktor_version") + implementation("io.ktor:ktor-server-content-negotiation:$ktor_version") + implementation("io.ktor:ktor-serialization-gson:$ktor_version") + implementation("io.ktor:ktor-server-resources:$ktor_version") + implementation("io.ktor:ktor-server-hsts:$ktor_version") + implementation("io.ktor:ktor-server-compression:$ktor_version") implementation("io.dropwizard.metrics:metrics-core:4.1.18") - implementation("io.ktor:ktor-metrics:$ktor_version") + implementation("io.ktor:ktor-server-metrics:$ktor_version") implementation("io.ktor:ktor-server-netty:$ktor_version") testImplementation("junit:junit:4.13.2") diff --git a/samples/server/petstore/kotlin-server/ktor/gradle/wrapper/gradle-wrapper.jar b/samples/server/petstore/kotlin-server/ktor/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..249e5832f090 Binary files /dev/null and b/samples/server/petstore/kotlin-server/ktor/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/server/petstore/kotlin-server/ktor/gradle/wrapper/gradle-wrapper.properties b/samples/server/petstore/kotlin-server/ktor/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..92f06b50fd65 --- /dev/null +++ b/samples/server/petstore/kotlin-server/ktor/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/server/petstore/kotlin-server/ktor/gradlew b/samples/server/petstore/kotlin-server/ktor/gradlew new file mode 100755 index 000000000000..a69d9cb6c206 --- /dev/null +++ b/samples/server/petstore/kotlin-server/ktor/gradlew @@ -0,0 +1,240 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/server/petstore/kotlin-server/ktor/gradlew.bat b/samples/server/petstore/kotlin-server/ktor/gradlew.bat new file mode 100644 index 000000000000..f127cfd49d40 --- /dev/null +++ b/samples/server/petstore/kotlin-server/ktor/gradlew.bat @@ -0,0 +1,91 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt index 3244ed0ba8cd..2de9d58ce937 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/AppMain.kt @@ -1,20 +1,23 @@ package org.openapitools.server -import com.codahale.metrics.Slf4jReporter -import io.ktor.application.* -import io.ktor.features.* -import io.ktor.gson.* +import io.ktor.server.application.* +import io.ktor.serialization.gson.* import io.ktor.http.* -import io.ktor.locations.* -import io.ktor.metrics.dropwizard.* +import io.ktor.server.resources.* +import io.ktor.server.plugins.autohead.* +import io.ktor.server.plugins.compression.* +import io.ktor.server.plugins.contentnegotiation.* +import io.ktor.server.plugins.defaultheaders.* +import io.ktor.server.plugins.hsts.* +import com.codahale.metrics.Slf4jReporter +import io.ktor.server.metrics.dropwizard.* import java.util.concurrent.TimeUnit -import io.ktor.routing.* -import io.ktor.util.* +import io.ktor.server.routing.* import com.typesafe.config.ConfigFactory -import io.ktor.auth.* import io.ktor.client.HttpClient import io.ktor.client.engine.apache.Apache -import io.ktor.config.HoconApplicationConfig +import io.ktor.server.config.HoconApplicationConfig +import io.ktor.server.auth.* import org.openapitools.server.infrastructure.* import org.openapitools.server.apis.PetApi import org.openapitools.server.apis.StoreApi @@ -27,13 +30,11 @@ object HTTP { val client = HttpClient(Apache) } -@KtorExperimentalAPI -@KtorExperimentalLocationsAPI fun Application.main() { install(DefaultHeaders) install(DropwizardMetrics) { val reporter = Slf4jReporter.forRegistry(registry) - .outputTo(log) + .outputTo(this@main.log) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build() @@ -45,11 +46,11 @@ fun Application.main() { install(AutoHeadResponse) // see https://ktor.io/docs/autoheadresponse.html install(Compression, ApplicationCompressionConfiguration()) // see https://ktor.io/docs/compression.html install(HSTS, ApplicationHstsConfiguration()) // see https://ktor.io/docs/hsts.html - install(Locations) // see https://ktor.io/docs/features-locations.html + install(Resources) install(Authentication) { oauth("petstore_auth") { client = HttpClient(Apache) - providerLookup = { ApplicationAuthProviders["petstore_auth"] } + providerLookup = { applicationAuthProvider(this@main.environment.config) } urlProvider = { _ -> // TODO: define a callback url here. "/" diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt index 604eb33677be..f78654c60f0f 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Configuration.kt @@ -1,22 +1,25 @@ package org.openapitools.server // Use this file to hold package-level internal functions that return receiver object passed to the `install` method. -import io.ktor.auth.* -import io.ktor.features.* import io.ktor.http.* +import io.ktor.server.auth.* +import io.ktor.server.config.* import io.ktor.util.* import java.time.Duration import java.util.concurrent.TimeUnit +import io.ktor.server.plugins.compression.* +import io.ktor.server.plugins.hsts.* + /** * Application block for [HSTS] configuration. * * This file may be excluded in .openapi-generator-ignore, - * and application specific configuration can be applied in this function. + * and application-specific configuration can be applied in this function. * * See http://ktor.io/features/hsts.html */ -internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { +internal fun ApplicationHstsConfiguration(): HSTSConfig.() -> Unit { return { maxAgeInSeconds = TimeUnit.DAYS.toSeconds(365) includeSubDomains = true @@ -31,11 +34,11 @@ internal fun ApplicationHstsConfiguration(): HSTS.Configuration.() -> Unit { * Application block for [Compression] configuration. * * This file may be excluded in .openapi-generator-ignore, - * and application specific configuration can be applied in this function. + * and application-specific configuration can be applied in this function. * * See http://ktor.io/features/compression.html */ -internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() -> Unit { +internal fun ApplicationCompressionConfiguration(): CompressionConfig.() -> Unit { return { gzip { priority = 1.0 @@ -48,24 +51,13 @@ internal fun ApplicationCompressionConfiguration(): Compression.Configuration.() } // Defines authentication mechanisms used throughout the application. -val ApplicationAuthProviders: Map = listOf( - OAuthServerSettings.OAuth2ServerSettings( - name = "petstore_auth", - authorizeUrl = "http://petstore.swagger.io/api/oauth/dialog", - accessTokenUrl = "", - requestMethod = HttpMethod.Get, - clientId = settings.property("auth.oauth.petstore_auth.clientId").getString(), - clientSecret = settings.property("auth.oauth.petstore_auth.clientSecret").getString(), - defaultScopes = listOf("write:pets", "read:pets") - ), -// OAuthServerSettings.OAuth2ServerSettings( -// name = "facebook", -// authorizeUrl = "https://graph.facebook.com/oauth/authorize", -// accessTokenUrl = "https://graph.facebook.com/oauth/access_token", -// requestMethod = HttpMethod.Post, -// -// clientId = settings.property("auth.oauth.facebook.clientId").getString(), -// clientSecret = settings.property("auth.oauth.facebook.clientSecret").getString(), -// defaultScopes = listOf("public_profile") -// ) -).associateBy { it.name } +fun applicationAuthProvider(config: ApplicationConfig): OAuthServerSettings = + OAuthServerSettings.OAuth2ServerSettings( + name = "petstore_auth", + authorizeUrl = "http://petstore.swagger.io/api/oauth/dialog", + accessTokenUrl = "", + requestMethod = HttpMethod.Get, + clientId = config.property("auth.oauth.petstore_auth.clientId").getString(), + clientSecret = config.property("auth.oauth.petstore_auth.clientSecret").getString(), + defaultScopes = listOf("write:pets", "read:pets") + ) diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Paths.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Paths.kt index 4920198e0f97..4a9c3bb01944 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Paths.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/Paths.kt @@ -11,17 +11,17 @@ */ package org.openapitools.server -import io.ktor.locations.* +import io.ktor.resources.* +import kotlinx.serialization.* import org.openapitools.server.models.* -@KtorExperimentalLocationsAPI object Paths { /** * Add a new pet to the store * * @param body Pet object that needs to be added to the store */ - @Location("/pet") class addPet(val body: Pet) + @Serializable @Resource("/pet") class addPet(val body: Pet) /** * Deletes a pet @@ -29,35 +29,35 @@ object Paths { * @param petId Pet id to delete * @param apiKey (optional) */ - @Location("/pet/{petId}") class deletePet(val petId: kotlin.Long, val apiKey: kotlin.String? = null) + @Serializable @Resource("/pet/{petId}") class deletePet(val petId: kotlin.Long, val apiKey: kotlin.String? = null) /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - @Location("/pet/findByStatus") class findPetsByStatus(val status: kotlin.collections.List) + @Serializable @Resource("/pet/findByStatus") class findPetsByStatus(val status: kotlin.collections.List) /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - @Location("/pet/findByTags") class findPetsByTags(val tags: kotlin.collections.List) + @Serializable @Resource("/pet/findByTags") class findPetsByTags(val tags: kotlin.collections.List) /** * Find pet by ID * Returns a single pet * @param petId ID of pet to return */ - @Location("/pet/{petId}") class getPetById(val petId: kotlin.Long) + @Serializable @Resource("/pet/{petId}") class getPetById(val petId: kotlin.Long) /** * Update an existing pet * * @param body Pet object that needs to be added to the store */ - @Location("/pet") class updatePet(val body: Pet) + @Serializable @Resource("/pet") class updatePet(val body: Pet) /** * Updates a pet in the store with form data @@ -66,7 +66,7 @@ object Paths { * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) */ - @Location("/pet/{petId}") class updatePetWithForm(val petId: kotlin.Long, val name: kotlin.String? = null, val status: kotlin.String? = null) + @Serializable @Resource("/pet/{petId}") class updatePetWithForm(val petId: kotlin.Long, val name: kotlin.String? = null, val status: kotlin.String? = null) /** * uploads an image @@ -75,69 +75,69 @@ object Paths { * @param additionalMetadata Additional data to pass to server (optional) * @param file file to upload (optional) */ - @Location("/pet/{petId}/uploadImage") class uploadFile(val petId: kotlin.Long, val additionalMetadata: kotlin.String? = null, val file: java.io.File? = null) + @Serializable @Resource("/pet/{petId}/uploadImage") class uploadFile(val petId: kotlin.Long, val additionalMetadata: kotlin.String? = null, val file: java.io.File? = null) /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted */ - @Location("/store/order/{orderId}") class deleteOrder(val orderId: kotlin.String) + @Serializable @Resource("/store/order/{orderId}") class deleteOrder(val orderId: kotlin.String) /** * Returns pet inventories by status * Returns a map of status codes to quantities */ - @Location("/store/inventory") object getInventory + @Serializable @Resource("/store/inventory") class getInventory /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions * @param orderId ID of pet that needs to be fetched */ - @Location("/store/order/{orderId}") class getOrderById(val orderId: kotlin.Long) + @Serializable @Resource("/store/order/{orderId}") class getOrderById(val orderId: kotlin.Long) /** * Place an order for a pet * * @param body order placed for purchasing the pet */ - @Location("/store/order") class placeOrder(val body: Order) + @Serializable @Resource("/store/order") class placeOrder(val body: Order) /** * Create user * This can only be done by the logged in user. * @param body Created user object */ - @Location("/user") class createUser(val body: User) + @Serializable @Resource("/user") class createUser(val body: User) /** * Creates list of users with given input array * * @param body List of user object */ - @Location("/user/createWithArray") class createUsersWithArrayInput(val body: kotlin.collections.List) + @Serializable @Resource("/user/createWithArray") class createUsersWithArrayInput(val body: kotlin.collections.List) /** * Creates list of users with given input array * * @param body List of user object */ - @Location("/user/createWithList") class createUsersWithListInput(val body: kotlin.collections.List) + @Serializable @Resource("/user/createWithList") class createUsersWithListInput(val body: kotlin.collections.List) /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - @Location("/user/{username}") class deleteUser(val username: kotlin.String) + @Serializable @Resource("/user/{username}") class deleteUser(val username: kotlin.String) /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. */ - @Location("/user/{username}") class getUserByName(val username: kotlin.String) + @Serializable @Resource("/user/{username}") class getUserByName(val username: kotlin.String) /** * Logs user into the system @@ -145,13 +145,13 @@ object Paths { * @param username The user name for login * @param password The password for login in clear text */ - @Location("/user/login") class loginUser(val username: kotlin.String, val password: kotlin.String) + @Serializable @Resource("/user/login") class loginUser(val username: kotlin.String, val password: kotlin.String) /** * Logs out current logged in user session * */ - @Location("/user/logout") object logoutUser + @Serializable @Resource("/user/logout") class logoutUser /** * Updated user @@ -159,6 +159,6 @@ object Paths { * @param username name that need to be deleted * @param body Updated user object */ - @Location("/user/{username}") class updateUser(val username: kotlin.String, val body: User) + @Serializable @Resource("/user/{username}") class updateUser(val username: kotlin.String, val body: User) } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt index cce96c458768..0743d1d24f8f 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt @@ -12,18 +12,23 @@ package org.openapitools.server.apis import com.google.gson.Gson -import io.ktor.application.* -import io.ktor.auth.* import io.ktor.http.* -import io.ktor.response.* +import io.ktor.server.application.* +import io.ktor.server.auth.* +import io.ktor.server.response.* import org.openapitools.server.Paths -import io.ktor.locations.* -import io.ktor.routing.* +import io.ktor.server.resources.options +import io.ktor.server.resources.get +import io.ktor.server.resources.post +import io.ktor.server.resources.put +import io.ktor.server.resources.delete +import io.ktor.server.resources.head +import io.ktor.server.resources.patch +import io.ktor.server.routing.* import org.openapitools.server.infrastructure.ApiPrincipal import org.openapitools.server.models.ModelApiResponse import org.openapitools.server.models.Pet -@KtorExperimentalLocationsAPI fun Route.PetApi() { val gson = Gson() val empty = mutableMapOf() diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt index b195797a0203..c8ae307e1033 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt @@ -12,17 +12,22 @@ package org.openapitools.server.apis import com.google.gson.Gson -import io.ktor.application.* -import io.ktor.auth.* import io.ktor.http.* -import io.ktor.response.* +import io.ktor.server.application.* +import io.ktor.server.auth.* +import io.ktor.server.response.* import org.openapitools.server.Paths -import io.ktor.locations.* -import io.ktor.routing.* +import io.ktor.server.resources.options +import io.ktor.server.resources.get +import io.ktor.server.resources.post +import io.ktor.server.resources.put +import io.ktor.server.resources.delete +import io.ktor.server.resources.head +import io.ktor.server.resources.patch +import io.ktor.server.routing.* import org.openapitools.server.infrastructure.ApiPrincipal import org.openapitools.server.models.Order -@KtorExperimentalLocationsAPI fun Route.StoreApi() { val gson = Gson() val empty = mutableMapOf() diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt index 1871c4b30975..a180d715fe77 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt @@ -12,17 +12,22 @@ package org.openapitools.server.apis import com.google.gson.Gson -import io.ktor.application.* -import io.ktor.auth.* import io.ktor.http.* -import io.ktor.response.* +import io.ktor.server.application.* +import io.ktor.server.auth.* +import io.ktor.server.response.* import org.openapitools.server.Paths -import io.ktor.locations.* -import io.ktor.routing.* +import io.ktor.server.resources.options +import io.ktor.server.resources.get +import io.ktor.server.resources.post +import io.ktor.server.resources.put +import io.ktor.server.resources.delete +import io.ktor.server.resources.head +import io.ktor.server.resources.patch +import io.ktor.server.routing.* import org.openapitools.server.infrastructure.ApiPrincipal import org.openapitools.server.models.User -@KtorExperimentalLocationsAPI fun Route.UserApi() { val gson = Gson() val empty = mutableMapOf() diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt index de09ba8b6b62..c2cad7fe7a7f 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/infrastructure/ApiKeyAuth.kt @@ -1,10 +1,10 @@ package org.openapitools.server.infrastructure -import io.ktor.application.* -import io.ktor.auth.* import io.ktor.http.auth.* -import io.ktor.request.* -import io.ktor.response.* +import io.ktor.server.application.* +import io.ktor.server.auth.* +import io.ktor.server.request.* +import io.ktor.server.response.* enum class ApiKeyLocation(val location: String) { QUERY("query"), @@ -15,8 +15,7 @@ data class ApiKeyCredential(val value: String) : Credential data class ApiPrincipal(val apiKeyCredential: ApiKeyCredential?) : Principal /** -* Represents a Api Key authentication provider -* @param name is the name of the provider, or `null` for a default provider +* Represents an Api Key authentication provider */ class ApiKeyAuthenticationProvider(configuration: Configuration) : AuthenticationProvider(configuration) { @@ -26,39 +25,38 @@ class ApiKeyAuthenticationProvider(configuration: Configuration) : Authenticatio private val apiKeyLocation: ApiKeyLocation = configuration.apiKeyLocation - internal fun install() { - pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> - val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) - val principal = credentials?.let { authenticationFunction(call, it) } + override suspend fun onAuthenticate(context: AuthenticationContext) { + val call = context.call + val credentials = call.request.apiKeyAuthenticationCredentials(apiKeyName, apiKeyLocation) + val principal = credentials?.let { authenticationFunction.invoke(call, it) } - val cause = when { - credentials == null -> AuthenticationFailedCause.NoCredentials - principal == null -> AuthenticationFailedCause.InvalidCredentials - else -> null - } + val cause = when { + credentials == null -> AuthenticationFailedCause.NoCredentials + principal == null -> AuthenticationFailedCause.InvalidCredentials + else -> null + } - if (cause != null) { - context.challenge(apiKeyName, cause) { - call.respond( - UnauthorizedResponse( - HttpAuthHeader.Parameterized( - "API_KEY", - mapOf("key" to apiKeyName), - HeaderValueEncoding.QUOTED_ALWAYS - ) + if (cause != null) { + context.challenge(apiKeyName, cause) { challenge, call -> + call.respond( + UnauthorizedResponse( + HttpAuthHeader.Parameterized( + "API_KEY", + mapOf("key" to apiKeyName), + HeaderValueEncoding.QUOTED_ALWAYS ) ) - it.complete() - } + ) + challenge.complete() } + } - if (principal != null) { - context.principal(principal) - } + if (principal != null) { + context.principal(principal) } } - class Configuration internal constructor(name: String?) : AuthenticationProvider.Configuration(name) { + class Configuration internal constructor(name: String?) : Config(name) { internal var authenticationFunction: suspend ApplicationCall.(ApiKeyCredential) -> Principal? = { throw NotImplementedError( @@ -80,13 +78,12 @@ class ApiKeyAuthenticationProvider(configuration: Configuration) : Authenticatio } } -fun Authentication.Configuration.apiKeyAuth( +fun AuthenticationConfig.apiKeyAuth( name: String? = null, configure: ApiKeyAuthenticationProvider.Configuration.() -> Unit ) { val configuration = ApiKeyAuthenticationProvider.Configuration(name).apply(configure) val provider = ApiKeyAuthenticationProvider(configuration) - provider.install() register(provider) } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/ApiResponse.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/ApiResponse.kt new file mode 100644 index 000000000000..14f50dbb9ad6 --- /dev/null +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/models/ApiResponse.kt @@ -0,0 +1,32 @@ +/** +* OpenAPI Petstore +* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. +* +* The version of the OpenAPI document: 1.0.0 +* +* +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). +* https://openapi-generator.tech +* Do not edit the class manually. +*/ +package org.openapitools.server.models + + +import java.io.Serializable +/** + * Describes the result of uploading an image resource + * @param code + * @param type + * @param message + */ +data class ApiResponse( + val code: kotlin.Int? = null, + val type: kotlin.String? = null, + val message: kotlin.String? = null +) : Serializable +{ + companion object { + private const val serialVersionUID: Long = 123 + } +} +