basyskom-dege f596b32316
[Qt][C++] Oauth2 Authorization Code Flow and Implicit Flow Support. (#10183)
* Oauth class with reply server for authorization flow

* multiple scopes. Joined with space seperator

* some refactoring, using urls from the spec

* added implicit flow. Refactored oauth classes.

* added missing {{prefix}} to Oauth class

* added client credentials flow

* added password flow. setVariables for each class

* Refactored variables to fit style. Updated Samples
2021-11-14 23:16:29 +08:00

1227 lines
48 KiB
C++

/**
* 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.
*/
#include "PFXPetApi.h"
#include "PFXServerConfiguration.h"
#include <QJsonArray>
#include <QJsonDocument>
namespace test_namespace {
PFXPetApi::PFXPetApi(const int timeOut)
: _timeOut(timeOut),
_manager(nullptr),
_isResponseCompressionEnabled(false),
_isRequestCompressionEnabled(false) {
initializeServerConfigs();
}
PFXPetApi::~PFXPetApi() {
}
void PFXPetApi::initializeServerConfigs() {
//Default server
QList<PFXServerConfiguration> defaultConf = QList<PFXServerConfiguration>();
//varying endpoint server
defaultConf.append(PFXServerConfiguration(
QUrl("http://petstore.swagger.io/v2"),
"No description provided",
QMap<QString, PFXServerVariable>()));
_serverConfigs.insert("addPet", defaultConf);
_serverIndices.insert("addPet", 0);
_serverConfigs.insert("deletePet", defaultConf);
_serverIndices.insert("deletePet", 0);
_serverConfigs.insert("findPetsByStatus", defaultConf);
_serverIndices.insert("findPetsByStatus", 0);
_serverConfigs.insert("findPetsByTags", defaultConf);
_serverIndices.insert("findPetsByTags", 0);
_serverConfigs.insert("getPetById", defaultConf);
_serverIndices.insert("getPetById", 0);
_serverConfigs.insert("updatePet", defaultConf);
_serverIndices.insert("updatePet", 0);
_serverConfigs.insert("updatePetWithForm", defaultConf);
_serverIndices.insert("updatePetWithForm", 0);
_serverConfigs.insert("uploadFile", defaultConf);
_serverIndices.insert("uploadFile", 0);
}
/**
* returns 0 on success and -1, -2 or -3 on failure.
* -1 when the variable does not exist and -2 if the value is not defined in the enum and -3 if the operation or server index is not found
*/
int PFXPetApi::setDefaultServerValue(int serverIndex, const QString &operation, const QString &variable, const QString &value) {
auto it = _serverConfigs.find(operation);
if (it != _serverConfigs.end() && serverIndex < it.value().size()) {
return _serverConfigs[operation][serverIndex].setDefaultValue(variable,value);
}
return -3;
}
void PFXPetApi::setServerIndex(const QString &operation, int serverIndex) {
if (_serverIndices.contains(operation) && serverIndex < _serverConfigs.find(operation).value().size()) {
_serverIndices[operation] = serverIndex;
}
}
void PFXPetApi::setApiKey(const QString &apiKeyName, const QString &apiKey) {
_apiKeys.insert(apiKeyName,apiKey);
}
void PFXPetApi::setBearerToken(const QString &token) {
_bearerToken = token;
}
void PFXPetApi::setUsername(const QString &username) {
_username = username;
}
void PFXPetApi::setPassword(const QString &password) {
_password = password;
}
void PFXPetApi::setTimeOut(const int timeOut) {
_timeOut = timeOut;
}
void PFXPetApi::setWorkingDirectory(const QString &path) {
_workingDirectory = path;
}
void PFXPetApi::setNetworkAccessManager(QNetworkAccessManager* manager) {
_manager = manager;
}
/**
* Appends a new ServerConfiguration to the config map for a specific operation.
* @param operation The id to the target operation.
* @param url A string that contains the URL of the server
* @param description A String that describes the server
* @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template.
* returns the index of the new server config on success and -1 if the operation is not found
*/
int PFXPetApi::addServerConfiguration(const QString &operation, const QUrl &url, const QString &description, const QMap<QString, PFXServerVariable> &variables) {
if (_serverConfigs.contains(operation)) {
_serverConfigs[operation].append(PFXServerConfiguration(
url,
description,
variables));
return _serverConfigs[operation].size()-1;
} else {
return -1;
}
}
/**
* Appends a new ServerConfiguration to the config map for a all operations and sets the index to that server.
* @param url A string that contains the URL of the server
* @param description A String that describes the server
* @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template.
*/
void PFXPetApi::setNewServerForAllOperations(const QUrl &url, const QString &description, const QMap<QString, PFXServerVariable> &variables) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)
for (auto keyIt = _serverIndices.keyBegin(); keyIt != _serverIndices.keyEnd(); keyIt++) {
setServerIndex(*keyIt, addServerConfiguration(*keyIt, url, description, variables));
}
#else
for (auto &e : _serverIndices.keys()) {
setServerIndex(e, addServerConfiguration(e, url, description, variables));
}
#endif
}
/**
* Appends a new ServerConfiguration to the config map for an operations and sets the index to that server.
* @param URL A string that contains the URL of the server
* @param description A String that describes the server
* @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template.
*/
void PFXPetApi::setNewServer(const QString &operation, const QUrl &url, const QString &description, const QMap<QString, PFXServerVariable> &variables) {
setServerIndex(operation, addServerConfiguration(operation, url, description, variables));
}
void PFXPetApi::addHeaders(const QString &key, const QString &value) {
_defaultHeaders.insert(key, value);
}
void PFXPetApi::enableRequestCompression() {
_isRequestCompressionEnabled = true;
}
void PFXPetApi::enableResponseCompression() {
_isResponseCompressionEnabled = true;
}
void PFXPetApi::abortRequests() {
emit abortRequestsSignal();
}
QString PFXPetApi::getParamStylePrefix(const QString &style) {
if (style == "matrix") {
return ";";
} else if (style == "label") {
return ".";
} else if (style == "form") {
return "&";
} else if (style == "simple") {
return "";
} else if (style == "spaceDelimited") {
return "&";
} else if (style == "pipeDelimited") {
return "&";
} else {
return "none";
}
}
QString PFXPetApi::getParamStyleSuffix(const QString &style) {
if (style == "matrix") {
return "=";
} else if (style == "label") {
return "";
} else if (style == "form") {
return "=";
} else if (style == "simple") {
return "";
} else if (style == "spaceDelimited") {
return "=";
} else if (style == "pipeDelimited") {
return "=";
} else {
return "none";
}
}
QString PFXPetApi::getParamStyleDelimiter(const QString &style, const QString &name, bool isExplode) {
if (style == "matrix") {
return (isExplode) ? ";" + name + "=" : ",";
} else if (style == "label") {
return (isExplode) ? "." : ",";
} else if (style == "form") {
return (isExplode) ? "&" + name + "=" : ",";
} else if (style == "simple") {
return ",";
} else if (style == "spaceDelimited") {
return (isExplode) ? "&" + name + "=" : " ";
} else if (style == "pipeDelimited") {
return (isExplode) ? "&" + name + "=" : "|";
} else if (style == "deepObject") {
return (isExplode) ? "&" : "none";
} else {
return "none";
}
}
void PFXPetApi::addPet(const PFXPet &body) {
QString fullPath = QString(_serverConfigs["addPet"][_serverIndices.value("addPet")].URL()+"/pet");
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "POST");
{
QByteArray output = body.asJson().toUtf8();
input.request_body.append(output);
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) {
input.headers.insert(keyValueIt->first, keyValueIt->second);
}
#else
for (auto key : _defaultHeaders.keys()) {
input.headers.insert(key, _defaultHeaders[key]);
}
#endif
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::addPetCallback);
connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater);
connect(worker, &QObject::destroyed, this, [this]() {
if (findChildren<PFXHttpRequestWorker*>().count() == 0) {
emit allPendingRequestsCompleted();
}
});
_OauthMethod = 1;
_implicitFlow.link();
_passwordFlow.unlink();
_authFlow.unlink();
_credentialFlow.unlink();
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
auto token = _implicitFlow.getToken(scope.join(" "));
if(token.isValid())
input.headers.insert("Authorization", "Bearer " + token.getToken());
_latestWorker = new PFXHttpRequestWorker(this, _manager);
_latestWorker->setTimeOut(_timeOut);
_latestWorker->setWorkingDirectory(_workingDirectory);
connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::addPetCallback);
connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater);
connect(_latestWorker, &QObject::destroyed, [this](){
if(findChildren<PFXHttpRequestWorker*>().count() == 0){
emit allPendingRequestsCompleted();
}
});
_latestInput = input;
_latestScope = scope;
worker->execute(&input);
}
void PFXPetApi::addPetCallback(PFXHttpRequestWorker *worker) {
QString error_str = worker->error_str;
QNetworkReply::NetworkError error_type = worker->error_type;
if (worker->error_type != QNetworkReply::NoError) {
error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response));
}
worker->deleteLater();
if (worker->error_type == QNetworkReply::NoError) {
emit addPetSignal();
emit addPetSignalFull(worker);
} else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){
connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable()));
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
QString scopeStr = scope.join(" ");
QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog");
//TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like
_implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId");
emit _implicitFlow.authenticationNeeded();
} else {
emit addPetSignalE(error_type, error_str);
emit addPetSignalEFull(worker, error_type, error_str);
}
}
void PFXPetApi::deletePet(const qint64 &pet_id, const ::test_namespace::OptionalParam<QString> &api_key) {
QString fullPath = QString(_serverConfigs["deletePet"][_serverIndices.value("deletePet")].URL()+"/pet/{petId}");
{
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if (pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "petId", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"petId"+pathSuffix : pathPrefix;
fullPath.replace(pet_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id)));
}
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "DELETE");
if (api_key.hasValue())
{
if (!::test_namespace::toStringValue(api_key.value()).isEmpty()) {
input.headers.insert("api_key", ::test_namespace::toStringValue(api_key.value()));
}
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) {
input.headers.insert(keyValueIt->first, keyValueIt->second);
}
#else
for (auto key : _defaultHeaders.keys()) {
input.headers.insert(key, _defaultHeaders[key]);
}
#endif
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::deletePetCallback);
connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater);
connect(worker, &QObject::destroyed, this, [this]() {
if (findChildren<PFXHttpRequestWorker*>().count() == 0) {
emit allPendingRequestsCompleted();
}
});
_OauthMethod = 1;
_implicitFlow.link();
_passwordFlow.unlink();
_authFlow.unlink();
_credentialFlow.unlink();
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
auto token = _implicitFlow.getToken(scope.join(" "));
if(token.isValid())
input.headers.insert("Authorization", "Bearer " + token.getToken());
_latestWorker = new PFXHttpRequestWorker(this, _manager);
_latestWorker->setTimeOut(_timeOut);
_latestWorker->setWorkingDirectory(_workingDirectory);
connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::deletePetCallback);
connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater);
connect(_latestWorker, &QObject::destroyed, [this](){
if(findChildren<PFXHttpRequestWorker*>().count() == 0){
emit allPendingRequestsCompleted();
}
});
_latestInput = input;
_latestScope = scope;
worker->execute(&input);
}
void PFXPetApi::deletePetCallback(PFXHttpRequestWorker *worker) {
QString error_str = worker->error_str;
QNetworkReply::NetworkError error_type = worker->error_type;
if (worker->error_type != QNetworkReply::NoError) {
error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response));
}
worker->deleteLater();
if (worker->error_type == QNetworkReply::NoError) {
emit deletePetSignal();
emit deletePetSignalFull(worker);
} else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){
connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable()));
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
QString scopeStr = scope.join(" ");
QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog");
//TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like
_implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId");
emit _implicitFlow.authenticationNeeded();
} else {
emit deletePetSignalE(error_type, error_str);
emit deletePetSignalEFull(worker, error_type, error_str);
}
}
void PFXPetApi::findPetsByStatus(const QList<QString> &status) {
QString fullPath = QString(_serverConfigs["findPetsByStatus"][_serverIndices.value("findPetsByStatus")].URL()+"/pet/findByStatus");
QString queryPrefix, querySuffix, queryDelimiter, queryStyle;
{
queryStyle = "form";
if (queryStyle == "")
queryStyle = "form";
queryPrefix = getParamStylePrefix(queryStyle);
querySuffix = getParamStyleSuffix(queryStyle);
queryDelimiter = getParamStyleDelimiter(queryStyle, "status", false);
if (status.size() > 0) {
if (QString("csv").indexOf("multi") == 0) {
foreach (QString t, status) {
if (fullPath.indexOf("?") > 0)
fullPath.append(queryPrefix);
else
fullPath.append("?");
fullPath.append("status=").append(::test_namespace::toStringValue(t));
}
} else if (QString("csv").indexOf("ssv") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("status").append(querySuffix);
qint32 count = 0;
foreach (QString t, status) {
if (count > 0) {
fullPath.append((false)? queryDelimiter : QUrl::toPercentEncoding(queryDelimiter));
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("tsv") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("status").append(querySuffix);
qint32 count = 0;
foreach (QString t, status) {
if (count > 0) {
fullPath.append("\t");
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("csv") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("status").append(querySuffix);
qint32 count = 0;
foreach (QString t, status) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("pipes") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("status").append(querySuffix);
qint32 count = 0;
foreach (QString t, status) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("deepObject") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("status").append(querySuffix);
qint32 count = 0;
foreach (QString t, status) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
}
}
}
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "GET");
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) {
input.headers.insert(keyValueIt->first, keyValueIt->second);
}
#else
for (auto key : _defaultHeaders.keys()) {
input.headers.insert(key, _defaultHeaders[key]);
}
#endif
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::findPetsByStatusCallback);
connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater);
connect(worker, &QObject::destroyed, this, [this]() {
if (findChildren<PFXHttpRequestWorker*>().count() == 0) {
emit allPendingRequestsCompleted();
}
});
_OauthMethod = 1;
_implicitFlow.link();
_passwordFlow.unlink();
_authFlow.unlink();
_credentialFlow.unlink();
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
auto token = _implicitFlow.getToken(scope.join(" "));
if(token.isValid())
input.headers.insert("Authorization", "Bearer " + token.getToken());
_latestWorker = new PFXHttpRequestWorker(this, _manager);
_latestWorker->setTimeOut(_timeOut);
_latestWorker->setWorkingDirectory(_workingDirectory);
connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::findPetsByStatusCallback);
connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater);
connect(_latestWorker, &QObject::destroyed, [this](){
if(findChildren<PFXHttpRequestWorker*>().count() == 0){
emit allPendingRequestsCompleted();
}
});
_latestInput = input;
_latestScope = scope;
worker->execute(&input);
}
void PFXPetApi::findPetsByStatusCallback(PFXHttpRequestWorker *worker) {
QString error_str = worker->error_str;
QNetworkReply::NetworkError error_type = worker->error_type;
if (worker->error_type != QNetworkReply::NoError) {
error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response));
}
QList<PFXPet> output;
QString json(worker->response);
QByteArray array(json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonArray jsonArray = doc.array();
foreach (QJsonValue obj, jsonArray) {
PFXPet val;
::test_namespace::fromJsonValue(val, obj);
output.append(val);
}
worker->deleteLater();
if (worker->error_type == QNetworkReply::NoError) {
emit findPetsByStatusSignal(output);
emit findPetsByStatusSignalFull(worker, output);
} else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){
connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable()));
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
QString scopeStr = scope.join(" ");
QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog");
//TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like
_implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId");
emit _implicitFlow.authenticationNeeded();
} else {
emit findPetsByStatusSignalE(output, error_type, error_str);
emit findPetsByStatusSignalEFull(worker, error_type, error_str);
}
}
void PFXPetApi::findPetsByTags(const QList<QString> &tags) {
QString fullPath = QString(_serverConfigs["findPetsByTags"][_serverIndices.value("findPetsByTags")].URL()+"/pet/findByTags");
QString queryPrefix, querySuffix, queryDelimiter, queryStyle;
{
queryStyle = "form";
if (queryStyle == "")
queryStyle = "form";
queryPrefix = getParamStylePrefix(queryStyle);
querySuffix = getParamStyleSuffix(queryStyle);
queryDelimiter = getParamStyleDelimiter(queryStyle, "tags", false);
if (tags.size() > 0) {
if (QString("csv").indexOf("multi") == 0) {
foreach (QString t, tags) {
if (fullPath.indexOf("?") > 0)
fullPath.append(queryPrefix);
else
fullPath.append("?");
fullPath.append("tags=").append(::test_namespace::toStringValue(t));
}
} else if (QString("csv").indexOf("ssv") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix);
qint32 count = 0;
foreach (QString t, tags) {
if (count > 0) {
fullPath.append((false)? queryDelimiter : QUrl::toPercentEncoding(queryDelimiter));
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("tsv") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix);
qint32 count = 0;
foreach (QString t, tags) {
if (count > 0) {
fullPath.append("\t");
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("csv") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix);
qint32 count = 0;
foreach (QString t, tags) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("pipes") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix);
qint32 count = 0;
foreach (QString t, tags) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
} else if (QString("csv").indexOf("deepObject") == 0) {
if (fullPath.indexOf("?") > 0)
fullPath.append("&");
else
fullPath.append("?").append(queryPrefix).append("tags").append(querySuffix);
qint32 count = 0;
foreach (QString t, tags) {
if (count > 0) {
fullPath.append(queryDelimiter);
}
fullPath.append(::test_namespace::toStringValue(t));
count++;
}
}
}
}
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "GET");
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) {
input.headers.insert(keyValueIt->first, keyValueIt->second);
}
#else
for (auto key : _defaultHeaders.keys()) {
input.headers.insert(key, _defaultHeaders[key]);
}
#endif
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::findPetsByTagsCallback);
connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater);
connect(worker, &QObject::destroyed, this, [this]() {
if (findChildren<PFXHttpRequestWorker*>().count() == 0) {
emit allPendingRequestsCompleted();
}
});
_OauthMethod = 1;
_implicitFlow.link();
_passwordFlow.unlink();
_authFlow.unlink();
_credentialFlow.unlink();
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
auto token = _implicitFlow.getToken(scope.join(" "));
if(token.isValid())
input.headers.insert("Authorization", "Bearer " + token.getToken());
_latestWorker = new PFXHttpRequestWorker(this, _manager);
_latestWorker->setTimeOut(_timeOut);
_latestWorker->setWorkingDirectory(_workingDirectory);
connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::findPetsByTagsCallback);
connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater);
connect(_latestWorker, &QObject::destroyed, [this](){
if(findChildren<PFXHttpRequestWorker*>().count() == 0){
emit allPendingRequestsCompleted();
}
});
_latestInput = input;
_latestScope = scope;
worker->execute(&input);
}
void PFXPetApi::findPetsByTagsCallback(PFXHttpRequestWorker *worker) {
QString error_str = worker->error_str;
QNetworkReply::NetworkError error_type = worker->error_type;
if (worker->error_type != QNetworkReply::NoError) {
error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response));
}
QList<PFXPet> output;
QString json(worker->response);
QByteArray array(json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonArray jsonArray = doc.array();
foreach (QJsonValue obj, jsonArray) {
PFXPet val;
::test_namespace::fromJsonValue(val, obj);
output.append(val);
}
worker->deleteLater();
if (worker->error_type == QNetworkReply::NoError) {
emit findPetsByTagsSignal(output);
emit findPetsByTagsSignalFull(worker, output);
} else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){
connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable()));
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
QString scopeStr = scope.join(" ");
QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog");
//TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like
_implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId");
emit _implicitFlow.authenticationNeeded();
} else {
emit findPetsByTagsSignalE(output, error_type, error_str);
emit findPetsByTagsSignalEFull(worker, error_type, error_str);
}
}
void PFXPetApi::getPetById(const qint64 &pet_id) {
QString fullPath = QString(_serverConfigs["getPetById"][_serverIndices.value("getPetById")].URL()+"/pet/{petId}");
if (_apiKeys.contains("api_key")) {
addHeaders("api_key",_apiKeys.find("api_key").value());
}
{
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if (pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "petId", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"petId"+pathSuffix : pathPrefix;
fullPath.replace(pet_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id)));
}
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "GET");
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) {
input.headers.insert(keyValueIt->first, keyValueIt->second);
}
#else
for (auto key : _defaultHeaders.keys()) {
input.headers.insert(key, _defaultHeaders[key]);
}
#endif
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::getPetByIdCallback);
connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater);
connect(worker, &QObject::destroyed, this, [this]() {
if (findChildren<PFXHttpRequestWorker*>().count() == 0) {
emit allPendingRequestsCompleted();
}
});
worker->execute(&input);
}
void PFXPetApi::getPetByIdCallback(PFXHttpRequestWorker *worker) {
QString error_str = worker->error_str;
QNetworkReply::NetworkError error_type = worker->error_type;
if (worker->error_type != QNetworkReply::NoError) {
error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response));
}
PFXPet output(QString(worker->response));
worker->deleteLater();
if (worker->error_type == QNetworkReply::NoError) {
emit getPetByIdSignal(output);
emit getPetByIdSignalFull(worker, output);
} else {
emit getPetByIdSignalE(output, error_type, error_str);
emit getPetByIdSignalEFull(worker, error_type, error_str);
}
}
void PFXPetApi::updatePet(const PFXPet &body) {
QString fullPath = QString(_serverConfigs["updatePet"][_serverIndices.value("updatePet")].URL()+"/pet");
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "PUT");
{
QByteArray output = body.asJson().toUtf8();
input.request_body.append(output);
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) {
input.headers.insert(keyValueIt->first, keyValueIt->second);
}
#else
for (auto key : _defaultHeaders.keys()) {
input.headers.insert(key, _defaultHeaders[key]);
}
#endif
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::updatePetCallback);
connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater);
connect(worker, &QObject::destroyed, this, [this]() {
if (findChildren<PFXHttpRequestWorker*>().count() == 0) {
emit allPendingRequestsCompleted();
}
});
_OauthMethod = 1;
_implicitFlow.link();
_passwordFlow.unlink();
_authFlow.unlink();
_credentialFlow.unlink();
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
auto token = _implicitFlow.getToken(scope.join(" "));
if(token.isValid())
input.headers.insert("Authorization", "Bearer " + token.getToken());
_latestWorker = new PFXHttpRequestWorker(this, _manager);
_latestWorker->setTimeOut(_timeOut);
_latestWorker->setWorkingDirectory(_workingDirectory);
connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::updatePetCallback);
connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater);
connect(_latestWorker, &QObject::destroyed, [this](){
if(findChildren<PFXHttpRequestWorker*>().count() == 0){
emit allPendingRequestsCompleted();
}
});
_latestInput = input;
_latestScope = scope;
worker->execute(&input);
}
void PFXPetApi::updatePetCallback(PFXHttpRequestWorker *worker) {
QString error_str = worker->error_str;
QNetworkReply::NetworkError error_type = worker->error_type;
if (worker->error_type != QNetworkReply::NoError) {
error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response));
}
worker->deleteLater();
if (worker->error_type == QNetworkReply::NoError) {
emit updatePetSignal();
emit updatePetSignalFull(worker);
} else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){
connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable()));
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
QString scopeStr = scope.join(" ");
QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog");
//TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like
_implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId");
emit _implicitFlow.authenticationNeeded();
} else {
emit updatePetSignalE(error_type, error_str);
emit updatePetSignalEFull(worker, error_type, error_str);
}
}
void PFXPetApi::updatePetWithForm(const qint64 &pet_id, const ::test_namespace::OptionalParam<QString> &name, const ::test_namespace::OptionalParam<QString> &status) {
QString fullPath = QString(_serverConfigs["updatePetWithForm"][_serverIndices.value("updatePetWithForm")].URL()+"/pet/{petId}");
{
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if (pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "petId", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"petId"+pathSuffix : pathPrefix;
fullPath.replace(pet_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id)));
}
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "POST");
if (name.hasValue())
{
input.add_var("name", ::test_namespace::toStringValue(name.value()));
}
if (status.hasValue())
{
input.add_var("status", ::test_namespace::toStringValue(status.value()));
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) {
input.headers.insert(keyValueIt->first, keyValueIt->second);
}
#else
for (auto key : _defaultHeaders.keys()) {
input.headers.insert(key, _defaultHeaders[key]);
}
#endif
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::updatePetWithFormCallback);
connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater);
connect(worker, &QObject::destroyed, this, [this]() {
if (findChildren<PFXHttpRequestWorker*>().count() == 0) {
emit allPendingRequestsCompleted();
}
});
_OauthMethod = 1;
_implicitFlow.link();
_passwordFlow.unlink();
_authFlow.unlink();
_credentialFlow.unlink();
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
auto token = _implicitFlow.getToken(scope.join(" "));
if(token.isValid())
input.headers.insert("Authorization", "Bearer " + token.getToken());
_latestWorker = new PFXHttpRequestWorker(this, _manager);
_latestWorker->setTimeOut(_timeOut);
_latestWorker->setWorkingDirectory(_workingDirectory);
connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::updatePetWithFormCallback);
connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater);
connect(_latestWorker, &QObject::destroyed, [this](){
if(findChildren<PFXHttpRequestWorker*>().count() == 0){
emit allPendingRequestsCompleted();
}
});
_latestInput = input;
_latestScope = scope;
worker->execute(&input);
}
void PFXPetApi::updatePetWithFormCallback(PFXHttpRequestWorker *worker) {
QString error_str = worker->error_str;
QNetworkReply::NetworkError error_type = worker->error_type;
if (worker->error_type != QNetworkReply::NoError) {
error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response));
}
worker->deleteLater();
if (worker->error_type == QNetworkReply::NoError) {
emit updatePetWithFormSignal();
emit updatePetWithFormSignalFull(worker);
} else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){
connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable()));
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
QString scopeStr = scope.join(" ");
QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog");
//TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like
_implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId");
emit _implicitFlow.authenticationNeeded();
} else {
emit updatePetWithFormSignalE(error_type, error_str);
emit updatePetWithFormSignalEFull(worker, error_type, error_str);
}
}
void PFXPetApi::uploadFile(const qint64 &pet_id, const ::test_namespace::OptionalParam<QString> &additional_metadata, const ::test_namespace::OptionalParam<PFXHttpFileElement> &file) {
QString fullPath = QString(_serverConfigs["uploadFile"][_serverIndices.value("uploadFile")].URL()+"/pet/{petId}/uploadImage");
{
QString pet_idPathParam("{");
pet_idPathParam.append("petId").append("}");
QString pathPrefix, pathSuffix, pathDelimiter;
QString pathStyle = "";
if (pathStyle == "")
pathStyle = "simple";
pathPrefix = getParamStylePrefix(pathStyle);
pathSuffix = getParamStyleSuffix(pathStyle);
pathDelimiter = getParamStyleDelimiter(pathStyle, "petId", false);
QString paramString = (pathStyle == "matrix") ? pathPrefix+"petId"+pathSuffix : pathPrefix;
fullPath.replace(pet_idPathParam, paramString+QUrl::toPercentEncoding(::test_namespace::toStringValue(pet_id)));
}
PFXHttpRequestWorker *worker = new PFXHttpRequestWorker(this, _manager);
worker->setTimeOut(_timeOut);
worker->setWorkingDirectory(_workingDirectory);
PFXHttpRequestInput input(fullPath, "POST");
if (additional_metadata.hasValue())
{
input.add_var("additionalMetadata", ::test_namespace::toStringValue(additional_metadata.value()));
}
if (file.hasValue())
{
input.add_file("file", file.value().local_filename, file.value().request_filename, file.value().mime_type);
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
for (auto keyValueIt = _defaultHeaders.keyValueBegin(); keyValueIt != _defaultHeaders.keyValueEnd(); keyValueIt++) {
input.headers.insert(keyValueIt->first, keyValueIt->second);
}
#else
for (auto key : _defaultHeaders.keys()) {
input.headers.insert(key, _defaultHeaders[key]);
}
#endif
connect(worker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::uploadFileCallback);
connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater);
connect(worker, &QObject::destroyed, this, [this]() {
if (findChildren<PFXHttpRequestWorker*>().count() == 0) {
emit allPendingRequestsCompleted();
}
});
_OauthMethod = 1;
_implicitFlow.link();
_passwordFlow.unlink();
_authFlow.unlink();
_credentialFlow.unlink();
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
auto token = _implicitFlow.getToken(scope.join(" "));
if(token.isValid())
input.headers.insert("Authorization", "Bearer " + token.getToken());
_latestWorker = new PFXHttpRequestWorker(this, _manager);
_latestWorker->setTimeOut(_timeOut);
_latestWorker->setWorkingDirectory(_workingDirectory);
connect(_latestWorker, &PFXHttpRequestWorker::on_execution_finished, this, &PFXPetApi::uploadFileCallback);
connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater);
connect(_latestWorker, &QObject::destroyed, [this](){
if(findChildren<PFXHttpRequestWorker*>().count() == 0){
emit allPendingRequestsCompleted();
}
});
_latestInput = input;
_latestScope = scope;
worker->execute(&input);
}
void PFXPetApi::uploadFileCallback(PFXHttpRequestWorker *worker) {
QString error_str = worker->error_str;
QNetworkReply::NetworkError error_type = worker->error_type;
if (worker->error_type != QNetworkReply::NoError) {
error_str = QString("%1, %2").arg(worker->error_str, QString(worker->response));
}
PFXApiResponse output(QString(worker->response));
worker->deleteLater();
if (worker->error_type == QNetworkReply::NoError) {
emit uploadFileSignal(output);
emit uploadFileSignalFull(worker, output);
} else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){
connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable()));
QStringList scope;
scope.append("write:pets");
scope.append("read:pets");
QString scopeStr = scope.join(" ");
QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog");
//TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like
_implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId");
emit _implicitFlow.authenticationNeeded();
} else {
emit uploadFileSignalE(output, error_type, error_str);
emit uploadFileSignalEFull(worker, error_type, error_str);
}
}
void PFXPetApi::tokenAvailable(){
oauthToken token;
switch (_OauthMethod) {
case 1: //implicit flow
token = _implicitFlow.getToken(_latestScope.join(" "));
if(token.isValid()){
_latestInput.headers.insert("Authorization", "Bearer " + token.getToken());
_latestWorker->execute(&_latestInput);
}else{
_implicitFlow.removeToken(_latestScope.join(" "));
qDebug() << "Could not retreive a valid token";
}
break;
case 2: //authorization flow
token = _authFlow.getToken(_latestScope.join(" "));
if(token.isValid()){
_latestInput.headers.insert("Authorization", "Bearer " + token.getToken());
_latestWorker->execute(&_latestInput);
}else{
_authFlow.removeToken(_latestScope.join(" "));
qDebug() << "Could not retreive a valid token";
}
break;
case 3: //client credentials flow
token = _credentialFlow.getToken(_latestScope.join(" "));
if(token.isValid()){
_latestInput.headers.insert("Authorization", "Bearer " + token.getToken());
_latestWorker->execute(&_latestInput);
}else{
_credentialFlow.removeToken(_latestScope.join(" "));
qDebug() << "Could not retreive a valid token";
}
break;
case 4: //resource owner password flow
token = _passwordFlow.getToken(_latestScope.join(" "));
if(token.isValid()){
_latestInput.headers.insert("Authorization", "Bearer " + token.getToken());
_latestWorker->execute(&_latestInput);
}else{
_credentialFlow.removeToken(_latestScope.join(" "));
qDebug() << "Could not retreive a valid token";
}
break;
default:
qDebug() << "No Oauth method set!";
break;
}
}
} // namespace test_namespace