[C++][Qt5] added Authentication Support (#8004)

* first commit of api Key feature.

* added multi key and URL query key support

* fixed error in mustache files, updated samples and tests

* added Basic Auth with Base64 encoding.

* updated Readme, added bearer token

* added check that authentication credentials are set. fixed typo in README
This commit is contained in:
basyskom-dege
2020-11-28 08:02:09 +01:00
committed by GitHub
parent 045d05fa72
commit cb1a620628
13 changed files with 517 additions and 1 deletions

View File

@@ -80,6 +80,7 @@ public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements Codege
supportingFiles.add(new SupportingFile("HttpFileElement.cpp.mustache", sourceFolder, PREFIX + "HttpFileElement.cpp"));
supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h"));
supportingFiles.add(new SupportingFile("enum.mustache", sourceFolder, PREFIX + "Enum.h"));
supportingFiles.add(new SupportingFile("README.mustache", "","README.md"));
supportingFiles.add(new SupportingFile("CMakeLists.txt.mustache", sourceFolder, "CMakeLists.txt"));
if (optionalProjectFileFlag) {
supportingFiles.add(new SupportingFile("Project.mustache", sourceFolder, "client.pri"));
@@ -108,6 +109,7 @@ public class CppQt5ClientCodegen extends CppQt5AbstractCodegen implements Codege
supportingFiles.add(new SupportingFile("HttpFileElement.cpp.mustache", sourceFolder, modelNamePrefix + "HttpFileElement.cpp"));
supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, modelNamePrefix + "Object.h"));
supportingFiles.add(new SupportingFile("enum.mustache", sourceFolder, modelNamePrefix + "Enum.h"));
supportingFiles.add(new SupportingFile("README.mustache", "","README.md"));
supportingFiles.add(new SupportingFile("CMakeLists.txt.mustache", sourceFolder, "CMakeLists.txt"));

View File

