Skip to content

Enhancement/kotlin/apiclient and auth #6585

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 11, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.openapitools.codegen.languages;

import org.apache.commons.lang3.StringUtils;
import org.openapitools.codegen.CliOption;
import org.openapitools.codegen.CodegenConstants;
import org.openapitools.codegen.CodegenModel;
Expand All @@ -28,6 +29,7 @@
import org.openapitools.codegen.meta.features.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.openapitools.codegen.utils.ProcessUtils;

import java.io.File;
import java.util.HashMap;
Expand Down Expand Up @@ -68,6 +70,8 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen {
// (mustache does not allow for boolean operators so we need this extra field)
protected boolean doNotUseRxAndCoroutines = true;

protected String authFolder;

public enum DateLibrary {
STRING("string"),
THREETENBP("threetenbp"),
Expand Down Expand Up @@ -300,6 +304,7 @@ public void processOpts() {

// infrastructure destination folder
final String infrastructureFolder = (sourceFolder + File.separator + packageName + File.separator + "infrastructure").replace(".", "/");
authFolder = (sourceFolder + File.separator + packageName + File.separator + "auth").replace(".", "/");

// additional properties
if (additionalProperties.containsKey(DATE_LIBRARY)) {
Expand Down Expand Up @@ -403,6 +408,7 @@ private void processJVMRetrofit2Library(String infrastructureFolder) {
additionalProperties.put(JVM, true);
additionalProperties.put(JVM_RETROFIT2, true);
supportingFiles.add(new SupportingFile("infrastructure/ApiClient.kt.mustache", infrastructureFolder, "ApiClient.kt"));
supportingFiles.add(new SupportingFile("infrastructure/ResponseExt.kt.mustache", infrastructureFolder, "ResponseExt.kt"));
supportingFiles.add(new SupportingFile("infrastructure/CollectionFormats.kt.mustache", infrastructureFolder, "CollectionFormats.kt"));
addSupportingSerializerAdapters(infrastructureFolder);
}
Expand Down Expand Up @@ -494,7 +500,6 @@ private void processMultiplatformLibrary(final String infrastructureFolder) {
supportingFiles.add(new SupportingFile("infrastructure/OctetByteArray.kt.mustache", infrastructureFolder, "OctetByteArray.kt"));

// multiplatform specific auth
final String authFolder = (sourceFolder + File.separator + packageName + File.separator + "auth").replace(".", "/");
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.kt.mustache", authFolder, "ApiKeyAuth.kt"));
supportingFiles.add(new SupportingFile("auth/Authentication.kt.mustache", authFolder, "Authentication.kt"));
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.kt.mustache", authFolder, "HttpBasicAuth.kt"));
Expand Down Expand Up @@ -558,6 +563,10 @@ public Map<String, Object> postProcessModels(Map<String, Object> objs) {
return objects;
}

private boolean usesRetrofit2Library() {
return getLibrary() != null && getLibrary().contains(JVM_RETROFIT2);
}

@Override
@SuppressWarnings("unchecked")
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
Expand All @@ -574,6 +583,22 @@ public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> o
}
}

if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) {
operation.path = operation.path.substring(1);
if (ProcessUtils.hasOAuthMethods(objs)) {
supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.kt.mustache", authFolder, "ApiKeyAuth.kt"));
supportingFiles.add(new SupportingFile("auth/OAuth.kt.mustache", authFolder, "OAuth.kt"));
supportingFiles.add(new SupportingFile("auth/OAuthFlow.kt.mustache", authFolder, "OAuthFlow.kt"));
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.kt.mustache", authFolder, "OAuthOkHttpClient.kt"));
}
if(ProcessUtils.hasBearerMethods(objs)) {
supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.kt.mustache", authFolder, "HttpBearerAuth.kt"));
}
if(ProcessUtils.hasHttpBasicMethods(objs)) {
supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.kt.mustache", authFolder, "HttpBasicAuth.kt"));
}
}

// modify the data type of binary form parameters to a more friendly type for multiplatform builds
if (MULTIPLATFORM.equals(getLibrary()) && operation.allParams != null) {
for (CodegenParameter param : operation.allParams) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.openapitools.codegen.CodegenModel;
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.CodegenSecurity;

Expand Down Expand Up @@ -81,7 +82,79 @@ public static boolean hasApiKeyMethods(List<CodegenSecurity> authMethods) {
}

/**
* Returns true if the specified OAS model has at least one operation with the HTTP signature
* Returns true if at least one operation has OAuth security schema defined
*
* @param objs Map of operations
* @return True if at least one operation has OAuth security schema defined
*/
public static boolean hasOAuthMethods(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if (operation.authMethods != null && !operation.authMethods.isEmpty()) {
for (CodegenSecurity cs : operation.authMethods) {
if (Boolean.TRUE.equals(cs.isOAuth)) {
return true;
}
}
}
}
}

return false;
}

/**
* Returns true if at least one operation has Bearer security schema defined
*
* @param objs Map of operations
* @return True if at least one operation has Bearer security schema defined
*/
public static boolean hasHttpBasicMethods(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if (operation.authMethods != null && !operation.authMethods.isEmpty()) {
for (CodegenSecurity cs : operation.authMethods) {
if (Boolean.TRUE.equals(cs.isBasicBasic)) {
return true;
}
}
}
}
}