@@ -0,0 +1,183 @@
# {{artifactId}}
{{appName}}
- API version: {{appVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
{{#appDescriptionWithNewLines}}{{{appDescriptionWithNewLines}}}{{/appDescriptionWithNewLines}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)*
## Licence
{{licenseInfo}}
for more information visit [{{licenseInfo}}]({{licenseUrl}})
## Requirements
Building the API client library requires:
1. Java {{#supportJava6}}1.6{{/supportJava6}}{{^supportJava6}}{{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}{{/supportJava6}}+
2. Maven/Gradle
## Installation
To install the API client library to your local Maven repository, simply execute:
```shell
mvn clean install
```
To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:
```shell
mvn clean deploy
```
Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information.
### Generate manually
At first generate the JAR by executing:
```shell
mvn clean package
```
Use the Jar file to generate the Qt5 Client:
```shell
java -jar target/openapi-generator-cli.jar generate -i <yourOpenApiFile> -g cpp-qt5-client -o <outputDir>
```
## Getting Started
Please follow the [installation](#installation) instruction and execute the following Java code:
example.h:
```c++
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
#include <iostream>
#include "../client/{{{classname}}}.h"
using namespace test_namespace;
class Example : public QObject {
Q_OBJECT
{{#allParams}}
{{{dataType}}} create();
{{/allParams}}
public slots:
void exampleFunction1();
};
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```
example.cpp:
```c++
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
#include "../client/{{{classname}}}.h"
#include "example.h"
#include <QTimer>
#include <QEventLoop>
{{#allParams}}
{{dataType}} Example::create(){
{{{dataType}}} obj;
{{/allParams}}
return obj;
}
void Example::exampleFunction1(){
{{{classname}}} apiInstance;
{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
// Configure HTTP basic authorization: {{{name}}}
apiInstance.setUsername("YOUR USERNAME");
apiInstance.setPassword("YOUR PASSWORD");{{/isBasicBasic}}{{#isBasicBearer}}
// Configure HTTP bearer authorization: {{{name}}}
apiInstance.setBearerToken("BEARER TOKEN");{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
apiInstance.setApiKey("YOUR API KEY NAME","YOUR API KEY");{{/isApiKey}}{{#isOAuth}}
//OAuth Authentication supported right now{{/isOAuth}}{{#isHttpSignature}}
//No Http Signature Authentication supported right now{{/isHttpSignature}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#allParams}}
QEventLoop loop;
connect(&apiInstance, &{{{classname}}}::{{nickname}}Signal, [&]() {
loop.quit();
});
connect(&apiInstance, &{{{classname}}}::{{nickname}}SignalE, [&](QNetworkReply::NetworkError, QString error_str) {
qDebug() << "Error happened while issuing request : " << error_str;
loop.quit();
});
{{{dataType}}} {{{paramName}}} = create(); // {{{dataType}}} | {{{description}}}
{{/allParams}}
apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}});
QTimer::singleShot(5000, &loop, &QEventLoop::quit);
loop.exec();
}
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```
## Documentation for API Endpoints
All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{commonPath}}{{path}} | {{#summary}}{{summary}}{{/summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation for Models
{{#models}}{{#model}} - [{{classname}}]({{modelDocPath}}{{classname}}.md)
{{/model}}{{/models}}
## Documentation for Authorization
{{^authMethods}}All endpoints do not require authorization.
{{/authMethods}}Authentication schemes defined for the API:
{{#authMethods}}### {{name}}
{{#isApiKey}}
- **Type**: API key
- **API key parameter name**: {{keyParamName}}
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
{{/isApiKey}}
{{#isBasicBasic}}
- **Type**: HTTP basic authentication
{{/isBasicBasic}}
{{#isBasicBearer}}
- **Type**: HTTP Bearer Token authentication
{{/isBasicBearer}}
{{#isOAuth}}
- **Type**: OAuth
- **Flow**: {{flow}}
- **Authorization URL**: {{authorizationUrl}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - {{scope}}: {{description}}
{{/scopes}}
{{/isOAuth}}
{{/authMethods}}
## Author
{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}}
{{/-last}}{{/apis}}{{/apiInfo}}

View File

@@ -34,6 +34,22 @@ void {{classname}}::setPort(int port) {
_port = port;
}
void {{classname}}::setApiKey(const QString &apiKeyName, const QString &apiKey){
_apiKeys.insert(apiKeyName,apiKey);
}
void {{classname}}::setBearerToken(const QString &token){
_bearerToken = token;
}
void {{classname}}::setUsername(const QString &username) {
_username = username;
}
void {{classname}}::setPassword(const QString &password) {
_password = password;
}
void {{classname}}::setBasePath(const QString &basePath) {
_basePath = basePath;
}
@@ -79,7 +95,27 @@ void {{classname}}::{{nickname}}({{#allParams}}const {{{dataType}}} &{{paramName
QString {{paramName}}PathParam("{");
{{paramName}}PathParam.append("{{baseName}}").append("}");
fullPath.replace({{paramName}}PathParam, QUrl::toPercentEncoding(::{{cppNamespace}}::toStringValue({{paramName}})));
{{/pathParams}}
{{/pathParams}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}}
if(_apiKeys.contains("{{name}}")){
addHeaders("{{name}}",_apiKeys.find("{{name}}").value());
}
{{/isKeyInHeader}}{{#isKeyInQuery}}
if(_apiKeys.contains("{{name}}")){
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?");
fullPath.append("{{{name}}}=").append(_apiKeys.find("{{name}}").value());
}
{{/isKeyInQuery}}{{/isApiKey}}{{#isBasicBearer}}
if(!_bearerToken.isEmpty())
addHeaders("Authorization", "Bearer " + _bearerToken);
{{/isBasicBearer}}{{#isBasicBasic}}
if(!_username.isEmpty() && !_password.isEmpty()){
QByteArray b64;
b64.append(_username + ":" + _password);
addHeaders("Authorization","Basic " + b64.toBase64());
}{{/isBasicBasic}}{{/authMethods}}
{{#queryParams}}{{^collectionFormat}}
if (fullPath.indexOf("?") > 0)
fullPath.append("&");

View File

@@ -8,6 +8,8 @@
{{/imports}}
#include <QObject>
#include <QByteArray>
#include <QStringList>
#include <QNetworkAccessManager>
{{#cppNamespaceDeclarations}}
@@ -24,6 +26,10 @@ public:
void setScheme(const QString &scheme);
void setHost(const QString &host);
void setPort(int port);
void setApiKey(const QString &apiKeyName, const QString &apiKey);
void setBearerToken(const QString &token);
void setUsername(const QString &username);
void setPassword(const QString &password);
void setBasePath(const QString &basePath);
void setTimeOut(const int timeOut);
void setWorkingDirectory(const QString &path);
@@ -38,6 +44,10 @@ public:
private:
QString _scheme, _host;
int _port;
QMap<QString, QString> _apiKeys;
QString _bearerToken;
QString _username;
QString _password;
QString _basePath;
int _timeOut;
QString _workingDirectory;