return false;
}

/**
* Returns true if at least one operation has Bearer security schema defined
*
* @param objs Map of operations
* @return True if at least one operation has Bearer security schema defined
*/
public static boolean hasBearerMethods(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
if (operations != null) {
List<CodegenOperation> ops = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation operation : ops) {
if (operation.authMethods != null && !operation.authMethods.isEmpty()) {
for (CodegenSecurity cs : operation.authMethods) {
if (Boolean.TRUE.equals(cs.isBasicBearer)) {
return true;
}
}
}
}
}

return false;
}

/**
* Returns true if the specified OAS model has at least one operation with the HTTP basic
* security scheme.
* The HTTP signature scheme is defined in https://datatracker.ietf.org/doc/draft-cavage-http-signatures/
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
## Requires

{{#jvm}}
* Kotlin 1.3.41
* Kotlin 1.3.61
* Gradle 4.9
{{/jvm}}
{{#multiplatform}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ test {

dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
{{#hasOAuthMethods}}
compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.0"
{{/hasOAuthMethods}}
{{#moshi}}
{{^moshiCodeGen}}
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
Expand Down Expand Up @@ -81,6 +84,7 @@ dependencies {
{{/modeCodeGen}}
{{/moshi}}
compile "com.squareup.okhttp3:okhttp:4.2.2"
compile "com.squareup.okhttp3:logging-interceptor:4.4.0"
{{/jvm-okhttp4}}
{{#threetenbp}}
compile "org.threeten:threetenbp:1.4.0"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,18 @@ import retrofit2.http.*
{{#doNotUseRxAndCoroutines}}
import retrofit2.Call
{{/doNotUseRxAndCoroutines}}
{{^doNotUseRxAndCoroutines}}
{{#useCoroutines}}
import retrofit2.Response
{{/useCoroutines}}
{{/doNotUseRxAndCoroutines}}
import okhttp3.RequestBody
{{#isResponseFile}}
import okhttp3.ResponseBody
{{/isResponseFile}}
{{#isMultipart}}
import okhttp3.MultipartBody
{{/isMultipart}}
{{^doNotUseRxAndCoroutines}}
{{#useRxJava}}
import rx.Observable
Expand All @@ -28,6 +37,17 @@ import io.reactivex.Completable
{{#operations}}
interface {{classname}} {
{{#operation}}
/**
* {{summary}}
* {{notes}}
* Responses:{{#responses}}
* - {{code}}: {{{message}}}{{/responses}}
*
{{#allParams}}
* @param {{paramName}} {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
{{/allParams}}
* @return {{^useCoroutines}}[Call]<{{/useCoroutines}}{{#isResponseFile}}[ResponseBody]{{/isResponseFile}}{{^isResponseFile}}{{#returnType}}[{{{returnType}}}]{{/returnType}}{{^returnType}}[Unit]{{/returnType}}{{/isResponseFile}}{{^useCoroutines}}>{{/useCoroutines}}
*/
{{#isDeprecated}}
@Deprecated("This api was deprecated")
{{/isDeprecated}}
Expand All @@ -46,7 +66,7 @@ interface {{classname}} {
{{/prioritizedContentTypes}}
{{/formParams}}
@{{httpMethod}}("{{{path}}}")
{{^doNotUseRxAndCoroutines}}{{#useCoroutines}}suspend {{/useCoroutines}}{{/doNotUseRxAndCoroutines}}fun {{operationId}}({{^allParams}}){{/allParams}}{{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}){{/hasMore}}{{/allParams}}: {{^doNotUseRxAndCoroutines}}{{#useRxJava}}Observable<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}{{/isResponseFile}}>{{/useRxJava}}{{#useRxJava2}}{{#returnType}}Single<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{{returnType}}}{{/isResponseFile}}>{{/returnType}}{{^returnType}}Completable{{/returnType}}{{/useRxJava2}}{{#useCoroutines}}{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}{{/isResponseFile}}{{/useCoroutines}}{{/doNotUseRxAndCoroutines}}{{#doNotUseRxAndCoroutines}}Call<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}{{/isResponseFile}}>{{/doNotUseRxAndCoroutines}}
{{^doNotUseRxAndCoroutines}}{{#useCoroutines}}suspend {{/useCoroutines}}{{/doNotUseRxAndCoroutines}}fun {{operationId}}({{^allParams}}){{/allParams}}{{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}){{/hasMore}}{{/allParams}}: {{^doNotUseRxAndCoroutines}}{{#useRxJava}}Observable<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}{{/isResponseFile}}>{{/useRxJava}}{{#useRxJava2}}{{#returnType}}Single<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{{returnType}}}{{/isResponseFile}}>{{/returnType}}{{^returnType}}Completable{{/returnType}}{{/useRxJava2}}{{#useCoroutines}}Response<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}{{/isResponseFile}}>{{/useCoroutines}}{{/doNotUseRxAndCoroutines}}{{#doNotUseRxAndCoroutines}}Call<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}{{/isResponseFile}}>{{/doNotUseRxAndCoroutines}}

{{/operation}}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# {{classname}}{{#description}}
{{description}}{{/description}}

All URIs are relative to *{{basePath}}*

Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}

{{#operations}}
{{#operation}}

{{summary}}{{#notes}}

{{notes}}{{/notes}}

### Example
```kotlin
// Import classes:
//import {{{packageName}}}.*
//import {{{packageName}}}.infrastructure.*
//import {{{modelPackage}}}.*

val apiClient = ApiClient()
{{#authMethods}}
{{#isBasic}}
{{#isBasicBasic}}
apiClient.setCredentials("USERNAME", "PASSWORD")
{{/isBasicBasic}}
{{#isBasicBearer}}
apiClient.setBearerToken("TOKEN")
{{/isBasicBearer}}
{{/isBasic}}
{{/authMethods}}
val webService = apiClient.createWebservice({{{classname}}}::class.java)
{{#allParams}}
val {{{paramName}}} : {{{dataType}}} = {{{example}}} // {{{dataType}}} | {{{description}}}
{{/allParams}}

{{#useCoroutines}}
launch(Dispatchers.IO) {
{{/useCoroutines}}
{{#useCoroutines}} {{/useCoroutines}}{{#returnType}}val result : {{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}} = {{/returnType}}webService.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
{{#useCoroutines}}
}
{{/useCoroutines}}
```

### Parameters
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#generateModelDocs}}[**{{dataType}}**]({{baseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{dataType}}**{{/generateModelDocs}}{{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{defaultValue}}]{{/defaultValue}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}}
{{/allParams}}

### Return type

{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{#generateModelDocs}}[**{{returnType}}**]({{returnBaseType}}.md){{/generateModelDocs}}{{^generateModelDocs}}**{{returnType}}**{{/generateModelDocs}}{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}}

### Authorization

{{^authMethods}}No authorization required{{/authMethods}}
{{#authMethods}}
{{#isBasic}}
{{#isBasicBasic}}
Configure {{name}}:
ApiClient().setCredentials("USERNAME", "PASSWORD")
{{/isBasicBasic}}
{{#isBasicBearer}}
Configure {{name}}:
ApiClient().setBearerToken("TOKEN")
{{/isBasicBearer}}
{{/isBasic}}
{{/authMethods}}

### HTTP request headers

- **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}}

{{/operation}}
{{/operations}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package {{packageName}}.auth

import java.io.IOException
import java.net.URI
import java.net.URISyntaxException

import okhttp3.Interceptor
import okhttp3.Response

class ApiKeyAuth(
private val location: String = "",
private val paramName: String = "",
private var apiKey: String = ""
) : Interceptor {

@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()

if ("query" == location) {
var newQuery = request.url.toUri().query
val paramValue = "$paramName=$apiKey"
if (newQuery == null) {
newQuery = paramValue
} else {
newQuery += "&$paramValue"
}

val newUri: URI
try {
val oldUri = request.url.toUri()
newUri = URI(oldUri.scheme, oldUri.authority,
oldUri.path, newQuery, oldUri.fragment)
} catch (e: URISyntaxException) {
throw IOException(e)
}

request = request.newBuilder().url(newUri.toURL()).build()
} else if ("header" == location) {
request = request.newBuilder()
.addHeader(paramName, apiKey)
.build()
} else if ("cookie" == location) {
request = request.newBuilder()
.addHeader("Cookie", "$paramName=$apiKey")
.build()
}
return chain.proceed(request)
}
}
Loading