From c84059b4aa26f92053192de46a6b1508ed8d107e Mon Sep 17 00:00:00 2001 From: Jorge Miguel Lobo Escalona Date: Tue, 1 Feb 2022 16:02:03 +0100 Subject: [PATCH] F #5704: Refactor FireEdge API (#1730) (cherry picked from commit 7511e1304a1080601ec9602b8539fdd4b118804b) --- .../features/One/application/services.js | 2 +- .../One/applicationTemplate/services.js | 2 +- .../client/features/One/provider/services.js | 2 +- .../client/features/One/provision/services.js | 2 +- src/fireedge/src/server/index.js | 3 +- .../params.js => routes/api/2fa/basepath.js} | 3 +- .../src/server/routes/api/2fa/functions.js | 26 +- .../src/server/routes/api/2fa/index.js | 25 +- .../src/server/routes/api/2fa/routes.js | 50 ++- .../{vm/string-routes.js => auth/basepath.js} | 8 +- .../src/server/routes/api/auth/functions.js | 18 +- .../src/server/routes/api/auth/index.js | 17 +- .../src/server/routes/api/auth/routes.js | 44 +- .../src/server/routes/api/auth/utils.js | 28 +- .../string-routes.js => files/basepath.js} | 8 +- .../src/server/routes/api/files/functions.js | 17 +- .../src/server/routes/api/files/index.js | 40 +- .../src/server/routes/api/files/routes.js | 107 +++-- src/fireedge/src/server/routes/api/index.js | 89 +++- .../basepath.js} | 8 +- .../server/routes/api/marketapp/functions.js | 19 +- .../src/server/routes/api/marketapp/index.js | 38 +- .../src/server/routes/api/marketapp/routes.js | 112 +++-- .../routes/api/marketapp/string-routes.js | 23 - .../oneflow/{string-routes.js => basepath.js} | 4 +- .../src/server/routes/api/oneflow/index.js | 116 ++++- .../routes/api/oneflow/service/functions.js | 13 +- .../routes/api/oneflow/service/index.js | 102 ----- .../routes/api/oneflow/service/routes.js | 155 +++++++ .../routes/api/oneflow/template/functions.js | 13 +- .../routes/api/oneflow/template/index.js | 77 ---- .../routes/api/oneflow/template/routes.js | 101 +++++ .../{string-routes.js => basepath.js} | 4 +- .../server/routes/api/oneprovision/index.js | 272 ++++++++++-- .../api/oneprovision/provider/functions.js | 20 +- .../provider/{index.js => routes.js} | 104 +++-- .../api/oneprovision/provision/functions.js | 20 +- .../api/oneprovision/provision/index.js | 230 ---------- .../api/oneprovision/provision/routes.js | 397 ++++++++++++++++++ .../api/oneprovision/template/functions.js | 9 +- .../routes/api/oneprovision/template/index.js | 74 ---- .../api/oneprovision/template/routes.js | 100 +++++ .../server/routes/api/sunstone/basepath.js | 17 + .../server/routes/api/sunstone/functions.js | 11 +- .../src/server/routes/api/sunstone/index.js | 22 +- .../src/server/routes/api/sunstone/routes.js | 39 +- .../routes/api/sunstone/string-routes.js | 23 - .../src/server/routes/api/vcenter/basepath.js | 17 + .../server/routes/api/vcenter/functions.js | 15 +- .../src/server/routes/api/vcenter/index.js | 45 +- .../src/server/routes/api/vcenter/routes.js | 136 +++--- .../routes/api/vcenter/string-routes.js | 23 - .../src/server/routes/api/vm/basepath.js | 17 + .../src/server/routes/api/vm/functions.js | 16 +- .../src/server/routes/api/vm/index.js | 17 +- .../src/server/routes/api/vm/routes.js | 37 +- .../src/server/routes/api/zendesk/basepath.js | 17 + .../server/routes/api/zendesk/functions.js | 44 +- .../src/server/routes/api/zendesk/index.js | 45 +- .../src/server/routes/api/zendesk/routes.js | 105 ++--- .../routes/api/zendesk/string-routes.js | 23 - .../src/server/routes/entrypoints/Api.js | 221 ---------- .../routes/entrypoints/Api/functions.js | 103 +++++ .../Api/index.js} | 44 +- .../routes/entrypoints/Api/middlawares.js | 163 +++++++ .../server/routes/entrypoints/Api/xmlrpc.js | 213 ++++++++++ .../src/server/routes/entrypoints/index.js | 6 +- .../entrypoints/middlewares/api/index.js | 257 ------------ .../routes/entrypoints/middlewares/index.js | 39 -- .../src/server/utils/constants/index.js | 2 - src/fireedge/src/server/utils/index.js | 122 ------ src/fireedge/src/server/utils/jwt.js | 2 +- src/fireedge/src/server/utils/logger.js | 3 +- src/fireedge/src/server/utils/opennebula.js | 118 ++---- src/fireedge/src/server/utils/server.js | 226 +--------- 75 files changed, 2495 insertions(+), 2195 deletions(-) rename src/fireedge/src/server/{utils/constants/params.js => routes/api/2fa/basepath.js} (94%) rename src/fireedge/src/server/routes/api/{vm/string-routes.js => auth/basepath.js} (94%) rename src/fireedge/src/server/routes/api/{2fa/string-routes.js => files/basepath.js} (94%) rename src/fireedge/src/server/routes/api/{auth/string-routes.js => marketapp/basepath.js} (94%) delete mode 100644 src/fireedge/src/server/routes/api/marketapp/string-routes.js rename src/fireedge/src/server/routes/api/oneflow/{string-routes.js => basepath.js} (96%) delete mode 100644 src/fireedge/src/server/routes/api/oneflow/service/index.js create mode 100644 src/fireedge/src/server/routes/api/oneflow/service/routes.js delete mode 100644 src/fireedge/src/server/routes/api/oneflow/template/index.js create mode 100644 src/fireedge/src/server/routes/api/oneflow/template/routes.js rename src/fireedge/src/server/routes/api/oneprovision/{string-routes.js => basepath.js} (96%) rename src/fireedge/src/server/routes/api/oneprovision/provider/{index.js => routes.js} (50%) delete mode 100644 src/fireedge/src/server/routes/api/oneprovision/provision/index.js create mode 100644 src/fireedge/src/server/routes/api/oneprovision/provision/routes.js delete mode 100644 src/fireedge/src/server/routes/api/oneprovision/template/index.js create mode 100644 src/fireedge/src/server/routes/api/oneprovision/template/routes.js create mode 100644 src/fireedge/src/server/routes/api/sunstone/basepath.js delete mode 100644 src/fireedge/src/server/routes/api/sunstone/string-routes.js create mode 100644 src/fireedge/src/server/routes/api/vcenter/basepath.js delete mode 100644 src/fireedge/src/server/routes/api/vcenter/string-routes.js create mode 100644 src/fireedge/src/server/routes/api/vm/basepath.js create mode 100644 src/fireedge/src/server/routes/api/zendesk/basepath.js delete mode 100644 src/fireedge/src/server/routes/api/zendesk/string-routes.js delete mode 100644 src/fireedge/src/server/routes/entrypoints/Api.js create mode 100644 src/fireedge/src/server/routes/entrypoints/Api/functions.js rename src/fireedge/src/server/routes/{api/files/string-routes.js => entrypoints/Api/index.js} (57%) create mode 100644 src/fireedge/src/server/routes/entrypoints/Api/middlawares.js create mode 100644 src/fireedge/src/server/routes/entrypoints/Api/xmlrpc.js delete mode 100644 src/fireedge/src/server/routes/entrypoints/middlewares/api/index.js delete mode 100644 src/fireedge/src/server/routes/entrypoints/middlewares/index.js delete mode 100644 src/fireedge/src/server/utils/index.js diff --git a/src/fireedge/src/client/features/One/application/services.js b/src/fireedge/src/client/features/One/application/services.js index c225c3e630..f8efa28cc3 100644 --- a/src/fireedge/src/client/features/One/application/services.js +++ b/src/fireedge/src/client/features/One/application/services.js @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * * limitations under the License. * * ------------------------------------------------------------------------- */ -import { SERVICE } from 'server/routes/api/oneflow/string-routes' +import { SERVICE } from 'server/routes/api/oneflow/basepath' import { httpCodes } from 'server/utils/constants' import { RestClient } from 'client/utils' diff --git a/src/fireedge/src/client/features/One/applicationTemplate/services.js b/src/fireedge/src/client/features/One/applicationTemplate/services.js index 03276ed4c1..b8c4141602 100644 --- a/src/fireedge/src/client/features/One/applicationTemplate/services.js +++ b/src/fireedge/src/client/features/One/applicationTemplate/services.js @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * * limitations under the License. * * ------------------------------------------------------------------------- */ -import { SERVICE_TEMPLATE } from 'server/routes/api/oneflow/string-routes' +import { SERVICE_TEMPLATE } from 'server/routes/api/oneflow/basepath' import { httpCodes, defaults } from 'server/utils/constants' import { RestClient } from 'client/utils' diff --git a/src/fireedge/src/client/features/One/provider/services.js b/src/fireedge/src/client/features/One/provider/services.js index af09f16ca5..657f029fc3 100644 --- a/src/fireedge/src/client/features/One/provider/services.js +++ b/src/fireedge/src/client/features/One/provider/services.js @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * * limitations under the License. * * ------------------------------------------------------------------------- */ -import { PROVIDER } from 'server/routes/api/oneprovision/string-routes' +import { PROVIDER } from 'server/routes/api/oneprovision/basepath' import { httpCodes, defaults } from 'server/utils/constants' import { RestClient } from 'client/utils' diff --git a/src/fireedge/src/client/features/One/provision/services.js b/src/fireedge/src/client/features/One/provision/services.js index 648318e462..5934e8d622 100644 --- a/src/fireedge/src/client/features/One/provision/services.js +++ b/src/fireedge/src/client/features/One/provision/services.js @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * * limitations under the License. * * ------------------------------------------------------------------------- */ -import { PROVISION } from 'server/routes/api/oneprovision/string-routes' +import { PROVISION } from 'server/routes/api/oneprovision/basepath' import { httpCodes, defaults } from 'server/utils/constants' import { RestClient } from 'client/utils' diff --git a/src/fireedge/src/server/index.js b/src/fireedge/src/server/index.js index b468d64df2..4307daa59f 100644 --- a/src/fireedge/src/server/index.js +++ b/src/fireedge/src/server/index.js @@ -32,7 +32,8 @@ import { import { websockets } from './routes/websockets' import { guacamole } from './routes/websockets/guacamole' import { vmrc } from './routes/websockets/vmrc' -import { getFireedgeConfig, messageTerminal } from './utils' +import { getFireedgeConfig } from './utils/yml' +import { messageTerminal } from './utils/general' import { defaultAppName, defaultApps, diff --git a/src/fireedge/src/server/utils/constants/params.js b/src/fireedge/src/server/routes/api/2fa/basepath.js similarity index 94% rename from src/fireedge/src/server/utils/constants/params.js rename to src/fireedge/src/server/routes/api/2fa/basepath.js index ad06a7c6f4..f8cff1b5db 100644 --- a/src/fireedge/src/server/utils/constants/params.js +++ b/src/fireedge/src/server/routes/api/2fa/basepath.js @@ -14,5 +14,4 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const params = ['method', 'id', 'id2'] -module.exports = params +module.exports = 'tfa' diff --git a/src/fireedge/src/server/routes/api/2fa/functions.js b/src/fireedge/src/server/routes/api/2fa/functions.js index f73ca45bbb..0b65ac34cd 100644 --- a/src/fireedge/src/server/routes/api/2fa/functions.js +++ b/src/fireedge/src/server/routes/api/2fa/functions.js @@ -16,14 +16,7 @@ const speakeasy = require('speakeasy') const qrcode = require('qrcode') - -const { - httpMethod, - default2FAIssuer, - defaultEmptyFunction, - default2FAOpennebulaVar, - default2FAOpennebulaTmpVar, -} = require('server/utils/constants/defaults') +const { defaults, httpCodes } = require('server/utils/constants') const { httpResponse } = require('server/utils/server') const { getFireedgeConfig } = require('server/utils/yml') const { check2Fa } = require('server/utils/jwt') @@ -36,15 +29,16 @@ const { // user config const appConfig = getFireedgeConfig() -const twoFactorAuthIssuer = appConfig.TWO_FACTOR_AUTH_ISSUER || default2FAIssuer - -const { GET } = httpMethod - const { - ok, - unauthorized, - internalServerError, -} = require('server/utils/constants/http-codes') + httpMethod, + default2FAIssuer, + defaultEmptyFunction, + default2FAOpennebulaVar, + default2FAOpennebulaTmpVar, +} = defaults +const { ok, unauthorized, internalServerError } = httpCodes +const { GET } = httpMethod +const twoFactorAuthIssuer = appConfig.TWO_FACTOR_AUTH_ISSUER || default2FAIssuer /** * Get information for opennebula authenticated user. diff --git a/src/fireedge/src/server/routes/api/2fa/index.js b/src/fireedge/src/server/routes/api/2fa/index.js index cbd7c6e8dc..910ee8bcbc 100644 --- a/src/fireedge/src/server/routes/api/2fa/index.js +++ b/src/fireedge/src/server/routes/api/2fa/index.js @@ -14,13 +14,22 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const { setApiRoutes } = require('server/utils/server') -const { routes: tfaRoutes } = require('server/routes/api/2fa/routes') -const { TFA } = require('server/routes/api/2fa/string-routes') +const { Actions, Commands } = require('server/routes/api/2fa/routes') +const { setup, qr, del } = require('server/routes/api/2fa/functions') -const functionRoutes = { - private: setApiRoutes(tfaRoutes, TFA), - public: [], -} +const { TFA_SETUP, TFA_QR, TFA_DELETE } = Actions -module.exports = functionRoutes +module.exports = [ + { + ...Commands[TFA_SETUP], + action: setup, + }, + { + ...Commands[TFA_QR], + action: qr, + }, + { + ...Commands[TFA_DELETE], + action: del, + }, +] diff --git a/src/fireedge/src/server/routes/api/2fa/routes.js b/src/fireedge/src/server/routes/api/2fa/routes.js index 918a4f2d81..58725c9ca8 100644 --- a/src/fireedge/src/server/routes/api/2fa/routes.js +++ b/src/fireedge/src/server/routes/api/2fa/routes.js @@ -18,36 +18,42 @@ const { httpMethod, from: fromData, } = require('server/utils/constants/defaults') -const { setup, qr, del } = require('server/routes/api/2fa/functions') -const { POST, DELETE, GET } = httpMethod +const TFA = require('server/routes/api/2fa/basepath') -const routes = { - [POST]: { - null: { - action: setup, +const { POST, DELETE, GET } = httpMethod +const basepath = `/${TFA}` +const TFA_SETUP = 'tfa.setup' +const TFA_QR = 'tfa.qr' +const TFA_DELETE = 'tfa.delete' + +const Actions = { + TFA_SETUP, + TFA_QR, + TFA_DELETE, +} + +module.exports = { + Actions, + Commands: { + [TFA_SETUP]: { + path: `${basepath}/`, + httpMethod: POST, + auth: true, params: { token: { from: fromData.postBody, - name: 'token', }, }, }, - }, - [GET]: { - null: { - action: qr, - params: {}, + [TFA_QR]: { + path: `${basepath}/`, + httpMethod: GET, + auth: true, }, - }, - [DELETE]: { - null: { - action: del, - params: {}, + [TFA_DELETE]: { + path: `${basepath}/`, + httpMethod: DELETE, + auth: true, }, }, } - -const authApi = { - routes, -} -module.exports = authApi diff --git a/src/fireedge/src/server/routes/api/vm/string-routes.js b/src/fireedge/src/server/routes/api/auth/basepath.js similarity index 94% rename from src/fireedge/src/server/routes/api/vm/string-routes.js rename to src/fireedge/src/server/routes/api/auth/basepath.js index acce84223f..a3c0715deb 100644 --- a/src/fireedge/src/server/routes/api/vm/string-routes.js +++ b/src/fireedge/src/server/routes/api/auth/basepath.js @@ -14,10 +14,4 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const VM = 'vm' - -const Actions = { - VM, -} - -module.exports = Actions +module.exports = 'auth' diff --git a/src/fireedge/src/server/routes/api/auth/functions.js b/src/fireedge/src/server/routes/api/auth/functions.js index 335521ee2a..3bcd08ff06 100644 --- a/src/fireedge/src/server/routes/api/auth/functions.js +++ b/src/fireedge/src/server/routes/api/auth/functions.js @@ -29,24 +29,20 @@ const { updaterResponse, } = require('server/routes/api/auth/utils') -const { - internalServerError, - unauthorized, -} = require('server/utils/constants/http-codes') +const { defaults, httpCodes } = require('server/utils/constants') const { Actions } = require('server/utils/constants/commands/user') -const { - httpMethod, - defaultEmptyFunction, -} = require('server/utils/constants/defaults') - -const { GET } = httpMethod - const { getDefaultParamsOfOpennebulaCommand, } = require('server/utils/opennebula') const { writeInLogger } = require('server/utils/logger') +const { internalServerError, unauthorized } = httpCodes + +const { httpMethod, defaultEmptyFunction } = defaults + +const { GET } = httpMethod + /** * Login user. * diff --git a/src/fireedge/src/server/routes/api/auth/index.js b/src/fireedge/src/server/routes/api/auth/index.js index f3f4b02a28..2bd71bf2e9 100644 --- a/src/fireedge/src/server/routes/api/auth/index.js +++ b/src/fireedge/src/server/routes/api/auth/index.js @@ -14,13 +14,14 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const { setApiRoutes } = require('server/utils/server') -const { routes: authRoutes } = require('server/routes/api/auth/routes') -const { AUTH } = require('server/routes/api/auth/string-routes') +const { Actions, Commands } = require('server/routes/api/auth/routes') +const { auth } = require('server/routes/api/auth/functions') -const functionRoutes = { - private: [], - public: setApiRoutes(authRoutes, AUTH), -} +const { AUTHENTICATION } = Actions -module.exports = functionRoutes +module.exports = [ + { + ...Commands[AUTHENTICATION], + action: auth, + }, +] diff --git a/src/fireedge/src/server/routes/api/auth/routes.js b/src/fireedge/src/server/routes/api/auth/routes.js index 83c896309e..d4a9aad4fe 100644 --- a/src/fireedge/src/server/routes/api/auth/routes.js +++ b/src/fireedge/src/server/routes/api/auth/routes.js @@ -18,40 +18,42 @@ const { httpMethod, from: fromData, } = require('server/utils/constants/defaults') -const { auth } = require('server/routes/api/auth/functions') -const { POST } = httpMethod -const routes = { - [POST]: { - null: { - action: auth, +const AUTH = require('server/routes/api/auth/basepath') + +const { POST } = httpMethod +const { postBody } = fromData +const basepath = `/${AUTH}` +const AUTHENTICATION = 'authentication' + +const Actions = { + AUTHENTICATION, +} + +module.exports = { + Actions, + Commands: { + [AUTHENTICATION]: { + path: `${basepath}/`, + httpMethod: POST, + auth: false, params: { user: { - from: fromData.postBody, - name: 'user', + from: postBody, }, token: { - from: fromData.postBody, - name: 'token', + from: postBody, }, type: { - from: fromData.postBody, - name: 'type', + from: postBody, }, token2fa: { - from: fromData.postBody, - name: 'token2fa', + from: postBody, }, remember: { - from: fromData.postBody, - name: 'remember', + from: postBody, }, }, }, }, } - -const authApi = { - routes, -} -module.exports = authApi diff --git a/src/fireedge/src/server/routes/api/auth/utils.js b/src/fireedge/src/server/routes/api/auth/utils.js index 427b8d8881..cae72d3dd9 100644 --- a/src/fireedge/src/server/routes/api/auth/utils.js +++ b/src/fireedge/src/server/routes/api/auth/utils.js @@ -20,22 +20,8 @@ const { parse } = require('url') const { global, Array } = require('window-or-global') const { Actions: ActionUsers } = require('server/utils/constants/commands/user') const { Actions: ActionZones } = require('server/utils/constants/commands/zone') -const { - httpMethod, - defaultSessionExpiration, - default2FAOpennebulaVar, - defaultNamespace, - defaultEmptyFunction, - defaultSessionLimitExpiration, - defaultRememberSessionExpiration, -} = require('server/utils/constants/defaults') +const { defaults, httpCodes } = require('server/utils/constants') const { getFireedgeConfig } = require('server/utils/yml') -const { - ok, - unauthorized, - accepted, - internalServerError, -} = require('server/utils/constants/http-codes') const { createJWT, check2Fa } = require('server/utils/jwt') const { httpResponse, @@ -47,6 +33,18 @@ const { getDefaultParamsOfOpennebulaCommand, } = require('server/utils/opennebula') +const { + httpMethod, + defaultSessionExpiration, + default2FAOpennebulaVar, + defaultNamespace, + defaultEmptyFunction, + defaultSessionLimitExpiration, + defaultRememberSessionExpiration, +} = defaults + +const { ok, unauthorized, accepted, internalServerError } = httpCodes + const appConfig = getFireedgeConfig() const namespace = appConfig.namespace || defaultNamespace diff --git a/src/fireedge/src/server/routes/api/2fa/string-routes.js b/src/fireedge/src/server/routes/api/files/basepath.js similarity index 94% rename from src/fireedge/src/server/routes/api/2fa/string-routes.js rename to src/fireedge/src/server/routes/api/files/basepath.js index 22edf7a4a8..d18b89945e 100644 --- a/src/fireedge/src/server/routes/api/2fa/string-routes.js +++ b/src/fireedge/src/server/routes/api/files/basepath.js @@ -14,10 +14,4 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const TFA = 'tfa' - -const Actions = { - TFA, -} - -module.exports = Actions +module.exports = 'files' diff --git a/src/fireedge/src/server/routes/api/files/functions.js b/src/fireedge/src/server/routes/api/files/functions.js index b3a2669e04..8836c6908c 100644 --- a/src/fireedge/src/server/routes/api/files/functions.js +++ b/src/fireedge/src/server/routes/api/files/functions.js @@ -18,14 +18,10 @@ const { global } = require('window-or-global') const { jwtDecode } = require('server/utils/jwt') const { existsSync, mkdirsSync, moveSync } = require('fs-extra') -const { defaultEmptyFunction } = require('server/utils/constants/defaults') +const { defaults, httpCodes } = require('server/utils/constants') -const { - ok, - internalServerError, - badRequest, -} = require('server/utils/constants/http-codes') const { Actions: ActionUser } = require('server/utils/constants/commands/user') + const { httpResponse, checkValidApp, @@ -34,6 +30,10 @@ const { removeFile, } = require('server/utils/server') +const { defaultEmptyFunction } = defaults + +const { ok, internalServerError, badRequest } = httpCodes + const httpBadRequest = httpResponse(badRequest, '', '') const groupAdministrator = ['0'] @@ -154,7 +154,7 @@ const upload = ( userData = {}, oneConnection = defaultEmptyFunction ) => { - const { app, files, root } = params + const { app, files, public: publicFile } = params const { id, user, password } = userData if ( global.paths.CPI && @@ -170,7 +170,8 @@ const upload = ( oneConnect, id, (admin = false) => { - const pathUserData = root && admin ? `${app}` : `${app}${sep}${id}` + const pathUserData = + publicFile && admin ? `${app}` : `${app}${sep}${id}` const pathUser = `${global.paths.CPI}${sep}${pathUserData}` if (!existsSync(pathUser)) { mkdirsSync(pathUser) diff --git a/src/fireedge/src/server/routes/api/files/index.js b/src/fireedge/src/server/routes/api/files/index.js index 5617341034..8754596be6 100644 --- a/src/fireedge/src/server/routes/api/files/index.js +++ b/src/fireedge/src/server/routes/api/files/index.js @@ -14,16 +14,36 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const { setApiRoutes } = require('server/utils/server') +const { Actions, Commands } = require('server/routes/api/files/routes') const { - privateRoutes: filePrivateRoutes, - publicRoutes: filePublicRoutes, -} = require('server/routes/api/files/routes') -const { FILES } = require('server/routes/api/files/string-routes') + show, + list, + upload, + update, + deleteFile, +} = require('server/routes/api/files/functions') -const functionRoutes = { - private: setApiRoutes(filePrivateRoutes, FILES), - public: setApiRoutes(filePublicRoutes, FILES), -} +const { FILE_SHOW, FILE_LIST, FILE_UPLOAD, FILE_UPDATE, FILE_DELETE } = Actions -module.exports = functionRoutes +module.exports = [ + { + ...Commands[FILE_SHOW], + action: show, + }, + { + ...Commands[FILE_LIST], + action: list, + }, + { + ...Commands[FILE_UPLOAD], + action: upload, + }, + { + ...Commands[FILE_UPDATE], + action: update, + }, + { + ...Commands[FILE_DELETE], + action: deleteFile, + }, +] diff --git a/src/fireedge/src/server/routes/api/files/routes.js b/src/fireedge/src/server/routes/api/files/routes.js index d4b5ae8411..8f065ec1ef 100644 --- a/src/fireedge/src/server/routes/api/files/routes.js +++ b/src/fireedge/src/server/routes/api/files/routes.js @@ -18,98 +18,93 @@ const { from: fromData, httpMethod, } = require('server/utils/constants/defaults') -const { - show, - list, - upload, - update, - deleteFile, -} = require('server/routes/api/files/functions') -const { GET, POST, PUT, DELETE } = httpMethod +const FILES = require('server/routes/api/files/basepath') -const publicRoutes = { - [GET]: { - null: { - action: show, +const { GET, POST, PUT, DELETE } = httpMethod +const basepath = `/${FILES}` +const { query } = fromData + +const FILE_SHOW = 'file.show' +const FILE_LIST = 'file.list' +const FILE_UPLOAD = 'file.upload' +const FILE_UPDATE = 'file.update' +const FILE_DELETE = 'file.delete' + +const Actions = { + FILE_SHOW, + FILE_LIST, + FILE_UPLOAD, + FILE_UPDATE, + FILE_DELETE, +} + +module.exports = { + Actions, + Commands: { + [FILE_SHOW]: { + path: `${basepath}/show`, + httpMethod: GET, + auth: false, params: { file: { - from: fromData.query, - name: 'file', + from: query, }, token: { - from: fromData.query, - name: 'token', + from: query, }, app: { - from: fromData.query, - name: 'app', + from: query, }, }, }, - }, -} - -const privateRoutes = { - [GET]: { - null: { - action: list, + [FILE_LIST]: { + path: `${basepath}`, + httpMethod: GET, + auth: true, params: { app: { - from: fromData.query, - name: 'app', + from: query, }, }, }, - }, - [POST]: { - null: { - action: upload, + [FILE_UPLOAD]: { + path: `${basepath}`, + httpMethod: POST, + auth: true, params: { app: { - from: fromData.query, - name: 'app', + from: query, }, files: { from: 'files', - name: 'files', }, - root: { - from: fromData.query, - name: 'public', + public: { + from: query, }, }, }, - }, - [PUT]: { - null: { - action: update, + [FILE_UPDATE]: { + path: `${basepath}`, + httpMethod: PUT, + auth: true, params: { name: { - from: fromData.query, - name: 'name', + from: query, }, files: { from: 'files', - name: 'files', }, }, }, - }, - [DELETE]: { - null: { - action: deleteFile, + [FILE_DELETE]: { + path: `${basepath}`, + httpMethod: DELETE, + auth: true, params: { file: { - from: fromData.query, - name: 'file', + from: query, }, }, }, }, } - -const fileApi = { - publicRoutes, - privateRoutes, -} -module.exports = fileApi diff --git a/src/fireedge/src/server/routes/api/index.js b/src/fireedge/src/server/routes/api/index.js index ae96eb2fdd..9aab4a04f7 100644 --- a/src/fireedge/src/server/routes/api/index.js +++ b/src/fireedge/src/server/routes/api/index.js @@ -14,9 +14,13 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ +const multer = require('multer') const { messageTerminal } = require('server/utils/general') -const { getRouteForOpennebulaCommand } = require('server/utils/opennebula') +const { getRequestParameters, getRequestFiles } = require('server/utils/server') const { defaultConfigErrorMessage } = require('server/utils/constants/defaults') +const { writeInLogger } = require('server/utils/logger') + +const upload = multer({ dest: '/tmp' }) const routes = [ '2fa', @@ -31,19 +35,81 @@ const routes = [ 'sunstone', ] -const filesDataPrivate = [] -const filesDataPublic = [] +const serverRoutes = [] + +/** + * Parse files for actions. + * + * @param {Array} files - files + * @returns {Array} files + */ +const parseFiles = (files = []) => { + let rtn + if (files && Array.isArray(files)) { + rtn = {} + files.forEach((file) => { + if (file.fieldname) { + rtn[file.fieldname] + ? rtn[file.fieldname].push(file) + : (rtn[file.fieldname] = [file]) + } + }) + } + + return rtn +} routes.forEach((file) => { try { // eslint-disable-next-line global-require const fileInfo = require(`./${file}`) - if (fileInfo.private && fileInfo.private.length) { - filesDataPrivate.push(...fileInfo.private) - } - if (fileInfo.public && fileInfo.public.length) { - filesDataPublic.push(...fileInfo.public) + if (fileInfo && Array.isArray(fileInfo) && fileInfo.length) { + serverRoutes.push( + ...fileInfo.map((route) => { + const { action, params } = route + if (action) { + route.action = (req, res, next, oneConnection, oneUser) => { + const { serverDataSource } = req + const uploadFiles = getRequestFiles(params) + if (!(uploadFiles && uploadFiles.length)) { + return action( + res, + next, + getRequestParameters(params, serverDataSource), + oneUser, + oneConnection + ) + } + + /** Request with files */ + const files = upload.array(uploadFiles) + files(req, res, (err) => { + if (err) { + const errorData = (err && err.message) || '' + writeInLogger(errorData) + messageTerminal({ + color: 'red', + message: 'Error: %s', + error: errorData, + }) + } + serverDataSource.files = parseFiles(req && req.files) + + return action( + res, + next, + getRequestParameters(params, serverDataSource), + oneUser, + oneConnection + ) + }) + } + } + + return route + }) + ) } } catch (error) { if (error instanceof Error && error.code === 'MODULE_NOT_FOUND') { @@ -54,9 +120,4 @@ routes.forEach((file) => { } }) -const opennebulaActions = getRouteForOpennebulaCommand() - -module.exports = { - private: [...opennebulaActions, ...filesDataPrivate], - public: [...filesDataPublic], -} +module.exports = serverRoutes diff --git a/src/fireedge/src/server/routes/api/auth/string-routes.js b/src/fireedge/src/server/routes/api/marketapp/basepath.js similarity index 94% rename from src/fireedge/src/server/routes/api/auth/string-routes.js rename to src/fireedge/src/server/routes/api/marketapp/basepath.js index 4d0a613c13..87d527994f 100644 --- a/src/fireedge/src/server/routes/api/auth/string-routes.js +++ b/src/fireedge/src/server/routes/api/marketapp/basepath.js @@ -14,10 +14,4 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const AUTH = 'auth' - -const Actions = { - AUTH, -} - -module.exports = Actions +module.exports = 'marketapp' diff --git a/src/fireedge/src/server/routes/api/marketapp/functions.js b/src/fireedge/src/server/routes/api/marketapp/functions.js index 29f5189092..c2f9dfdb9b 100644 --- a/src/fireedge/src/server/routes/api/marketapp/functions.js +++ b/src/fireedge/src/server/routes/api/marketapp/functions.js @@ -16,31 +16,18 @@ const { sprintf } = require('sprintf-js') const { request: axios } = require('axios') - -const { - defaultEmptyFunction, - defaultCommandMarketApp, - dockerUrl, -} = require('server/utils/constants/defaults') - -const { - ok, - internalServerError, - badRequest, - notFound, -} = require('server/utils/constants/http-codes') - +const { defaults, httpCodes } = require('server/utils/constants') const { Actions: ActionsMarketApp, } = require('server/utils/constants/commands/marketapp') - const { Actions: ActionsMarket, } = require('server/utils/constants/commands/market') - const { httpResponse, executeCommand } = require('server/utils/server') const { getSunstoneConfig } = require('server/utils/yml') +const { defaultEmptyFunction, defaultCommandMarketApp, dockerUrl } = defaults +const { ok, internalServerError, badRequest, notFound } = httpCodes const httpBadRequest = httpResponse(badRequest, '', '') const httpNotFoundRequest = httpResponse(notFound, '', '') diff --git a/src/fireedge/src/server/routes/api/marketapp/index.js b/src/fireedge/src/server/routes/api/marketapp/index.js index fc241f55c1..bdde64bcbb 100644 --- a/src/fireedge/src/server/routes/api/marketapp/index.js +++ b/src/fireedge/src/server/routes/api/marketapp/index.js @@ -14,15 +14,35 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const { setApiRoutes } = require('server/utils/server') +const { Actions, Commands } = require('server/routes/api/marketapp/routes') const { - routes: marketappRoutes, -} = require('server/routes/api/marketapp/routes') -const { MARKETAPP } = require('./string-routes') + exportApp, + importMarket, + getDockerTags, +} = require('server/routes/api/marketapp/functions') -const functionRoutes = { - private: setApiRoutes(marketappRoutes, MARKETAPP), - public: [], -} +const { + MARKETAPP_EXPORT, + MARKETAPP_VMIMPORT, + MARKETAPP_TEMPLATEIMPORT, + MARKETAPP_DOCKERTAGS, +} = Actions -module.exports = functionRoutes +module.exports = [ + { + ...Commands[MARKETAPP_EXPORT], + action: exportApp, + }, + { + ...Commands[MARKETAPP_VMIMPORT], + actions: importMarket, + }, + { + ...Commands[MARKETAPP_TEMPLATEIMPORT], + actions: importMarket, + }, + { + ...Commands[MARKETAPP_DOCKERTAGS], + actions: getDockerTags, + }, +] diff --git a/src/fireedge/src/server/routes/api/marketapp/routes.js b/src/fireedge/src/server/routes/api/marketapp/routes.js index caefd24f77..97444247c7 100644 --- a/src/fireedge/src/server/routes/api/marketapp/routes.js +++ b/src/fireedge/src/server/routes/api/marketapp/routes.js @@ -18,113 +18,107 @@ const { httpMethod, from: fromData, } = require('server/utils/constants/defaults') -const { - exportApp, - importMarket, - getDockerTags, -} = require('server/routes/api/marketapp/functions') -const { POST, GET } = httpMethod +const MARKETAPP = require('server/routes/api/marketapp/basepath') -const routes = { - [POST]: { - export: { - action: exportApp, +const { POST, GET } = httpMethod +const basepath = `/${MARKETAPP}` +const { query, resource, postBody } = fromData +const MARKETAPP_EXPORT = 'marketapp.export' +const MARKETAPP_VMIMPORT = 'marketapp.vmimport' +const MARKETAPP_TEMPLATEIMPORT = 'marketapp.templateimport' +const MARKETAPP_DOCKERTAGS = 'marketapp.dockertags' + +const Actions = { + MARKETAPP_EXPORT, + MARKETAPP_VMIMPORT, + MARKETAPP_TEMPLATEIMPORT, + MARKETAPP_DOCKERTAGS, +} + +module.exports = { + Actions, + Commands: { + [MARKETAPP_EXPORT]: { + path: `${basepath}/export/:id`, + httpMethod: POST, + auth: true, params: { id: { - from: fromData.resource, - name: 'id', + from: resource, }, name: { - from: fromData.postBody, - name: 'name', + from: postBody, }, datastore: { - from: fromData.postBody, - name: 'datastore', + from: postBody, }, file: { - from: fromData.postBody, - name: 'file', + from: postBody, }, associated: { - from: fromData.postBody, - name: 'associated', + from: postBody, }, tag: { - from: fromData.postBody, - name: 'tag', + from: postBody, }, template: { - from: fromData.postBody, - name: 'template', + from: postBody, }, vmname: { - from: fromData.postBody, - name: 'vmname', + from: postBody, }, }, }, - vmimport: { - action: importMarket, + [MARKETAPP_VMIMPORT]: { + path: `${basepath}/vmimport/:vmId`, + httpMethod: POST, + auth: true, params: { vmId: { - from: fromData.resource, - name: 'id', + from: resource, }, associated: { - from: fromData.postBody, - name: 'associated', + from: postBody, }, marketId: { - from: fromData.postBody, - name: 'marketId', + from: postBody, }, vmname: { - from: fromData.postBody, - name: 'vmname', + from: postBody, }, }, }, - templateimport: { - action: importMarket, + [MARKETAPP_TEMPLATEIMPORT]: { + path: `${basepath}/templateimport/:templateId`, + httpMethod: POST, + auth: true, params: { templateId: { - from: fromData.resource, - name: 'id', + from: resource, }, associated: { - from: fromData.postBody, - name: 'associated', + from: postBody, }, marketId: { - from: fromData.postBody, - name: 'marketId', + from: postBody, }, vmname: { - from: fromData.postBody, - name: 'vmname', + from: postBody, }, }, }, - }, - [GET]: { - dockertags: { - action: getDockerTags, + [MARKETAPP_DOCKERTAGS]: { + path: `${basepath}/dockertags/:id`, + httpMethod: GET, + auth: true, params: { id: { - from: fromData.resource, - name: 'id', + from: resource, }, page: { - from: fromData.query, - name: 'page', + from: query, }, }, }, }, } - -const authApi = { - routes, -} -module.exports = authApi diff --git a/src/fireedge/src/server/routes/api/marketapp/string-routes.js b/src/fireedge/src/server/routes/api/marketapp/string-routes.js deleted file mode 100644 index a2e8f0fa47..0000000000 --- a/src/fireedge/src/server/routes/api/marketapp/string-routes.js +++ /dev/null @@ -1,23 +0,0 @@ -/* ------------------------------------------------------------------------- * - * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * - * * - * 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 * - * * - * http://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. * - * ------------------------------------------------------------------------- */ - -const MARKETAPP = 'marketapp' - -const Actions = { - MARKETAPP, -} - -module.exports = Actions diff --git a/src/fireedge/src/server/routes/api/oneflow/string-routes.js b/src/fireedge/src/server/routes/api/oneflow/basepath.js similarity index 96% rename from src/fireedge/src/server/routes/api/oneflow/string-routes.js rename to src/fireedge/src/server/routes/api/oneflow/basepath.js index b659316f08..968c1a9fd8 100644 --- a/src/fireedge/src/server/routes/api/oneflow/string-routes.js +++ b/src/fireedge/src/server/routes/api/oneflow/basepath.js @@ -17,9 +17,7 @@ const SERVICE = 'service' const SERVICE_TEMPLATE = 'service_template' -const Actions = { +module.exports = { SERVICE, SERVICE_TEMPLATE, } - -module.exports = Actions diff --git a/src/fireedge/src/server/routes/api/oneflow/index.js b/src/fireedge/src/server/routes/api/oneflow/index.js index fe73106ab5..52cd2186ec 100644 --- a/src/fireedge/src/server/routes/api/oneflow/index.js +++ b/src/fireedge/src/server/routes/api/oneflow/index.js @@ -14,25 +14,107 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const { setApiRoutes } = require('server/utils/server') -const { routes: serviceRoutes } = require('./service') -const { routes: serviceTemplateRoutes } = require('./template') +const { + Actions: ActionsService, + Commands: CommandsService, +} = require('server/routes/api/oneflow/service/routes') +const { + service, + serviceDelete, + serviceAddAction, + serviceAddScale, + serviceAddRoleAction, + serviceAddSchedAction, + serviceUpdateSchedAction, + serviceDeleteSchedAction, +} = require('server/routes/api/oneflow/service/functions') +const { + Actions: ActionsTemplate, + Commands: CommandsTemplate, +} = require('server/routes/api/oneflow/template/routes') +const { + serviceTemplate, + serviceTemplateDelete, + serviceTemplateCreate, + serviceTemplateUpdate, + serviceTemplateAction, +} = require('server/routes/api/oneflow/template/functions') -const { SERVICE, SERVICE_TEMPLATE } = require('./string-routes') +const { + SERVICE_SHOW, + SERVICE_ADD_ACTION, + SERVICE_ADD_SCALE, + SERVICE_ADD_ROLEACTION, + SERVICE_ADD_SCHEDACTION, + SERVICE_UPDATE_SCHEDACTION, + SERVICE_DELETE_SCHEDACTION, + SERVICE_DELETE, +} = ActionsService -/** - * Add routes. - * - * @returns {Array} routes - */ -const generatePrivateRoutes = () => [ - ...setApiRoutes(serviceRoutes, SERVICE), - ...setApiRoutes(serviceTemplateRoutes, SERVICE_TEMPLATE), +const { + SERVICETEMPLATE_SHOW, + SERVICETEMPLATE_ACTION, + SERVICETEMPLATE_CREATE, + SERVICETEMPLATE_UPDATE, + SERVICETEMPLATE_DELETE, +} = ActionsTemplate + +const services = [ + { + ...CommandsService[SERVICE_SHOW], + action: service, + }, + { + ...CommandsService[SERVICE_ADD_ACTION], + action: serviceAddAction, + }, + { + ...CommandsService[SERVICE_ADD_SCALE], + action: serviceAddScale, + }, + { + ...CommandsService[SERVICE_ADD_ROLEACTION], + action: serviceAddRoleAction, + }, + { + ...CommandsService[SERVICE_ADD_SCHEDACTION], + action: serviceAddSchedAction, + }, + { + ...CommandsService[SERVICE_UPDATE_SCHEDACTION], + action: serviceUpdateSchedAction, + }, + { + ...CommandsService[SERVICE_DELETE_SCHEDACTION], + action: serviceDeleteSchedAction, + }, + { + ...CommandsService[SERVICE_DELETE], + action: serviceDelete, + }, ] -const functionRoutes = { - private: generatePrivateRoutes(), - public: [], -} +const template = [ + { + ...CommandsTemplate[SERVICETEMPLATE_SHOW], + action: serviceTemplate, + }, + { + ...CommandsTemplate[SERVICETEMPLATE_ACTION], + action: serviceTemplateAction, + }, + { + ...CommandsTemplate[SERVICETEMPLATE_CREATE], + action: serviceTemplateCreate, + }, + { + ...CommandsTemplate[SERVICETEMPLATE_UPDATE], + action: serviceTemplateUpdate, + }, + { + ...CommandsTemplate[SERVICETEMPLATE_DELETE], + action: serviceTemplateDelete, + }, +] -module.exports = functionRoutes +module.exports = [...services, ...template] diff --git a/src/fireedge/src/server/routes/api/oneflow/service/functions.js b/src/fireedge/src/server/routes/api/oneflow/service/functions.js index 24ddead422..15ed8a9126 100644 --- a/src/fireedge/src/server/routes/api/oneflow/service/functions.js +++ b/src/fireedge/src/server/routes/api/oneflow/service/functions.js @@ -20,18 +20,13 @@ const { oneFlowConnection, returnSchemaError, } = require('server/routes/api/oneflow/utils') -const { - httpMethod, - defaultEmptyFunction, -} = require('server/utils/constants/defaults') +const { defaults, httpCodes } = require('server/utils/constants') const { httpResponse, parsePostData } = require('server/utils/server') -const { - ok, - internalServerError, - methodNotAllowed, -} = require('server/utils/constants/http-codes') const { generateNewResourceTemplate } = require('server/utils/opennebula') const { Actions: ActionVM } = require('server/utils/constants/commands/vm') + +const { httpMethod, defaultEmptyFunction } = defaults +const { ok, internalServerError, methodNotAllowed } = httpCodes const { GET, POST, DELETE } = httpMethod /** diff --git a/src/fireedge/src/server/routes/api/oneflow/service/index.js b/src/fireedge/src/server/routes/api/oneflow/service/index.js deleted file mode 100644 index 96c796027e..0000000000 --- a/src/fireedge/src/server/routes/api/oneflow/service/index.js +++ /dev/null @@ -1,102 +0,0 @@ -/* ------------------------------------------------------------------------- * - * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * - * * - * 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 * - * * - * http://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. * - * ------------------------------------------------------------------------- */ - -const { - httpMethod, - from: fromData, -} = require('server/utils/constants/defaults') -const { - service, - serviceDelete, - serviceAddAction, - serviceAddScale, - serviceAddRoleAction, - serviceAddSchedAction, - serviceUpdateSchedAction, - serviceDeleteSchedAction, -} = require('server/routes/api/oneflow/service/functions') -const { GET, POST, DELETE, PUT } = httpMethod - -const routes = { - [GET]: { - null: { - action: service, - params: { - id: { from: fromData.resource, name: 'method' }, - }, - }, - }, - [POST]: { - action: { - action: serviceAddAction, - params: { - id: { from: fromData.resource, name: 'id' }, - action: { from: fromData.postBody }, - }, - }, - scale: { - action: serviceAddScale, - params: { - id: { from: fromData.resource, name: 'id' }, - action: { from: fromData.postBody }, - }, - }, - role_action: { - action: serviceAddRoleAction, - params: { - id: { from: fromData.resource, name: 'id' }, - role: { from: fromData.resource, name: 'id2' }, - action: { from: fromData.postBody }, - }, - }, - sched_action: { - action: serviceAddSchedAction, - params: { - id: { from: fromData.resource, name: 'id' }, - sched_action: { from: fromData.postBody, name: 'sched_action' }, - }, - }, - }, - [PUT]: { - sched_action: { - action: serviceUpdateSchedAction, - params: { - id: { from: fromData.resource, name: 'id' }, - id_sched: { from: fromData.resource, name: 'id2' }, - sched_action: { from: fromData.postBody, name: 'sched_action' }, - }, - }, - }, - [DELETE]: { - null: { - action: serviceDelete, - params: { id: { from: fromData.resource, name: 'method' } }, - }, - sched_action: { - action: serviceDeleteSchedAction, - params: { - id: { from: fromData.resource, name: 'method' }, - id_sched: { from: fromData.resource, name: 'id' }, - }, - }, - }, -} - -const serviceApi = { - routes, -} - -module.exports = serviceApi diff --git a/src/fireedge/src/server/routes/api/oneflow/service/routes.js b/src/fireedge/src/server/routes/api/oneflow/service/routes.js new file mode 100644 index 0000000000..0c18c253f5 --- /dev/null +++ b/src/fireedge/src/server/routes/api/oneflow/service/routes.js @@ -0,0 +1,155 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * + * * + * 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 * + * * + * http://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. * + * ------------------------------------------------------------------------- */ + +const { + httpMethod, + from: fromData, +} = require('server/utils/constants/defaults') +const { SERVICE } = require('server/routes/api/oneflow/basepath') + +const basepath = `/${SERVICE}` +const { GET, POST, DELETE, PUT } = httpMethod +const { resource, postBody } = fromData + +const SERVICE_SHOW = 'service.show' +const SERVICE_ADD_ACTION = 'service.addaction' +const SERVICE_ADD_SCALE = 'service.addscale' +const SERVICE_ADD_ROLEACTION = 'service.addroleaction' +const SERVICE_ADD_SCHEDACTION = 'service.addscheaction' +const SERVICE_UPDATE_SCHEDACTION = 'service.updateschedaction' +const SERVICE_DELETE_SCHEDACTION = 'service.deleteschedaction' +const SERVICE_DELETE = 'service.delete' + +const Actions = { + SERVICE_SHOW, + SERVICE_ADD_ACTION, + SERVICE_ADD_SCALE, + SERVICE_ADD_ROLEACTION, + SERVICE_ADD_SCHEDACTION, + SERVICE_UPDATE_SCHEDACTION, + SERVICE_DELETE_SCHEDACTION, + SERVICE_DELETE, +} + +module.exports = { + Actions, + Commands: { + [SERVICE_SHOW]: { + path: `${basepath}/:id`, + httpMethod: GET, + auth: true, + params: { + id: { + from: resource, + }, + }, + }, + [SERVICE_ADD_ACTION]: { + path: `${basepath}/action/:id`, + httpMethod: POST, + auth: true, + params: { + id: { + from: resource, + }, + action: { + from: postBody, + }, + }, + }, + [SERVICE_ADD_SCALE]: { + path: `${basepath}/scale/:id`, + httpMethod: POST, + auth: true, + params: { + id: { + from: resource, + }, + action: { + from: postBody, + }, + }, + }, + [SERVICE_ADD_ROLEACTION]: { + path: `${basepath}/role_action/:id/:role`, + httpMethod: POST, + auth: true, + params: { + id: { + from: resource, + }, + role: { + from: resource, + }, + action: { + from: postBody, + }, + }, + }, + [SERVICE_ADD_SCHEDACTION]: { + path: `${basepath}/sched_action/:id`, + httpMethod: POST, + auth: true, + params: { + id: { + from: resource, + }, + sched_action: { + from: postBody, + }, + }, + }, + [SERVICE_UPDATE_SCHEDACTION]: { + path: `${basepath}/sched_action/:id/:id_sched`, + httpMethod: PUT, + auth: true, + params: { + id: { + from: resource, + }, + id_sched: { + from: resource, + }, + sched_action: { + from: postBody, + }, + }, + }, + [SERVICE_DELETE_SCHEDACTION]: { + path: `${basepath}/sched_action/:id/:id_sched`, + httpMethod: DELETE, + auth: true, + params: { + id: { + from: resource, + }, + id_sched: { + from: resource, + }, + }, + }, + [SERVICE_DELETE]: { + path: `${basepath}/:id`, + httpMethod: DELETE, + auth: true, + params: { + id: { + from: resource, + }, + }, + }, + }, +} diff --git a/src/fireedge/src/server/routes/api/oneflow/template/functions.js b/src/fireedge/src/server/routes/api/oneflow/template/functions.js index bee661a0de..ec9d6e69d3 100644 --- a/src/fireedge/src/server/routes/api/oneflow/template/functions.js +++ b/src/fireedge/src/server/routes/api/oneflow/template/functions.js @@ -20,16 +20,11 @@ const { oneFlowConection, returnSchemaError, } = require('server/routes/api/oneflow/utils') -const { - httpMethod, - defaultEmptyFunction, -} = require('server/utils/constants/defaults') +const { defaults, httpCodes } = require('server/utils/constants') const { httpResponse, parsePostData } = require('server/utils/server') -const { - ok, - internalServerError, - methodNotAllowed, -} = require('server/utils/constants/http-codes') + +const { httpMethod, defaultEmptyFunction } = defaults +const { ok, internalServerError, methodNotAllowed } = httpCodes const { GET, POST, DELETE, PUT } = httpMethod /** diff --git a/src/fireedge/src/server/routes/api/oneflow/template/index.js b/src/fireedge/src/server/routes/api/oneflow/template/index.js deleted file mode 100644 index f205665d11..0000000000 --- a/src/fireedge/src/server/routes/api/oneflow/template/index.js +++ /dev/null @@ -1,77 +0,0 @@ -/* ------------------------------------------------------------------------- * - * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * - * * - * 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 * - * * - * http://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. * - * ------------------------------------------------------------------------- */ - -const { - httpMethod, - from: fromData, -} = require('server/utils/constants/defaults') -const { - serviceTemplate, - serviceTemplateDelete, - serviceTemplateCreate, - serviceTemplateUpdate, - serviceTemplateAction, -} = require('server/routes/api/oneflow/template/functions') -const { GET, POST, DELETE, PUT } = httpMethod - -const routes = { - [GET]: { - null: { - action: serviceTemplate, - params: { - id: { from: fromData.resource, name: 'method' }, - }, - }, - }, - [POST]: { - null: { - action: serviceTemplateCreate, - params: { - template: { from: fromData.postBody }, - }, - }, - action: { - action: serviceTemplateAction, - params: { - id: { from: fromData.resource, name: 'id' }, - template: { from: fromData.postBody }, - }, - }, - }, - [PUT]: { - null: { - action: serviceTemplateUpdate, - params: { - id: { from: fromData.resource, name: 'method' }, - template: { from: fromData.postBody }, - }, - }, - }, - [DELETE]: { - null: { - action: serviceTemplateDelete, - params: { - id: { from: fromData.resource, name: 'method' }, - }, - }, - }, -} - -const serviceTemplateApi = { - routes, -} - -module.exports = serviceTemplateApi diff --git a/src/fireedge/src/server/routes/api/oneflow/template/routes.js b/src/fireedge/src/server/routes/api/oneflow/template/routes.js new file mode 100644 index 0000000000..6f9ea22ed1 --- /dev/null +++ b/src/fireedge/src/server/routes/api/oneflow/template/routes.js @@ -0,0 +1,101 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * + * * + * 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 * + * * + * http://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. * + * ------------------------------------------------------------------------- */ + +const { + httpMethod, + from: fromData, +} = require('server/utils/constants/defaults') +const { SERVICE_TEMPLATE } = require('server/routes/api/oneflow/basepath') + +const { GET, POST, DELETE, PUT } = httpMethod +const basepath = `/${SERVICE_TEMPLATE}` +const { resource, postBody } = fromData + +const SERVICETEMPLATE_SHOW = 'servicetemplate.show' +const SERVICETEMPLATE_ACTION = 'servicetemplate.action' +const SERVICETEMPLATE_CREATE = 'servicetemplate.create' +const SERVICETEMPLATE_UPDATE = 'servicetemplate.update' +const SERVICETEMPLATE_DELETE = 'servicetemplate.delete' + +const Actions = { + SERVICETEMPLATE_SHOW, + SERVICETEMPLATE_ACTION, + SERVICETEMPLATE_CREATE, + SERVICETEMPLATE_UPDATE, + SERVICETEMPLATE_DELETE, +} + +module.exports = { + Actions, + Commands: { + [SERVICETEMPLATE_SHOW]: { + path: `${basepath}/:id`, + httpMethod: GET, + auth: true, + params: { + id: { + from: resource, + }, + }, + }, + [SERVICETEMPLATE_ACTION]: { + path: `${basepath}/action/:id`, + httpMethod: POST, + auth: true, + params: { + id: { + from: resource, + }, + template: { + from: postBody, + }, + }, + }, + [SERVICETEMPLATE_CREATE]: { + path: `${basepath}`, + httpMethod: POST, + auth: true, + params: { + template: { + from: postBody, + }, + }, + }, + [SERVICETEMPLATE_UPDATE]: { + path: `${basepath}/:id`, + httpMethod: PUT, + auth: true, + params: { + id: { + from: resource, + }, + template: { + from: postBody, + }, + }, + }, + [SERVICETEMPLATE_DELETE]: { + path: `${basepath}/:id`, + httpMethod: DELETE, + auth: true, + params: { + id: { + from: resource, + }, + }, + }, + }, +} diff --git a/src/fireedge/src/server/routes/api/oneprovision/string-routes.js b/src/fireedge/src/server/routes/api/oneprovision/basepath.js similarity index 96% rename from src/fireedge/src/server/routes/api/oneprovision/string-routes.js rename to src/fireedge/src/server/routes/api/oneprovision/basepath.js index 79f9ebb4fb..a856276608 100644 --- a/src/fireedge/src/server/routes/api/oneprovision/string-routes.js +++ b/src/fireedge/src/server/routes/api/oneprovision/basepath.js @@ -18,10 +18,8 @@ const PROVIDER = 'provider' const PROVISION = 'provision' const PROVISION_TEMPLATE = 'provision-template' -const Actions = { +module.exports = { PROVIDER, PROVISION, PROVISION_TEMPLATE, } - -module.exports = Actions diff --git a/src/fireedge/src/server/routes/api/oneprovision/index.js b/src/fireedge/src/server/routes/api/oneprovision/index.js index f8cf87d078..95c11231a2 100644 --- a/src/fireedge/src/server/routes/api/oneprovision/index.js +++ b/src/fireedge/src/server/routes/api/oneprovision/index.js @@ -14,37 +14,253 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const { setApiRoutes } = require('server/utils/server') const { - routes: provisionRoutes, -} = require('server/routes/api/oneprovision/provision') + Actions: ActionsProvision, + Commands: CommandsProvision, +} = require('server/routes/api/oneprovision/provision/routes') const { - routes: provisionTemplateRoutes, -} = require('server/routes/api/oneprovision/template') -const { - routes: providerRoutes, -} = require('server/routes/api/oneprovision/provider') + getListResourceProvision, + getListProvisions, + getLogProvisions, + deleteResource, + deleteProvision, + hostCommand, + hostCommandSSH, + createProvision, + configureProvision, + configureHost, + validate, + getProvisionDefaults, +} = require('server/routes/api/oneprovision/provision/functions') const { - PROVIDER, - PROVISION, - PROVISION_TEMPLATE, -} = require('server/routes/api/oneprovision/string-routes') + Actions: ActionsTemplate, + Commands: CommandsTemplate, +} = require('server/routes/api/oneprovision/template/routes') +const { + getListProvisionTemplates, + createProvisionTemplate, + instantiateProvisionTemplate, + updateProvisionTemplate, + deleteProvisionTemplate, +} = require('server/routes/api/oneprovision/template/functions') -/** - * Add routes. - * - * @returns {Array} routes - */ -const generatePrivateRoutes = () => [ - ...setApiRoutes(provisionRoutes, PROVISION), - ...setApiRoutes(provisionTemplateRoutes, PROVISION_TEMPLATE), - ...setApiRoutes(providerRoutes, PROVIDER), +const { + Actions: ActionsProvider, + Commands: CommandsProvider, +} = require('server/routes/api/oneprovision/provider/routes') +const { + getListProviders, + getConnectionProviders, + createProviders, + updateProviders, + deleteProvider, + getProviderConfig, +} = require('server/routes/api/oneprovision/provider/functions') + +const { + PROVISION_CLUSTER_RESOURCE, + PROVISION_DATASTORE_RESOURCE, + PROVISION_HOST_RESOURCE, + PROVISION_IMAGE_RESOURCE, + PROVISION_NETWORK_RESOURCE, + PROVISION_TEMPLATE_RESOURCE, + PROVISION_VNTEMPLATE_RESOURCE, + PROVISION_LOGS, + PROVISION_DEFAULTS, + PROVISION_LIST, + PROVISION_VALIDATE, + PROVISION_HOST_POWEROFF, + PROVISION_HOST_REBOOT, + PROVISION_HOST_RESUME, + PROVISION_CREATE, + PROVISION_HOST_SSH, + PROVISION_DATASTORE, + PROVISION_FLOWTEMPLATE, + PROVISION_DELETE_HOST_RESOURCE, + PROVISION_DELETE_IMAGE_RESOURCE, + PROVISION_DELETE_NETWORK_RESOURCE, + PROVISION_DELETE_VNTEMPLATE_RESOURCE, + PROVISION_DELETE_TEMPLATE_RESOURCE, + PROVISION_DELETE_CLUSTER_RESOURCE, + PROVISION_DELETE_PROVISION, + PROVISION_UPDATE_CONFIGURE, + PROVISION_UPDATE_HOST, +} = ActionsProvision + +const { + PROVISIONTEMPLATE_SHOW, + PROVISIONTEMPLATE_INSTANTIATE, + PROVISIONTEMPLATE_CREATE, + PROVISIONTEMPLATE_UPDATE, + PROVISIONTEMPLATE_DELETE, +} = ActionsTemplate + +const { + PROVIDER_CONNECTION, + PROVIDER_CONFIG, + PROVIDER_LIST, + PROVIDER_CREATE, + PROVIDER_UPDATE, + PROVIDER_DELETE, +} = ActionsProvider + +module.exports = [ + // Provision + { + ...CommandsProvision[PROVISION_CLUSTER_RESOURCE], + action: getListResourceProvision, + }, + { + ...CommandsProvision[PROVISION_DATASTORE_RESOURCE], + action: getListResourceProvision, + }, + { + ...CommandsProvision[PROVISION_HOST_RESOURCE], + action: getListResourceProvision, + }, + { + ...CommandsProvision[PROVISION_IMAGE_RESOURCE], + action: getListResourceProvision, + }, + { + ...CommandsProvision[PROVISION_NETWORK_RESOURCE], + action: getListResourceProvision, + }, + { + ...CommandsProvision[PROVISION_TEMPLATE_RESOURCE], + action: getListResourceProvision, + }, + { + ...CommandsProvision[PROVISION_VNTEMPLATE_RESOURCE], + action: getListResourceProvision, + }, + { + ...CommandsProvision[PROVISION_LOGS], + action: getLogProvisions, + }, + { + ...CommandsProvision[PROVISION_DEFAULTS], + action: getProvisionDefaults, + }, + { + ...CommandsProvision[PROVISION_LIST], + action: getListProvisions, + }, + { + ...CommandsProvision[PROVISION_VALIDATE], + action: validate, + }, + { + ...CommandsProvision[PROVISION_HOST_POWEROFF], + action: hostCommand, + }, + { + ...CommandsProvision[PROVISION_HOST_REBOOT], + action: hostCommand, + }, + { + ...CommandsProvision[PROVISION_HOST_RESUME], + action: hostCommand, + }, + { + ...CommandsProvision[PROVISION_CREATE], + action: createProvision, + }, + { + ...CommandsProvision[PROVISION_HOST_SSH], + action: hostCommandSSH, + }, + { + ...CommandsProvision[PROVISION_DATASTORE], + action: deleteResource, + }, + { + ...CommandsProvision[PROVISION_FLOWTEMPLATE], + action: deleteResource, + }, + { + ...CommandsProvision[PROVISION_DELETE_HOST_RESOURCE], + action: deleteResource, + }, + { + ...CommandsProvision[PROVISION_DELETE_IMAGE_RESOURCE], + action: deleteResource, + }, + { + ...CommandsProvision[PROVISION_DELETE_NETWORK_RESOURCE], + action: deleteResource, + }, + { + ...CommandsProvision[PROVISION_DELETE_VNTEMPLATE_RESOURCE], + action: deleteResource, + }, + { + ...CommandsProvision[PROVISION_DELETE_TEMPLATE_RESOURCE], + action: deleteResource, + }, + { + ...CommandsProvision[PROVISION_DELETE_CLUSTER_RESOURCE], + action: deleteResource, + }, + { + ...CommandsProvision[PROVISION_DELETE_PROVISION], + action: deleteProvision, + }, + { + ...CommandsProvision[PROVISION_UPDATE_CONFIGURE], + action: configureProvision, + }, + { + ...CommandsProvision[PROVISION_UPDATE_HOST], + action: configureHost, + }, + // Template + + { + ...CommandsTemplate[PROVISIONTEMPLATE_SHOW], + action: getListProvisionTemplates, + }, + { + ...CommandsTemplate[PROVISIONTEMPLATE_INSTANTIATE], + action: instantiateProvisionTemplate, + }, + { + ...CommandsTemplate[PROVISIONTEMPLATE_CREATE], + action: createProvisionTemplate, + }, + { + ...CommandsTemplate[PROVISIONTEMPLATE_UPDATE], + action: updateProvisionTemplate, + }, + { + ...CommandsTemplate[PROVISIONTEMPLATE_DELETE], + action: deleteProvisionTemplate, + }, + + // Provider + { + ...CommandsProvider[PROVIDER_CONNECTION], + action: getConnectionProviders, + }, + { + ...CommandsProvider[PROVIDER_CONFIG], + action: getProviderConfig, + }, + { + ...CommandsProvider[PROVIDER_LIST], + action: getListProviders, + }, + { + ...CommandsProvider[PROVIDER_CREATE], + action: createProviders, + }, + { + ...CommandsProvider[PROVIDER_UPDATE], + action: updateProviders, + }, + { + ...CommandsProvider[PROVIDER_DELETE], + action: deleteProvider, + }, ] - -const functionRoutes = { - private: generatePrivateRoutes(), - public: [], -} - -module.exports = functionRoutes diff --git a/src/fireedge/src/server/routes/api/oneprovision/provider/functions.js b/src/fireedge/src/server/routes/api/oneprovision/provider/functions.js index c8d43fdbbf..d1b24b625a 100644 --- a/src/fireedge/src/server/routes/api/oneprovision/provider/functions.js +++ b/src/fireedge/src/server/routes/api/oneprovision/provider/functions.js @@ -16,16 +16,7 @@ const { parse } = require('yaml') const { basename } = require('path') -const { - defaultFolderTmpProvision, - defaultCommandProvider, - defaultHideCredentials, - defaultHideCredentialReplacer, - defaultEmptyFunction, - defaultProvidersConfigPath, -} = require('server/utils/constants/defaults') - -const { ok, internalServerError } = require('server/utils/constants/http-codes') +const { defaults, httpCodes } = require('server/utils/constants') const { httpResponse, parsePostData, @@ -41,6 +32,15 @@ const { getSpecificConfig, } = require('server/routes/api/oneprovision/utils') +const { + defaultFolderTmpProvision, + defaultCommandProvider, + defaultHideCredentials, + defaultHideCredentialReplacer, + defaultEmptyFunction, + defaultProvidersConfigPath, +} = defaults +const { ok, internalServerError } = httpCodes const httpInternalError = httpResponse(internalServerError, '', '') /** diff --git a/src/fireedge/src/server/routes/api/oneprovision/provider/index.js b/src/fireedge/src/server/routes/api/oneprovision/provider/routes.js similarity index 50% rename from src/fireedge/src/server/routes/api/oneprovision/provider/index.js rename to src/fireedge/src/server/routes/api/oneprovision/provider/routes.js index 0818fd211a..b5d0160cd0 100644 --- a/src/fireedge/src/server/routes/api/oneprovision/provider/index.js +++ b/src/fireedge/src/server/routes/api/oneprovision/provider/routes.js @@ -18,64 +18,86 @@ const { from: fromData, httpMethod, } = require('server/utils/constants/defaults') -const { - getListProviders, - getConnectionProviders, - createProviders, - updateProviders, - deleteProvider, - getProviderConfig, -} = require('server/routes/api/oneprovision/provider/functions') +const { PROVIDER } = require('server/routes/api/oneprovision/basepath') const { GET, POST, PUT, DELETE } = httpMethod +const basepath = `/${PROVIDER}` +const { resource, postBody } = fromData -const routes = { - [GET]: { - null: { - action: getListProviders, +const PROVIDER_CONNECTION = 'provider.connection' +const PROVIDER_CONFIG = 'provider.config' +const PROVIDER_LIST = 'provider.list' +const PROVIDER_CREATE = 'provider.create' +const PROVIDER_UPDATE = 'provider.update' +const PROVIDER_DELETE = 'provider.delete' + +const Actions = { + PROVIDER_CONNECTION, + PROVIDER_CONFIG, + PROVIDER_LIST, + PROVIDER_CREATE, + PROVIDER_UPDATE, + PROVIDER_DELETE, +} + +module.exports = { + Actions, + Commands: { + [PROVIDER_CONNECTION]: { + path: `${basepath}/connection/:id`, + httpMethod: GET, + auth: true, params: { - id: { from: fromData.resource, name: 'method' }, + id: { + from: resource, + }, }, }, - connection: { - action: getConnectionProviders, + [PROVIDER_CONFIG]: { + path: `${basepath}/config`, + httpMethod: GET, + auth: true, + }, + [PROVIDER_LIST]: { + path: `${basepath}/:id?`, + httpMethod: GET, + auth: true, params: { - id: { from: fromData.resource, name: 'id' }, + id: { + from: resource, + }, }, }, - config: { - action: getProviderConfig, - params: {}, - }, - }, - [POST]: { - null: { - action: createProviders, + [PROVIDER_CREATE]: { + path: `${basepath}`, + httpMethod: POST, + auth: true, params: { - resource: { from: fromData.postBody }, + resource: { + from: postBody, + all: true, + }, }, }, - }, - [PUT]: { - null: { - action: updateProviders, + [PROVIDER_UPDATE]: { + path: `${basepath}/:id`, + httpMethod: PUT, + auth: true, params: { - resource: { from: fromData.postBody }, - id: { from: fromData.resource, name: 'method' }, + resource: { + from: postBody, + all: true, + }, + id: { from: resource }, }, }, - }, - [DELETE]: { - null: { - action: deleteProvider, + [PROVIDER_DELETE]: { + path: `${basepath}/:id`, + httpMethod: DELETE, + auth: true, params: { - id: { from: fromData.resource, name: 'method' }, + id: { from: resource }, }, }, }, } - -const providerApi = { - routes, -} -module.exports = providerApi diff --git a/src/fireedge/src/server/routes/api/oneprovision/provision/functions.js b/src/fireedge/src/server/routes/api/oneprovision/provision/functions.js index 762cc356d8..eb15d8b186 100644 --- a/src/fireedge/src/server/routes/api/oneprovision/provision/functions.js +++ b/src/fireedge/src/server/routes/api/oneprovision/provision/functions.js @@ -23,12 +23,7 @@ const { basename, dirname } = require('path') const { sprintf } = require('sprintf-js') const { Actions } = require('server/utils/constants/commands/document') -const { - ok, - notFound, - accepted, - internalServerError, -} = require('server/utils/constants/http-codes') +const { defaults, httpCodes } = require('server/utils/constants') const { httpResponse, parsePostData, @@ -41,12 +36,6 @@ const { removeFile, } = require('server/utils/server') const { checkEmptyObject } = require('server/utils/general') -const { - defaultFolderTmpProvision, - defaultCommandProvision, - defaultEmptyFunction, - defaultErrorTemplate, -} = require('server/utils/constants/defaults') const { createTemporalFile, createFolderWithFiles, @@ -61,6 +50,13 @@ const { } = require('server/routes/api/oneprovision/utils') const { provision } = require('server/routes/api/oneprovision/schemas') +const { + defaultFolderTmpProvision, + defaultCommandProvision, + defaultEmptyFunction, + defaultErrorTemplate, +} = defaults +const { ok, notFound, accepted, internalServerError } = httpCodes const httpInternalError = httpResponse(internalServerError, '', '') const logFile = { diff --git a/src/fireedge/src/server/routes/api/oneprovision/provision/index.js b/src/fireedge/src/server/routes/api/oneprovision/provision/index.js deleted file mode 100644 index 32d3434e42..0000000000 --- a/src/fireedge/src/server/routes/api/oneprovision/provision/index.js +++ /dev/null @@ -1,230 +0,0 @@ -/* ------------------------------------------------------------------------- * - * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * - * * - * 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 * - * * - * http://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. * - * ------------------------------------------------------------------------- */ - -const { - httpMethod, - from: fromData, -} = require('server/utils/constants/defaults') -const { - getListResourceProvision, - getListProvisions, - getLogProvisions, - deleteResource, - deleteProvision, - hostCommand, - hostCommandSSH, - createProvision, - configureProvision, - configureHost, - validate, - getProvisionDefaults, -} = require('server/routes/api/oneprovision/provision/functions') -const { GET, POST, DELETE, PUT } = httpMethod - -const routes = { - [GET]: { - null: { - action: getListProvisions, - params: { - id: { from: fromData.resource, name: 'method' }, - }, - }, - cluster: { - action: getListResourceProvision, - params: { - resource: { from: fromData.resource, name: 'id' }, - }, - }, - datastore: { - action: getListResourceProvision, - params: { - resource: { from: fromData.resource, name: 'id' }, - }, - }, - host: { - action: getListResourceProvision, - params: { - resource: { from: fromData.resource, name: 'id' }, - }, - }, - image: { - action: getListResourceProvision, - params: { - resource: { from: fromData.resource, name: 'id' }, - }, - }, - network: { - action: getListResourceProvision, - params: { - resource: { from: fromData.resource, name: 'id' }, - }, - }, - template: { - action: getListResourceProvision, - params: { - resource: { from: fromData.resource, name: 'id' }, - }, - }, - vntemplate: { - action: getListResourceProvision, - params: { - resource: { from: fromData.resource, name: 'id' }, - }, - }, - log: { - action: getLogProvisions, - params: { - id: { from: fromData.resource, name: 'id' }, - }, - }, - defaults: { - action: getProvisionDefaults, - params: {}, - }, - }, - [POST]: { - null: { - action: createProvision, - params: { - resource: { from: fromData.postBody }, - }, - websocket: true, - }, - validate: { - action: validate, - params: { - resource: { from: fromData.postBody }, - }, - }, - host: { - poweroff: { - action: hostCommand, - params: { - action: { from: fromData.resource, name: 'id' }, - id: { from: fromData.resource, name: 'id2' }, - }, - }, - reboot: { - action: hostCommand, - params: { - action: { from: fromData.resource, name: 'id' }, - id: { from: fromData.resource, name: 'id2' }, - }, - }, - resume: { - action: hostCommand, - params: { - action: { from: fromData.resource, name: 'id' }, - id: { from: fromData.resource, name: 'id2' }, - }, - }, - ssh: { - action: hostCommandSSH, - params: { - action: { from: fromData.resource, name: 'id' }, - id: { from: fromData.resource, name: 'id2' }, - command: { from: fromData.postBody, name: 'command' }, - }, - }, - }, - }, - [DELETE]: { - null: { - action: deleteProvision, - params: { - id: { from: fromData.resource, name: 'method' }, - cleanup: { from: fromData.postBody, name: 'cleanup' }, - }, - websocket: true, - }, - datastore: { - action: deleteResource, - params: { - resource: { from: fromData.resource, name: 'method' }, - id: { from: fromData.resource, name: 'id' }, - }, - }, - flowtemplate: { - action: deleteResource, - params: { - resource: { from: fromData.resource, name: 'method' }, - id: { from: fromData.resource, name: 'id' }, - }, - }, - host: { - action: deleteResource, - params: { - resource: { from: fromData.resource, name: 'method' }, - id: { from: fromData.resource, name: 'id' }, - }, - }, - image: { - action: deleteResource, - params: { - resource: { from: fromData.resource, name: 'method' }, - id: { from: fromData.resource, name: 'id' }, - }, - }, - network: { - action: deleteResource, - params: { - resource: { from: fromData.resource, name: 'method' }, - id: { from: fromData.resource, name: 'id' }, - }, - }, - vntemplate: { - action: deleteResource, - params: { - resource: { from: fromData.resource, name: 'method' }, - id: { from: fromData.resource, name: 'id' }, - }, - }, - template: { - action: deleteResource, - params: { - resource: { from: fromData.resource, name: 'method' }, - id: { from: fromData.resource, name: 'id' }, - }, - }, - cluster: { - action: deleteResource, - params: { - resource: { from: fromData.resource, name: 'method' }, - id: { from: fromData.resource, name: 'id' }, - }, - }, - }, - [PUT]: { - configure: { - action: configureProvision, - params: { - id: { from: fromData.resource, name: 'id' }, - }, - websocket: true, - }, - host: { - action: configureHost, - params: { - id: { from: fromData.resource, name: 'id' }, - }, - }, - }, -} - -const provisionApi = { - routes, -} -module.exports = provisionApi diff --git a/src/fireedge/src/server/routes/api/oneprovision/provision/routes.js b/src/fireedge/src/server/routes/api/oneprovision/provision/routes.js new file mode 100644 index 0000000000..ea22672f9c --- /dev/null +++ b/src/fireedge/src/server/routes/api/oneprovision/provision/routes.js @@ -0,0 +1,397 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * + * * + * 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 * + * * + * http://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. * + * ------------------------------------------------------------------------- */ + +const { + httpMethod, + from: fromData, +} = require('server/utils/constants/defaults') +const { PROVISION } = require('server/routes/api/oneprovision/basepath') + +const { GET, POST, DELETE, PUT } = httpMethod +const basepath = `/${PROVISION}` +const { resource, postBody } = fromData + +const PROVISION_CLUSTER_RESOURCE = 'provision.clusterresource' +const PROVISION_DATASTORE_RESOURCE = 'provision.datastoreresource' +const PROVISION_HOST_RESOURCE = 'provision.hostresource' +const PROVISION_IMAGE_RESOURCE = 'provision.imageresource' +const PROVISION_NETWORK_RESOURCE = 'provision.networkresource' +const PROVISION_TEMPLATE_RESOURCE = 'provision.templateresource' +const PROVISION_VNTEMPLATE_RESOURCE = 'provision.vntemplateresource' +const PROVISION_LOGS = 'provision.logs' +const PROVISION_DEFAULTS = 'provision.defauls' +const PROVISION_LIST = 'provision.list' +const PROVISION_VALIDATE = 'provision.validate' +const PROVISION_HOST_POWEROFF = 'provision.hostpoweroff' +const PROVISION_HOST_REBOOT = 'provision.hostreboot' +const PROVISION_HOST_RESUME = 'provision.hostresume' +const PROVISION_CREATE = 'provision.create' +const PROVISION_HOST_SSH = 'provision.hostssh' +const PROVISION_DATASTORE = 'provision.datastore' +const PROVISION_FLOWTEMPLATE = 'provision.flowtemplate' +const PROVISION_DELETE_HOST_RESOURCE = 'provision.deletehostresource' +const PROVISION_DELETE_IMAGE_RESOURCE = 'provision.deleteimageresource' +const PROVISION_DELETE_NETWORK_RESOURCE = 'provision.deletenetworkresource' +const PROVISION_DELETE_VNTEMPLATE_RESOURCE = 'provision.deletevntemplate' +const PROVISION_DELETE_TEMPLATE_RESOURCE = 'provision.deletetemplateresource' +const PROVISION_DELETE_CLUSTER_RESOURCE = 'provision.deleteclusterresource' +const PROVISION_DELETE_PROVISION = 'provision.deleteprovision' +const PROVISION_UPDATE_CONFIGURE = 'provision.updateconfigure' +const PROVISION_UPDATE_HOST = 'provision.updatehost' + +const Actions = { + PROVISION_CLUSTER_RESOURCE, + PROVISION_DATASTORE_RESOURCE, + PROVISION_HOST_RESOURCE, + PROVISION_IMAGE_RESOURCE, + PROVISION_NETWORK_RESOURCE, + PROVISION_TEMPLATE_RESOURCE, + PROVISION_VNTEMPLATE_RESOURCE, + PROVISION_LOGS, + PROVISION_DEFAULTS, + PROVISION_LIST, + PROVISION_VALIDATE, + PROVISION_HOST_POWEROFF, + PROVISION_HOST_REBOOT, + PROVISION_HOST_RESUME, + PROVISION_CREATE, + PROVISION_HOST_SSH, + PROVISION_DATASTORE, + PROVISION_FLOWTEMPLATE, + PROVISION_DELETE_HOST_RESOURCE, + PROVISION_DELETE_IMAGE_RESOURCE, + PROVISION_DELETE_NETWORK_RESOURCE, + PROVISION_DELETE_VNTEMPLATE_RESOURCE, + PROVISION_DELETE_TEMPLATE_RESOURCE, + PROVISION_DELETE_CLUSTER_RESOURCE, + PROVISION_DELETE_PROVISION, + PROVISION_UPDATE_CONFIGURE, + PROVISION_UPDATE_HOST, +} + +module.exports = { + Actions, + Commands: { + [PROVISION_CLUSTER_RESOURCE]: { + path: `${basepath}/cluster/:resource`, + httpMethod: GET, + auth: true, + params: { + resource: { + from: resource, + }, + }, + }, + [PROVISION_DATASTORE_RESOURCE]: { + path: `${basepath}/datastore/:resource`, + httpMethod: GET, + auth: true, + params: { + resource: { + from: resource, + }, + }, + }, + [PROVISION_HOST_RESOURCE]: { + path: `${basepath}/host/:resource`, + httpMethod: GET, + auth: true, + params: { + resource: { + from: resource, + }, + }, + }, + [PROVISION_IMAGE_RESOURCE]: { + path: `${basepath}/image/:resource`, + httpMethod: GET, + auth: true, + params: { + resource: { + from: resource, + }, + }, + }, + [PROVISION_NETWORK_RESOURCE]: { + path: `${basepath}/network/:resource`, + httpMethod: GET, + auth: true, + params: { + resource: { + from: resource, + }, + }, + }, + [PROVISION_TEMPLATE_RESOURCE]: { + path: `${basepath}/template/:resource`, + httpMethod: GET, + auth: true, + params: { + resource: { + from: resource, + }, + }, + }, + [PROVISION_VNTEMPLATE_RESOURCE]: { + path: `${basepath}/vntemplate/:resource`, + httpMethod: GET, + auth: true, + params: { + resource: { + from: resource, + }, + }, + }, + [PROVISION_LOGS]: { + path: `${basepath}/log/:id`, + httpMethod: GET, + auth: true, + params: { + id: { + from: resource, + }, + }, + }, + [PROVISION_DEFAULTS]: { + path: `${basepath}/defaults`, + httpMethod: GET, + auth: true, + }, + [PROVISION_LIST]: { + path: `${basepath}/:id?`, + httpMethod: GET, + auth: true, + params: { + id: { + from: resource, + }, + }, + }, + [PROVISION_VALIDATE]: { + path: `${basepath}/validate`, + httpMethod: POST, + auth: true, + params: { + resource: { + from: postBody, + }, + }, + }, + [PROVISION_HOST_POWEROFF]: { + path: `${basepath}/host/poweroff/:action/:id`, + httpMethod: POST, + auth: true, + params: { + action: { + from: resource, + }, + id: { + from: resource, + }, + }, + }, + [PROVISION_HOST_REBOOT]: { + path: `${basepath}/host/reboot/:action/:id`, + httpMethod: POST, + auth: true, + params: { + action: { + from: resource, + }, + id: { + from: resource, + }, + }, + }, + [PROVISION_HOST_RESUME]: { + path: `${basepath}/host/resume/:action/:id`, + httpMethod: POST, + auth: true, + params: { + action: { + from: resource, + }, + id: { + from: resource, + }, + }, + }, + [PROVISION_CREATE]: { + path: `${basepath}`, + httpMethod: POST, + auth: true, + params: { + resource: { + from: postBody, + all: true, + }, + }, + }, + [PROVISION_HOST_SSH]: { + path: `${basepath}/host/ssh/:action/:id/:command`, + httpMethod: DELETE, + auth: true, + params: { + action: { + from: resource, + }, + id: { + from: resource, + }, + command: { + from: postBody, + }, + }, + }, + [PROVISION_DATASTORE]: { + path: `${basepath}/datastore/:resource/:id`, + httpMethod: DELETE, + auth: true, + params: { + resource: { + from: resource, + }, + id: { + from: resource, + }, + }, + }, + [PROVISION_FLOWTEMPLATE]: { + path: `${basepath}/flowtemplate/:resource/:id`, + httpMethod: DELETE, + auth: true, + params: { + resource: { + from: resource, + }, + id: { + from: resource, + }, + }, + }, + [PROVISION_DELETE_HOST_RESOURCE]: { + path: `${basepath}/host/:resource/:id`, + httpMethod: DELETE, + auth: true, + params: { + resource: { + from: resource, + }, + id: { + from: resource, + }, + }, + }, + [PROVISION_DELETE_IMAGE_RESOURCE]: { + path: `${basepath}/image/:resource/:id`, + httpMethod: DELETE, + auth: true, + params: { + resource: { + from: resource, + }, + id: { + from: resource, + }, + }, + }, + [PROVISION_DELETE_NETWORK_RESOURCE]: { + path: `${basepath}/network/:resource/:id`, + httpMethod: DELETE, + auth: true, + params: { + resource: { + from: resource, + }, + id: { + from: resource, + }, + }, + }, + [PROVISION_DELETE_VNTEMPLATE_RESOURCE]: { + path: `${basepath}/vntemplate/:resource/:id`, + httpMethod: DELETE, + auth: true, + params: { + resource: { + from: resource, + }, + id: { + from: resource, + }, + }, + }, + [PROVISION_DELETE_TEMPLATE_RESOURCE]: { + path: `${basepath}/template/:resource/:id`, + httpMethod: DELETE, + auth: true, + params: { + resource: { + from: resource, + }, + id: { + from: resource, + }, + }, + }, + [PROVISION_DELETE_CLUSTER_RESOURCE]: { + path: `${basepath}/cluster/:resource/:id`, + httpMethod: DELETE, + auth: true, + params: { + resource: { + from: resource, + }, + id: { + from: resource, + }, + }, + }, + [PROVISION_DELETE_PROVISION]: { + path: `${basepath}/:id`, + httpMethod: DELETE, + auth: true, + params: { + id: { + from: resource, + }, + cleanup: { + from: postBody, + }, + }, + }, + [PROVISION_UPDATE_CONFIGURE]: { + path: `${basepath}/configure/:id`, + httpMethod: PUT, + auth: true, + params: { + id: { + from: resource, + }, + }, + }, + [PROVISION_UPDATE_HOST]: { + path: `${basepath}/host/:id`, + httpMethod: PUT, + auth: true, + params: { + id: { + from: resource, + }, + }, + }, + }, +} diff --git a/src/fireedge/src/server/routes/api/oneprovision/template/functions.js b/src/fireedge/src/server/routes/api/oneprovision/template/functions.js index c25ef70e18..6eb5388038 100644 --- a/src/fireedge/src/server/routes/api/oneprovision/template/functions.js +++ b/src/fireedge/src/server/routes/api/oneprovision/template/functions.js @@ -15,12 +15,7 @@ * ------------------------------------------------------------------------- */ const { Validator } = require('jsonschema') -const { - defaultFolderTmpProvision, - defaultCommandProvisionTemplate, -} = require('server/utils/constants/defaults') - -const { ok, internalServerError } = require('server/utils/constants/http-codes') +const { defaults, httpCodes } = require('server/utils/constants') const { httpResponse, parsePostData, @@ -35,6 +30,8 @@ const { } = require('server/routes/api/oneprovision/utils') const { provider } = require('server/routes/api/oneprovision/schemas') +const { defaultFolderTmpProvision, defaultCommandProvisionTemplate } = defaults +const { ok, internalServerError } = httpCodes const httpInternalError = httpResponse(internalServerError, '', '') /** diff --git a/src/fireedge/src/server/routes/api/oneprovision/template/index.js b/src/fireedge/src/server/routes/api/oneprovision/template/index.js deleted file mode 100644 index a65e8f9cea..0000000000 --- a/src/fireedge/src/server/routes/api/oneprovision/template/index.js +++ /dev/null @@ -1,74 +0,0 @@ -/* ------------------------------------------------------------------------- * - * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * - * * - * 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 * - * * - * http://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. * - * ------------------------------------------------------------------------- */ - -const { from: fromData } = require('server/utils/constants/defaults') -const { - getListProvisionTemplates, - createProvisionTemplate, - instantiateProvisionTemplate, - updateProvisionTemplate, - deleteProvisionTemplate, -} = require('server/routes/api/oneprovision/template/functions') -const { httpMethod } = require('server/utils/constants/defaults') - -const { GET, POST, PUT, DELETE } = httpMethod - -const routes = { - [GET]: { - null: { - action: getListProvisionTemplates, - params: { - id: { from: fromData.resource, name: 'method' }, - }, - }, - }, - [POST]: { - null: { - action: createProvisionTemplate, - params: { - resource: { from: fromData.postBody }, - }, - }, - instantiate: { - action: instantiateProvisionTemplate, - params: { - id: { from: fromData.resource, name: 'id' }, - }, - }, - }, - [PUT]: { - null: { - action: updateProvisionTemplate, - params: { - resource: { from: fromData.postBody }, - id: { from: fromData.resource, name: 'method' }, - }, - }, - }, - [DELETE]: { - null: { - action: deleteProvisionTemplate, - params: { - id: { from: fromData.resource, name: 'method' }, - }, - }, - }, -} - -const provisionTemplateApi = { - routes, -} -module.exports = provisionTemplateApi diff --git a/src/fireedge/src/server/routes/api/oneprovision/template/routes.js b/src/fireedge/src/server/routes/api/oneprovision/template/routes.js new file mode 100644 index 0000000000..cbe4bcb7e2 --- /dev/null +++ b/src/fireedge/src/server/routes/api/oneprovision/template/routes.js @@ -0,0 +1,100 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * + * * + * 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 * + * * + * http://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. * + * ------------------------------------------------------------------------- */ + +const { from: fromData } = require('server/utils/constants/defaults') +const { httpMethod } = require('server/utils/constants/defaults') +const { + PROVISION_TEMPLATE, +} = require('server/routes/api/oneprovision/basepath') + +const basepath = `/${PROVISION_TEMPLATE}` +const { GET, POST, PUT, DELETE } = httpMethod +const { resource, postBody } = fromData + +const PROVISIONTEMPLATE_SHOW = 'provisiontemplate.show' +const PROVISIONTEMPLATE_INSTANTIATE = 'provisiontemplate.instantiate' +const PROVISIONTEMPLATE_CREATE = 'provisiontemplate.create' +const PROVISIONTEMPLATE_UPDATE = 'provisiontemplate.update' +const PROVISIONTEMPLATE_DELETE = 'provisiontemplate.delete' + +const Actions = { + PROVISIONTEMPLATE_SHOW, + PROVISIONTEMPLATE_INSTANTIATE, + PROVISIONTEMPLATE_CREATE, + PROVISIONTEMPLATE_UPDATE, + PROVISIONTEMPLATE_DELETE, +} + +module.exports = { + Actions, + Commands: { + [PROVISIONTEMPLATE_SHOW]: { + path: `${basepath}/:id`, + httpMethod: GET, + auth: true, + params: { + id: { + from: resource, + }, + }, + }, + [PROVISIONTEMPLATE_INSTANTIATE]: { + path: `${basepath}/instantiate/:id`, + httpMethod: POST, + auth: true, + params: { + id: { + from: resource, + }, + }, + }, + [PROVISIONTEMPLATE_CREATE]: { + path: `${basepath}`, + httpMethod: POST, + auth: true, + params: { + resource: { + from: postBody, + all: true, + }, + }, + }, + [PROVISIONTEMPLATE_UPDATE]: { + path: `${basepath}/:id`, + httpMethod: PUT, + auth: true, + params: { + resource: { + from: postBody, + all: true, + }, + id: { + from: resource, + }, + }, + }, + [PROVISIONTEMPLATE_DELETE]: { + path: `${basepath}/:id`, + httpMethod: DELETE, + auth: true, + params: { + id: { + from: resource, + }, + }, + }, + }, +} diff --git a/src/fireedge/src/server/routes/api/sunstone/basepath.js b/src/fireedge/src/server/routes/api/sunstone/basepath.js new file mode 100644 index 0000000000..6681f23fe1 --- /dev/null +++ b/src/fireedge/src/server/routes/api/sunstone/basepath.js @@ -0,0 +1,17 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * + * * + * 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 * + * * + * http://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. * + * ------------------------------------------------------------------------- */ + +module.exports = 'sunstone' diff --git a/src/fireedge/src/server/routes/api/sunstone/functions.js b/src/fireedge/src/server/routes/api/sunstone/functions.js index 0fd6c2d892..d6aa715288 100644 --- a/src/fireedge/src/server/routes/api/sunstone/functions.js +++ b/src/fireedge/src/server/routes/api/sunstone/functions.js @@ -16,7 +16,7 @@ const { parse } = require('yaml') const { getSunstoneConfig } = require('server/utils/yml') -const { defaultEmptyFunction } = require('server/utils/constants/defaults') +const { defaults, httpCodes } = require('server/utils/constants') const { existsFile, httpResponse, getFiles } = require('server/utils/server') const { sensitiveDataRemoverConfig } = require('server/utils/opennebula') const { Actions: ActionsUser } = require('server/utils/constants/commands/user') @@ -24,14 +24,9 @@ const { Actions: ActionsGroup, } = require('server/utils/constants/commands/group') -const { - ok, - internalServerError, - notFound, -} = require('server/utils/constants/http-codes') - +const { defaultEmptyFunction } = defaults +const { ok, internalServerError, notFound } = httpCodes const sensitiveData = ['support_url', 'support_token'] - const httpInternalError = httpResponse(internalServerError, '', '') /** diff --git a/src/fireedge/src/server/routes/api/sunstone/index.js b/src/fireedge/src/server/routes/api/sunstone/index.js index 2edd57bfd6..3051a3f709 100644 --- a/src/fireedge/src/server/routes/api/sunstone/index.js +++ b/src/fireedge/src/server/routes/api/sunstone/index.js @@ -14,14 +14,18 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const { setApiRoutes } = require('server/utils/server') -const { routes: sunstoneRoutes } = require('./routes') +const { Actions, Commands } = require('server/routes/api/sunstone/routes') +const { getConfig, getViews } = require('server/routes/api/sunstone/functions') -const { SUNSTONE } = require('./string-routes') +const { SUNSTONE_VIEWS, SUNSTONE_CONFIG } = Actions -const functionRoutes = { - private: setApiRoutes(sunstoneRoutes, SUNSTONE), - public: [], -} - -module.exports = functionRoutes +module.exports = [ + { + ...Commands[SUNSTONE_VIEWS], + action: getViews, + }, + { + ...Commands[SUNSTONE_CONFIG], + action: getConfig, + }, +] diff --git a/src/fireedge/src/server/routes/api/sunstone/routes.js b/src/fireedge/src/server/routes/api/sunstone/routes.js index e0fcacd984..7b427993d0 100644 --- a/src/fireedge/src/server/routes/api/sunstone/routes.js +++ b/src/fireedge/src/server/routes/api/sunstone/routes.js @@ -15,24 +15,31 @@ * ------------------------------------------------------------------------- */ const { httpMethod } = require('server/utils/constants/defaults') -const { getConfig, getViews } = require('server/routes/api/sunstone/functions') -const { GET } = httpMethod +const SUNSTONE = require('server/routes/api/sunstone/basepath') -const routes = { - [GET]: { - views: { - action: getViews, - params: {}, +const { GET } = httpMethod +const basepath = `/${SUNSTONE}` + +const SUNSTONE_VIEWS = 'sunstone.views' +const SUNSTONE_CONFIG = 'sunstone.config' + +const Actions = { + SUNSTONE_VIEWS, + SUNSTONE_CONFIG, +} + +module.exports = { + Actions, + Commands: { + [SUNSTONE_VIEWS]: { + path: `${basepath}/views`, + httpMethod: GET, + auth: true, }, - config: { - action: getConfig, - params: {}, + [SUNSTONE_CONFIG]: { + path: `${basepath}/config`, + httpMethod: GET, + auth: true, }, }, } - -const sunstoneApi = { - routes, -} - -module.exports = sunstoneApi diff --git a/src/fireedge/src/server/routes/api/sunstone/string-routes.js b/src/fireedge/src/server/routes/api/sunstone/string-routes.js deleted file mode 100644 index 25b2dad99e..0000000000 --- a/src/fireedge/src/server/routes/api/sunstone/string-routes.js +++ /dev/null @@ -1,23 +0,0 @@ -/* ------------------------------------------------------------------------- * - * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * - * * - * 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 * - * * - * http://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. * - * ------------------------------------------------------------------------- */ - -const SUNSTONE = 'sunstone' - -const Actions = { - SUNSTONE, -} - -module.exports = Actions diff --git a/src/fireedge/src/server/routes/api/vcenter/basepath.js b/src/fireedge/src/server/routes/api/vcenter/basepath.js new file mode 100644 index 0000000000..f993aa27bf --- /dev/null +++ b/src/fireedge/src/server/routes/api/vcenter/basepath.js @@ -0,0 +1,17 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * + * * + * 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 * + * * + * http://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. * + * ------------------------------------------------------------------------- */ + +module.exports = 'vcenter' diff --git a/src/fireedge/src/server/routes/api/vcenter/functions.js b/src/fireedge/src/server/routes/api/vcenter/functions.js index 07cbcbd5b2..60e250b6d8 100644 --- a/src/fireedge/src/server/routes/api/vcenter/functions.js +++ b/src/fireedge/src/server/routes/api/vcenter/functions.js @@ -13,26 +13,17 @@ * See the License for the specific language governing permissions and * * limitations under the License. * * ------------------------------------------------------------------------- */ - -const { - defaultEmptyFunction, - defaultCommandVcenter, -} = require('server/utils/constants/defaults') - -const { - ok, - internalServerError, - badRequest, -} = require('server/utils/constants/http-codes') +const { defaults, httpCodes } = require('server/utils/constants') const { httpResponse, executeCommand } = require('server/utils/server') const { consoleParseToString, consoleParseToJSON, } = require('server/utils/opennebula') const { resources } = require('server/routes/api/vcenter/command-flags') - const { getSunstoneConfig } = require('server/utils/yml') +const { defaultEmptyFunction, defaultCommandVcenter } = defaults +const { ok, internalServerError, badRequest } = httpCodes const httpBadRequest = httpResponse(badRequest, '', '') const appConfig = getSunstoneConfig() const prependCommand = appConfig.vcenter_prepend_command || '' diff --git a/src/fireedge/src/server/routes/api/vcenter/index.js b/src/fireedge/src/server/routes/api/vcenter/index.js index f215035bde..1b4d56431b 100644 --- a/src/fireedge/src/server/routes/api/vcenter/index.js +++ b/src/fireedge/src/server/routes/api/vcenter/index.js @@ -14,13 +14,42 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const { setApiRoutes } = require('server/utils/server') -const { routes: vcenterRoutes } = require('server/routes/api/vcenter/routes') -const { VCENTER } = require('server/routes/api/vcenter/string-routes') +const { Actions, Commands } = require('server/routes/api/vcenter/routes') +const { + importVcenter, + list, + listAll, + cleartags, + hosts, +} = require('server/routes/api/vcenter/functions') -const functionRoutes = { - private: setApiRoutes(vcenterRoutes, VCENTER), - public: [], -} +const { + VCENTER_CLEARTAGS, + VCENTER_HOSTS, + VCENTER_IMPORT, + VCENTER_LISTALL, + VCENTER_LIST, +} = Actions -module.exports = functionRoutes +module.exports = [ + { + ...Commands[VCENTER_CLEARTAGS], + action: cleartags, + }, + { + ...Commands[VCENTER_HOSTS], + action: hosts, + }, + { + ...Commands[VCENTER_IMPORT], + actions: importVcenter, + }, + { + ...Commands[VCENTER_LISTALL], + actions: listAll, + }, + { + ...Commands[VCENTER_LIST], + actions: list, + }, +] diff --git a/src/fireedge/src/server/routes/api/vcenter/routes.js b/src/fireedge/src/server/routes/api/vcenter/routes.js index 1eee5fb7a5..59074a1469 100644 --- a/src/fireedge/src/server/routes/api/vcenter/routes.js +++ b/src/fireedge/src/server/routes/api/vcenter/routes.js @@ -18,108 +18,110 @@ const { httpMethod, from: fromData, } = require('server/utils/constants/defaults') -const { - importVcenter, - list, - listAll, - cleartags, - hosts, -} = require('server/routes/api/vcenter/functions') -const { POST, GET } = httpMethod +const VCENTER = require('server/routes/api/vcenter/basepath') -const routes = { - [POST]: { - import: { - action: importVcenter, +const basepath = `/${VCENTER}` +const { POST, GET } = httpMethod +const { resource, postBody, query } = fromData + +const VCENTER_CLEARTAGS = 'vcenter.cleartags' +const VCENTER_HOSTS = 'vcenter.hosts' +const VCENTER_IMPORT = 'vcenter.import' +const VCENTER_LISTALL = 'vcenter.listall' +const VCENTER_LIST = 'vcenter.list' +const Actions = { + VCENTER_CLEARTAGS, + VCENTER_HOSTS, + VCENTER_IMPORT, + VCENTER_LISTALL, + VCENTER_LIST, +} + +module.exports = { + Actions, + Commands: { + [VCENTER_CLEARTAGS]: { + path: `${basepath}/cleartags/:id`, + httpMethod: POST, + auth: true, params: { - vobject: { - from: fromData.resource, - name: 'id', - }, - host: { - from: fromData.postBody, - name: 'host', - }, - datastore: { - from: fromData.postBody, - name: 'datastore', - }, id: { - from: fromData.postBody, - name: 'id', - }, - answers: { - from: fromData.postBody, - name: 'answers', + from: resource, }, }, }, - cleartags: { - action: cleartags, - params: { - id: { - from: fromData.resource, - name: 'id', - }, - }, - }, - hosts: { - action: hosts, + [VCENTER_HOSTS]: { + path: `${basepath}/hosts`, + httpMethod: POST, + auth: true, params: { vcenter: { - from: fromData.postBody, + from: postBody, name: 'vcenter', }, user: { - from: fromData.postBody, + from: postBody, name: 'user', }, pass: { - from: fromData.postBody, + from: postBody, name: 'pass', }, }, }, - }, - [GET]: { - null: { - action: list, + [VCENTER_IMPORT]: { + path: `${basepath}/:vobject`, + httpMethod: POST, + auth: true, params: { vobject: { - from: fromData.resource, - name: 'method', + from: resource, }, host: { - from: fromData.query, - name: 'host', + from: postBody, }, datastore: { - from: fromData.query, - name: 'datastore', + from: postBody, + }, + id: { + from: postBody, + }, + answers: { + from: postBody, }, }, }, - listall: { - action: listAll, + [VCENTER_LISTALL]: { + path: `${basepath}/listall/:vobject`, + httpMethod: GET, + auth: true, params: { vobject: { - from: fromData.resource, - name: 'id', + from: resource, }, host: { - from: fromData.query, - name: 'host', + from: query, }, datastore: { - from: fromData.query, - name: 'datastore', + from: query, + }, + }, + }, + [VCENTER_LIST]: { + path: `${basepath}/:vobject`, + httpMethod: GET, + auth: true, + params: { + vobject: { + from: resource, + }, + host: { + from: query, + }, + datastore: { + from: query, }, }, }, }, } - -const authApi = { - routes, -} -module.exports = authApi diff --git a/src/fireedge/src/server/routes/api/vcenter/string-routes.js b/src/fireedge/src/server/routes/api/vcenter/string-routes.js deleted file mode 100644 index 29ea6b3d4a..0000000000 --- a/src/fireedge/src/server/routes/api/vcenter/string-routes.js +++ /dev/null @@ -1,23 +0,0 @@ -/* ------------------------------------------------------------------------- * - * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * - * * - * 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 * - * * - * http://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. * - * ------------------------------------------------------------------------- */ - -const VCENTER = 'vcenter' - -const Actions = { - VCENTER, -} - -module.exports = Actions diff --git a/src/fireedge/src/server/routes/api/vm/basepath.js b/src/fireedge/src/server/routes/api/vm/basepath.js new file mode 100644 index 0000000000..11a938d650 --- /dev/null +++ b/src/fireedge/src/server/routes/api/vm/basepath.js @@ -0,0 +1,17 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * + * * + * 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 * + * * + * http://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. * + * ------------------------------------------------------------------------- */ + +module.exports = 'vm' diff --git a/src/fireedge/src/server/routes/api/vm/functions.js b/src/fireedge/src/server/routes/api/vm/functions.js index bfffc62e90..4ac4a9947c 100644 --- a/src/fireedge/src/server/routes/api/vm/functions.js +++ b/src/fireedge/src/server/routes/api/vm/functions.js @@ -13,21 +13,13 @@ * See the License for the specific language governing permissions and * * limitations under the License. * * ------------------------------------------------------------------------- */ - -const { - defaultEmptyFunction, - defaultCommandVM, -} = require('server/utils/constants/defaults') - -const { - ok, - internalServerError, - badRequest, -} = require('server/utils/constants/http-codes') +const { defaults, httpCodes } = require('server/utils/constants') const { httpResponse, executeCommand } = require('server/utils/server') - const { getSunstoneConfig } = require('server/utils/yml') +const { defaultEmptyFunction, defaultCommandVM } = defaults + +const { ok, internalServerError, badRequest } = httpCodes const httpBadRequest = httpResponse(badRequest, '', '') const appConfig = getSunstoneConfig() const prependCommand = appConfig.sunstone_prepend || '' diff --git a/src/fireedge/src/server/routes/api/vm/index.js b/src/fireedge/src/server/routes/api/vm/index.js index 1f15fd9d3d..09cfb6f3f5 100644 --- a/src/fireedge/src/server/routes/api/vm/index.js +++ b/src/fireedge/src/server/routes/api/vm/index.js @@ -14,13 +14,14 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const { setApiRoutes } = require('server/utils/server') -const { routes: vmRoutes } = require('server/routes/api/vm/routes') -const { VM } = require('server/routes/api/vm/string-routes') +const { Actions, Commands } = require('server/routes/api/vm/routes') +const { saveAsTemplate } = require('server/routes/api/vm/functions') -const functionRoutes = { - private: setApiRoutes(vmRoutes, VM), - public: [], -} +const { VM_SAVEASTEMPLATE } = Actions -module.exports = functionRoutes +module.exports = [ + { + ...Commands[VM_SAVEASTEMPLATE], + action: saveAsTemplate, + }, +] diff --git a/src/fireedge/src/server/routes/api/vm/routes.js b/src/fireedge/src/server/routes/api/vm/routes.js index 24e7cd83f7..888f371b44 100644 --- a/src/fireedge/src/server/routes/api/vm/routes.js +++ b/src/fireedge/src/server/routes/api/vm/routes.js @@ -18,32 +18,35 @@ const { httpMethod, from: fromData, } = require('server/utils/constants/defaults') -const { saveAsTemplate } = require('server/routes/api/vm/functions') -const { POST } = httpMethod +const VM = require('server/routes/api/vm/basepath') -const routes = { - [POST]: { - save: { - action: saveAsTemplate, +const basepath = `/${VM}` +const { POST } = httpMethod +const { resource, postBody } = fromData + +const VM_SAVEASTEMPLATE = 'vm.saveastemplate' +const Actions = { + VM_SAVEASTEMPLATE, +} + +module.exports = { + Actions, + Commands: { + [VM_SAVEASTEMPLATE]: { + path: `${basepath}/save/:id`, + httpMethod: POST, + auth: true, params: { id: { - from: fromData.resource, - name: 'id', + from: resource, }, name: { - from: fromData.postBody, - name: 'name', + from: postBody, }, persistent: { - from: fromData.postBody, - name: 'persistent', + from: postBody, }, }, }, }, } - -const authApi = { - routes, -} -module.exports = authApi diff --git a/src/fireedge/src/server/routes/api/zendesk/basepath.js b/src/fireedge/src/server/routes/api/zendesk/basepath.js new file mode 100644 index 0000000000..82af8ed713 --- /dev/null +++ b/src/fireedge/src/server/routes/api/zendesk/basepath.js @@ -0,0 +1,17 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * + * * + * 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 * + * * + * http://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. * + * ------------------------------------------------------------------------- */ + +module.exports = 'zendesk' diff --git a/src/fireedge/src/server/routes/api/zendesk/functions.js b/src/fireedge/src/server/routes/api/zendesk/functions.js index fcc186af24..084491f036 100644 --- a/src/fireedge/src/server/routes/api/zendesk/functions.js +++ b/src/fireedge/src/server/routes/api/zendesk/functions.js @@ -17,21 +17,25 @@ const { env } = require('process') const zendesk = require('node-zendesk') const { getSunstoneConfig } = require('server/utils/yml') -const { - defaultEmptyFunction, - defaultSeverities, - defaultWebpackMode, -} = require('server/utils/constants/defaults') +const { defaults, httpCodes } = require('server/utils/constants') const { httpResponse } = require('server/utils/server') const { getSession } = require('server/routes/api/zendesk/utils') -const { - ok, - internalServerError, - badRequest, - unauthorized, -} = require('server/utils/constants/http-codes') +const { defaultEmptyFunction, defaultSeverities, defaultWebpackMode } = defaults +const { ok, internalServerError, badRequest, unauthorized } = httpCodes +const httpBadRequest = httpResponse(badRequest, '', '') + +/** + * Format create ticket. + * + * @param {object} configFormatCreate - config format + * @param {string} configFormatCreate.subject - subject + * @param {string} configFormatCreate.body - body + * @param {string} configFormatCreate.version - one version + * @param {string} configFormatCreate.severity - ticket severity + * @returns {object|undefined} format message create ticket + */ const formatCreate = ({ subject = '', body = '', @@ -59,6 +63,15 @@ const formatCreate = ({ return rtn } +/** + * Format comment. + * + * @param {object} configFormatComment - config format + * @param {string} configFormatComment.body - body + * @param {string} configFormatComment.solved - solved + * @param {string[]} configFormatComment.attachments - attachments + * @returns {object|undefined} format comment + */ const formatComment = ({ body = '', solved = '', attachments = [] }) => { let rtn if (body) { @@ -81,6 +94,13 @@ const formatComment = ({ body = '', solved = '', attachments = [] }) => { return rtn } +/** + * Parse Buffer error. + * + * @param {object} err - buffer error + * @param {string} err.error - buffer error + * @returns {string} string error + */ const parseBufferError = (err) => { let rtn = '' let errorJson = {} @@ -97,8 +117,6 @@ const parseBufferError = (err) => { return rtn } -const httpBadRequest = httpResponse(badRequest, '', '') - /** * Login on Zendesk. * diff --git a/src/fireedge/src/server/routes/api/zendesk/index.js b/src/fireedge/src/server/routes/api/zendesk/index.js index 5ed2132865..2d020816f1 100644 --- a/src/fireedge/src/server/routes/api/zendesk/index.js +++ b/src/fireedge/src/server/routes/api/zendesk/index.js @@ -14,13 +14,42 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const { setApiRoutes } = require('server/utils/server') -const { routes: zendeskRoutes } = require('server/routes/api/zendesk/routes') -const { ZENDESK } = require('server/routes/api/zendesk/string-routes') +const { Actions, Commands } = require('server/routes/api/zendesk/routes') +const { + login, + list, + comments, + create, + update, +} = require('server/routes/api/zendesk/functions') -const functionRoutes = { - private: setApiRoutes(zendeskRoutes, ZENDESK), - public: [], -} +const { + ZENDESK_LOGIN, + ZENDESK_CREATE, + ZENDESK_UPDATE, + ZENDESK_COMMENT, + ZENDESK_LIST, +} = Actions -module.exports = functionRoutes +module.exports = [ + { + ...Commands[ZENDESK_LOGIN], + action: login, + }, + { + ...Commands[ZENDESK_CREATE], + action: create, + }, + { + ...Commands[ZENDESK_UPDATE], + action: update, + }, + { + ...Commands[ZENDESK_COMMENT], + action: comments, + }, + { + ...Commands[ZENDESK_LIST], + action: list, + }, +] diff --git a/src/fireedge/src/server/routes/api/zendesk/routes.js b/src/fireedge/src/server/routes/api/zendesk/routes.js index f50a291cec..f43ab8a7a0 100644 --- a/src/fireedge/src/server/routes/api/zendesk/routes.js +++ b/src/fireedge/src/server/routes/api/zendesk/routes.js @@ -18,93 +18,94 @@ const { httpMethod, from: fromData, } = require('server/utils/constants/defaults') -const { - login, - list, - comments, - create, - update, -} = require('server/routes/api/zendesk/functions') -const { POST, GET, PUT } = httpMethod +const ZENDESK = require('server/routes/api/zendesk/basepath') -const routes = { - [POST]: { - login: { - action: login, +const { POST, GET, UPDATE } = httpMethod +const basepath = `/${ZENDESK}` +const { resource, postBody } = fromData + +const ZENDESK_LOGIN = 'zendesk.login' +const ZENDESK_CREATE = 'zendesk.create' +const ZENDESK_UPDATE = 'zendesk.update' +const ZENDESK_COMMENT = 'zendesk.comment' +const ZENDESK_LIST = 'zendesk.list' + +const Actions = { + ZENDESK_LOGIN, + ZENDESK_CREATE, + ZENDESK_UPDATE, + ZENDESK_COMMENT, + ZENDESK_LIST, +} + +module.exports = { + Actions, + Commands: { + [ZENDESK_LOGIN]: { + path: `${basepath}/login`, + httpMethod: POST, + auth: true, params: { user: { - from: fromData.postBody, - name: 'user', + from: postBody, }, pass: { - from: fromData.postBody, - name: 'pass', + from: postBody, }, }, }, - null: { - action: create, + [ZENDESK_CREATE]: { + path: `${basepath}`, + httpMethod: POST, + auth: true, params: { subject: { - from: fromData.postBody, - name: 'subject', + from: postBody, }, body: { - from: fromData.postBody, - name: 'body', + from: postBody, }, version: { - from: fromData.postBody, - name: 'version', + from: postBody, }, severity: { - from: fromData.postBody, - name: 'severity', + from: postBody, }, }, }, - }, - [PUT]: { - null: { - action: update, + [ZENDESK_UPDATE]: { + path: `${basepath}/:id`, + httpMethod: UPDATE, + auth: true, params: { id: { - from: fromData.resource, - name: 'method', + from: resource, }, body: { - from: fromData.postBody, - name: 'body', + from: postBody, }, solved: { - from: fromData.postBody, - name: 'solved', + from: postBody, }, attachments: { from: 'files', - name: 'attachments', }, }, }, - }, - [GET]: { - null: { - action: list, - params: {}, - }, - comments: { - action: comments, + [ZENDESK_COMMENT]: { + path: `${basepath}/comments/:id`, + httpMethod: GET, + auth: true, params: { id: { - from: fromData.resource, - name: 'id', + from: resource, }, }, }, + [ZENDESK_LIST]: { + path: `${basepath}/:id`, + httpMethod: GET, + auth: true, + }, }, } - -const authApi = { - routes, -} -module.exports = authApi diff --git a/src/fireedge/src/server/routes/api/zendesk/string-routes.js b/src/fireedge/src/server/routes/api/zendesk/string-routes.js deleted file mode 100644 index 17ff2f4bca..0000000000 --- a/src/fireedge/src/server/routes/api/zendesk/string-routes.js +++ /dev/null @@ -1,23 +0,0 @@ -/* ------------------------------------------------------------------------- * - * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * - * * - * 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 * - * * - * http://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. * - * ------------------------------------------------------------------------- */ - -const ZENDESK = 'zendesk' - -const Actions = { - ZENDESK, -} - -module.exports = Actions diff --git a/src/fireedge/src/server/routes/entrypoints/Api.js b/src/fireedge/src/server/routes/entrypoints/Api.js deleted file mode 100644 index f034d28d9e..0000000000 --- a/src/fireedge/src/server/routes/entrypoints/Api.js +++ /dev/null @@ -1,221 +0,0 @@ -/* ------------------------------------------------------------------------- * - * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * - * * - * 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 * - * * - * http://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. * - * ------------------------------------------------------------------------- */ -/* eslint-disable indent */ - -const { env } = require('process') -const express = require('express') -const { resolve } = require('path') -const Worker = require('tiny-worker') -const { defaults, httpCodes, params } = require('server/utils/constants') -const { getFireedgeConfig } = require('server/utils/yml') - -const { - opennebulaConnect, - checkIfIsARouteFunction, - commandXMLRPC, - checkOpennebulaCommand, - responseOpennebula, - httpResponse, - getDataZone, - fillResourceforHookConnection, -} = require('../../utils') - -const { writeInLogger } = require('../../utils/logger') - -const { - validateResourceAndSession, - setOptionalParameters, - setOptionalQueries, - clearStates, - getParamsState, - getQueriesState, - getIdUserOpennebula, - getUserOpennebula, - getPassOpennebula, -} = require('./middlewares') - -const { - defaultMessageInvalidZone, - from: fromData, - defaultOpennebulaZones, - defaultWebpackMode, -} = defaults - -const router = express.Router() - -express() - -/** - * Get route parameters. - * - * @returns {Array} valid express route - */ -const routeParameters = () => - Object.keys(params).reduce( - (resources, param) => String(resources).concat(`/:${params[param]}?`), - '/:resource?' - ) - -router.all( - routeParameters(), - [validateResourceAndSession, setOptionalParameters, setOptionalQueries], - (req, res, next) => { - const { internalServerError, ok, methodNotAllowed, notFound } = httpCodes - const { method: httpMethod } = req - res.locals.httpCode = httpResponse(internalServerError) - const { zone } = getQueriesState() - - // get fireedge config - const appConfig = getFireedgeConfig() - - // set first zone - if ( - appConfig.one_xmlrpc && - Array.isArray(defaultOpennebulaZones) && - defaultOpennebulaZones[0] && - defaultOpennebulaZones[0].rpc - ) { - defaultOpennebulaZones[0].rpc = appConfig.one_xmlrpc - } - - // get data zone - const zoneData = getDataZone(zone, defaultOpennebulaZones) - if (zoneData) { - const user = getUserOpennebula() - const password = getPassOpennebula() - const userId = getIdUserOpennebula() - const { rpc } = zoneData - - /** - * Instance of connection to opennebula. - * - * @param {string} userONE - opennebula user - * @param {string} passwordONE - opennebula pass - * @returns {Function} opennebula executer calls to XMLRPC - */ - const connectOpennebula = (userONE, passwordONE) => - opennebulaConnect(userONE, passwordONE, rpc) - - const { resource } = req.params - - const { method } = getParamsState() - const dataSources = { - [fromData.resource]: getParamsState(), - [fromData.query]: req.query, - [fromData.postBody]: req.body, - } - - const command = commandXMLRPC(resource, method) - const getOpennebulaMethod = checkOpennebulaCommand(command, httpMethod) - - if (getOpennebulaMethod) { - /* XMLRPC */ - dataSources[fromData.query] = getQueriesState() - - const responser = (val = {}) => { - switch (typeof val) { - case 'string': - try { - res.locals.httpCode = httpResponse(ok, JSON.parse(val)) - } catch (error) { - res.locals.httpCode = httpResponse(notFound, val) - } - break - case 'object': - res.locals.httpCode = httpResponse(ok, val) - break - case 'number': - res.locals.httpCode = httpResponse(ok, val) - break - default: - break - } - next() - } - - const updaterResponse = (code) => { - if ('id' in code && 'message' in code) { - res.locals.httpCode = code - } - } - - const paramsCommand = getOpennebulaMethod(dataSources) - let workerPath = [__dirname] - if (env && env.NODE_ENV === defaultWebpackMode) { - workerPath = ['src', 'server', 'utils'] - } else { - require('server/utils/index.worker') - } - const worker = new Worker(resolve(...workerPath, 'index.worker.js')) - worker.onmessage = function (result) { - worker.terminate() - const err = result && result.data && result.data.err - const value = result && result.data && result.data.value - if (!err) { - fillResourceforHookConnection(user, command, paramsCommand) - } - writeInLogger([command, JSON.stringify(value)], 'worker: %s : %s') - responseOpennebula(updaterResponse, err, value, responser, next) - } - worker.postMessage({ - globalState: (global && global.paths) || {}, - user, - password, - rpc, - command, - paramsCommand, - }) - } else { - /* FUNCTIONS */ - res.locals.httpCode = httpResponse(methodNotAllowed) - const routeFunction = checkIfIsARouteFunction( - resource, - httpMethod, - !!userId.length - ) - - if (routeFunction) { - const { action } = routeFunction - req.serverDataSource = dataSources - - action - ? action(req, res, next, connectOpennebula, userId, { - id: userId, - user, - password, - }) - : next() - } else { - next() - } - } - } else { - res.locals.httpCode.message += `: ${defaultMessageInvalidZone}` - next() - } - }, - (req, res) => { - clearStates() - const { httpCode } = res.locals - if (httpCode.file) { - res.sendFile(httpCode.file) - } else { - res.status(httpCode.id).json(httpCode) - } - } -) - -module.exports = router diff --git a/src/fireedge/src/server/routes/entrypoints/Api/functions.js b/src/fireedge/src/server/routes/entrypoints/Api/functions.js new file mode 100644 index 0000000000..e9bfb71fb4 --- /dev/null +++ b/src/fireedge/src/server/routes/entrypoints/Api/functions.js @@ -0,0 +1,103 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * + * * + * 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 * + * * + * http://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. * + * ------------------------------------------------------------------------- */ + +const { + defaultEmptyFunction, + defaultMessageInvalidZone, + from: fromData, +} = require('server/utils/constants/defaults') +const { + validateSession, + getIdUserOpennebula, + getUserOpennebula, + getPassOpennebula, + getZone, +} = require('server/routes/entrypoints/Api/middlawares') +const { httpResponse, validateHttpMethod } = require('server/utils/server') +const { opennebulaConnect } = require('server/utils/opennebula') +const { httpCodes } = require('server/utils/constants') +const routes = require('server/routes/api') + +const { resource, query, postBody } = fromData +const { internalServerError } = httpCodes + +/** + * Get routes functions. + * + * @param {object} config - config router + * @param {object} config.expressRouter - express router + * @param {function(object):object} config.jsonResponser - parse to json + */ +const functionsRoutes = ({ + expressRouter = {}, + jsonResponser = defaultEmptyFunction, +}) => { + routes.forEach((route) => { + const { path, httpMethod, action, auth } = route + if (path && httpMethod) { + const validHttpMethod = validateHttpMethod(httpMethod) + if ( + validHttpMethod && + typeof action === 'function' && + typeof expressRouter[validHttpMethod] === 'function' + ) { + expressRouter[validHttpMethod]( + path, + (req, res, next) => validateSession({ req, res, next, auth }), + (req, res, next) => { + res.locals.httpCode = httpResponse(internalServerError) + const { zone } = req.query + const zoneData = getZone(zone) + if (zoneData) { + const user = getUserOpennebula() + const password = getPassOpennebula() + const userId = getIdUserOpennebula() + const { rpc } = zoneData + + req.serverDataSource = { + [resource]: req.params, + [query]: req.query, + [postBody]: req.body, + } + + action( + req, + res, + next, + (ONEuser, ONEpass) => opennebulaConnect(ONEuser, ONEpass, rpc), + { + id: userId, + user, + password, + } + ) + } else { + res.locals.httpCode = httpResponse( + internalServerError, + '', + `${internalServerError.message}: ${defaultMessageInvalidZone}` + ) + next() + } + }, + jsonResponser + ) + } + } + }) +} + +module.exports = functionsRoutes diff --git a/src/fireedge/src/server/routes/api/files/string-routes.js b/src/fireedge/src/server/routes/entrypoints/Api/index.js similarity index 57% rename from src/fireedge/src/server/routes/api/files/string-routes.js rename to src/fireedge/src/server/routes/entrypoints/Api/index.js index 167e2116a3..aa5c3f3cbc 100644 --- a/src/fireedge/src/server/routes/api/files/string-routes.js +++ b/src/fireedge/src/server/routes/entrypoints/Api/index.js @@ -14,10 +14,46 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const FILES = 'files' +const express = require('express') +const { httpCodes } = require('server/utils/constants') +const xmlrpcRoutes = require('server/routes/entrypoints/Api/xmlrpc') +const functionsRoutes = require('server/routes/entrypoints/Api/functions') -const Actions = { - FILES, +const { notFound, internalServerError } = httpCodes +const router = express.Router() + +express() + +const jsonResponser = (req, res) => { + const { httpCode } = res.locals + if (httpCode) { + const { id, file } = httpCode + if (file) { + res.sendFile(file) + + return + } else { + res.status(id).json(httpCode) + + return + } + } + res.status(internalServerError.id).json(internalServerError) } -module.exports = Actions +functionsRoutes({ + expressRouter: router, + jsonResponser, +}) + +xmlrpcRoutes({ + expressRouter: router, + jsonResponser, +}) + +/** NOT FOUND */ +router.use((req, res) => { + res.status(notFound.id).json(notFound) +}) + +module.exports = router diff --git a/src/fireedge/src/server/routes/entrypoints/Api/middlawares.js b/src/fireedge/src/server/routes/entrypoints/Api/middlawares.js new file mode 100644 index 0000000000..a036252e20 --- /dev/null +++ b/src/fireedge/src/server/routes/entrypoints/Api/middlawares.js @@ -0,0 +1,163 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * + * * + * 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 * + * * + * http://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. * + * ------------------------------------------------------------------------- */ +const { env } = require('process') +const { httpCodes, defaults } = require('server/utils/constants') +const { getFireedgeConfig } = require('server/utils/yml') +const { defaultWebpackMode, defaultEmptyFunction, defaultOpennebulaZones } = + defaults +const { validateAuth } = require('server/utils/jwt') +const { getDataZone } = require('server/utils/server') + +let idUserOpennebula = '' +let userOpennebula = '' +let passOpennebula = '' + +/** + * Validate user in global state. + * + * @param {string} user - username + * @param {string} token - token of user + * @returns {boolean} user valid data + */ +const userValidation = (user = '', token = '') => { + let rtn = false + if ( + user && + token && + global && + global.users && + global.users[user] && + global.users[user].tokens && + Array.isArray(global.users[user].tokens) && + global.users[user].tokens.some((x) => x && x.token === token) + ) { + rtn = true + } + + return rtn +} + +/** + * Get id opennebula user. + * + * @returns {number} id opennebula user + */ +const getIdUserOpennebula = () => idUserOpennebula + +/** + * Get user opennebula. + * + * @returns {string} opennebula username + */ +const getUserOpennebula = () => userOpennebula + +/** + * Get pass opennebula. + * + * @returns {string} opennebula user password + */ +const getPassOpennebula = () => passOpennebula + +/** + * MIDDLEWARE validate resource and session. + * + * @param {object} config - http request + * @param {object} config.req - http request + * @param {object} config.res - http response + * @param {function():any} config.next - express stepper + * @param {boolean} config.auth - check if the route need authentication + */ +const validateSession = ({ + req = {}, + res = {}, + next = defaultEmptyFunction, + auth = true, +}) => { + const { badRequest, unauthorized } = httpCodes + let status = badRequest + if (auth) { + const session = validateAuth(req) + if (session) { + const { iss, aud, jti, exp } = session + idUserOpennebula = iss + userOpennebula = aud + passOpennebula = jti + if (env && (!env.NODE_ENV || env.NODE_ENV !== defaultWebpackMode)) { + /** Validate User in production */ + if (userValidation(userOpennebula, passOpennebula)) { + next() + + return + } else { + status = unauthorized + } + } else { + /** Validate user in development mode */ + if (global && !global.users) { + global.users = {} + } + if (!global.users[userOpennebula]) { + global.users[userOpennebula] = { + tokens: [{ token: passOpennebula, time: exp }], + } + } + if (userValidation(userOpennebula, passOpennebula)) { + next() + + return + } else { + status = unauthorized + } + } + } else { + status = unauthorized + } + } else { + next() + + return + } + res.status(status.id).json(status) +} +/** + * Get Zone. + * + * @param {string} zone - zone id + * @returns {object} data zone + */ +const getZone = (zone = '0') => { + // get fireedge config + const appConfig = getFireedgeConfig() + // set first zone + if ( + appConfig.one_xmlrpc && + Array.isArray(defaultOpennebulaZones) && + defaultOpennebulaZones[0] && + defaultOpennebulaZones[0].rpc + ) { + defaultOpennebulaZones[0].rpc = appConfig.one_xmlrpc + } + + return getDataZone(zone, defaultOpennebulaZones) +} + +module.exports = { + getIdUserOpennebula, + getUserOpennebula, + getPassOpennebula, + getZone, + validateSession, +} diff --git a/src/fireedge/src/server/routes/entrypoints/Api/xmlrpc.js b/src/fireedge/src/server/routes/entrypoints/Api/xmlrpc.js new file mode 100644 index 0000000000..a5f7a8618d --- /dev/null +++ b/src/fireedge/src/server/routes/entrypoints/Api/xmlrpc.js @@ -0,0 +1,213 @@ +/* ------------------------------------------------------------------------- * + * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * + * * + * 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 * + * * + * http://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. * + * ------------------------------------------------------------------------- */ +const { resolve } = require('path') +const { env } = require('process') +const Worker = require('tiny-worker') +const upcast = require('upcast') +const { + defaults, + httpCodes, + opennebulaCommands: commands, +} = require('server/utils/constants') +const { + validateSession, + getUserOpennebula, + getPassOpennebula, + getZone, +} = require('server/routes/entrypoints/Api/middlawares') +const { fillResourceforHookConnection } = require('server/utils/opennebula') +const { httpResponse, validateHttpMethod } = require('server/utils/server') +const { writeInLogger } = require('server/utils/logger') + +const { + defaultWebpackMode, + defaultEmptyFunction, + defaultMessageInvalidZone, + from: fromData, +} = defaults +const { internalServerError, ok, notFound } = httpCodes +const { resource: fromResource, query, postBody } = fromData + +/** + * Execute Worker. + * + * @param {object} config - worker config. + * @param {string} config.user - user. + * @param {string} config.password - password. + * @param {string} config.rpc - rpc path. + * @param {string} config.command - command. + * @param {any[]} config.paramsCommand - params for commands + * @param {function():any} config.next - stepper express + * @param {object} config.res - response express + */ +const executeWorker = ({ + user, + password, + rpc, + command, + paramsCommand, + next, + res, +}) => { + if (user && password && rpc && command && paramsCommand) { + let workerPath = [__dirname] + if (env && env.NODE_ENV === defaultWebpackMode) { + workerPath = ['src', 'server', 'utils'] + } else { + require('server/utils/index.worker') + } + const worker = new Worker(resolve(...workerPath, 'index.worker.js')) + + worker.onmessage = function (result) { + worker.terminate() + const err = result && result.data && result.data.err + const value = result && result.data && result.data.value + writeInLogger([command, JSON.stringify(value)], 'worker: %s : %s') + if (!err) { + fillResourceforHookConnection(user, command, paramsCommand) + switch (typeof value) { + case 'string': + try { + res.locals.httpCode = httpResponse(ok, JSON.parse(value)) + } catch (error) { + res.locals.httpCode = httpResponse(notFound, value) + } + break + case 'object': + res.locals.httpCode = httpResponse(ok, value) + break + case 'number': + res.locals.httpCode = httpResponse(ok, value) + break + default: + break + } + } + next() + } + + worker.postMessage({ + globalState: (global && global.paths) || {}, + user, + password, + rpc, + command, + paramsCommand, + }) + } +} + +/** + * Get commands for command. + * + * @param {object} config - config for get params for command + * @param {object} config.params - params command + * @param {object} config.serverDataSource - server data source + * @returns {any[]} - params for command + */ +const getCommandParams = (config) => { + const { params, serverDataSource } = config + if (params && serverDataSource) { + return Object.entries(params).map(([key, value]) => { + if (key && value && value.from && typeof value.default !== 'undefined') { + return serverDataSource[value.from] && serverDataSource[value.from][key] + ? upcast.to( + serverDataSource[value.from][key], + upcast.type(value.default) + ) + : value.default + } + + return '' + }) + } +} + +/** + * Get routes functions. + * + * @param {object} config - config router + * @param {object} config.expressRouter - express router + * @param {function(object):object} config.jsonResponser - parse to json + */ +const xmlrpcRoutes = ({ + expressRouter = {}, + jsonResponser = defaultEmptyFunction, +}) => { + Object.keys(commands).forEach((command) => { + const [resource, method] = command.split('.') + const { httpMethod, params } = commands[command] + if (resource && method && httpMethod) { + const validHttpMethod = validateHttpMethod(httpMethod) + if ( + validHttpMethod && + typeof expressRouter[validHttpMethod] === 'function' + ) { + const resourceParams = + (params && + Object.entries(params).reduce((prev, current) => { + const [key, value] = current + if (value && value.from && value.from === fromResource) { + return `${prev}/:${key}?` + } + + return prev + }, '')) || + '' + expressRouter[validHttpMethod]( + `/${resource}/${method}${resourceParams}`, + (req, res, next) => validateSession({ req, res, next }), + (req, res, next) => { + res.locals.httpCode = httpResponse(internalServerError) + const { zone } = req.query + const zoneData = getZone(zone) + if (zoneData) { + const user = getUserOpennebula() + const password = getPassOpennebula() + const { rpc } = zoneData + + const serverDataSource = { + [fromResource]: req.params, + [query]: req.query, + [postBody]: req.body, + } + + executeWorker({ + user, + password, + rpc, + command, + paramsCommand: getCommandParams({ params, serverDataSource }), + next, + res, + }) + } else { + res.locals.httpCode = httpResponse( + internalServerError, + '', + `${internalServerError.message}: ${defaultMessageInvalidZone}` + ) + next() + } + }, + jsonResponser + ) + } + } + }) +} + +module.exports = xmlrpcRoutes diff --git a/src/fireedge/src/server/routes/entrypoints/index.js b/src/fireedge/src/server/routes/entrypoints/index.js index 6b3a81a10a..2ce60bff4f 100644 --- a/src/fireedge/src/server/routes/entrypoints/index.js +++ b/src/fireedge/src/server/routes/entrypoints/index.js @@ -14,9 +14,9 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const entrypoint404 = require('./404') -const entrypointApi = require('./Api') -const entrypointApp = require('./App') +const entrypoint404 = require('server/routes/entrypoints/404') +const entrypointApi = require('server/routes/entrypoints/Api') +const entrypointApp = require('server/routes/entrypoints/App') module.exports = { entrypoint404, diff --git a/src/fireedge/src/server/routes/entrypoints/middlewares/api/index.js b/src/fireedge/src/server/routes/entrypoints/middlewares/api/index.js deleted file mode 100644 index a10eeedd8a..0000000000 --- a/src/fireedge/src/server/routes/entrypoints/middlewares/api/index.js +++ /dev/null @@ -1,257 +0,0 @@ -/* ------------------------------------------------------------------------- * - * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * - * * - * 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 * - * * - * http://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. * - * ------------------------------------------------------------------------- */ - -const { Map } = require('immutable') -const { env } = require('process') -const { global } = require('window-or-global') - -const { - private: authenticated, - public: nonAuthenticated, -} = require('../../../api') -const { httpCodes, params, defaults } = require('server/utils/constants') -const { - validateAuth, - getAllowedQueryParams, - createParamsState, - createQueriesState, -} = require('server/utils') -const { defaultWebpackMode } = defaults - -const defaultParams = Map(createParamsState()) -const defaultQueries = Map(createQueriesState()) - -let paramsState = defaultParams.toObject() -let queriesState = defaultQueries.toObject() -let idUserOpennebula = '' -let userOpennebula = '' -let passOpennebula = '' -/** - * Get params state. - * - * @returns {object} params state - */ -const getParamsState = () => paramsState - -/** - * Get query state. - * - * @returns {object} query state - */ -const getQueriesState = () => queriesState - -/** - * Get id opennebula user. - * - * @returns {number} id opennebula user - */ -const getIdUserOpennebula = () => idUserOpennebula - -/** - * Get user opennebula. - * - * @returns {string} opennebula username - */ -const getUserOpennebula = () => userOpennebula - -/** - * Get pass opennebula. - * - * @returns {string} opennebula user password - */ -const getPassOpennebula = () => passOpennebula - -/** - * Validate user in global state. - * - * @param {string} user - username - * @param {string} token - token of user - * @returns {boolean} user valid data - */ -const userValidation = (user = '', token = '') => { - let rtn = false - if ( - user && - token && - global && - global.users && - global.users[user] && - global.users[user].tokens && - Array.isArray(global.users[user].tokens) && - global.users[user].tokens.some((x) => x && x.token === token) - ) { - rtn = true - } - - return rtn -} - -/** - * MIDDLEWARE validate resource and session. - * - * @param {object} req - http request - * @param {object} res - http response - * @param {Function} next - express stepper - */ -const validateResourceAndSession = (req, res, next) => { - clearStates() - const { badRequest, unauthorized, serviceUnavailable } = httpCodes - let status = badRequest - if (req && req.params && req.params.resource) { - const resource = req.params.resource - status = serviceUnavailable - - /** - * Finder command. - * - * @param {object} rtnCommand - command - * @returns {object} command - */ - const finderCommand = (rtnCommand) => - rtnCommand && rtnCommand.endpoint && rtnCommand.endpoint === resource - if (authenticated.some(finderCommand)) { - const session = validateAuth(req) - if (session) { - idUserOpennebula = session.iss - userOpennebula = session.aud - passOpennebula = session.jti - if (env && (!env.NODE_ENV || env.NODE_ENV !== defaultWebpackMode)) { - /********************************************************* - * Validate user in production mode - *********************************************************/ - - if (userValidation(userOpennebula, passOpennebula)) { - next() - - return - } - } else { - /********************************************************* - * Validate user in development mode - *********************************************************/ - - if (global && !global.users) { - global.users = {} - } - if (!global.users[userOpennebula]) { - global.users[userOpennebula] = { - tokens: [{ token: passOpennebula, time: session.exp }], - } - } - if (userValidation(userOpennebula, passOpennebula)) { - next() - - return - } - } - } - status = unauthorized - } - if (nonAuthenticated.some(finderCommand)) { - next() - - return - } - } - res.status(status.id).json(status) -} -/** - * MIDDLEWARE set optional parameters (params ins URL). - * - * @param {object} req - http request - * @param {object} res - http response - * @param {Function} next - express stepper - */ -const setOptionalParameters = (req, res, next) => { - if (req && req.params) { - let start = true - const keys = Object.keys(req.params) - keys.forEach((param) => { - if (start) { - // The params[0] is the resource - start = false - - return start - } - if (req.params[param]) { - const matches = req.params[param].match(/(^[\w]*=)/gi) - if (matches && matches[0]) { - params.forEach((parameter) => { - if ( - matches[0].replace(/=/g, '').toLowerCase() === - parameter.toLowerCase() - ) { - const removeKey = new RegExp(`^${parameter}=`, 'i') - if (paramsState[parameter] === null) { - paramsState[parameter] = req.params[param].replace( - removeKey, - '' - ) - } - } - }) - } else { - paramsState[param] = req.params[param] - } - } - - return '' - }) - } - next() -} -/** - * MIDDLEWARE set optional queries. - * - * @param {object} req - http request - * @param {object} res - http response - * @param {Function} next - express stepper - */ -const setOptionalQueries = (req, res, next) => { - if (req && req.query) { - const keys = Object.keys(req.query) - const queries = getAllowedQueryParams() - keys.forEach((query) => { - if (req.query[query] && queries.includes(query)) { - queriesState[query] = req.query[query] - } - }) - } - next() -} - -/** - * Clear states. - */ -const clearStates = () => { - paramsState = defaultParams.toObject() - queriesState = defaultQueries.toObject() - idUserOpennebula = '' - userOpennebula = '' - passOpennebula = '' -} - -module.exports = { - validateResourceAndSession, - setOptionalParameters, - setOptionalQueries, - clearStates, - getParamsState, - getQueriesState, - getIdUserOpennebula, - getUserOpennebula, - getPassOpennebula, -} diff --git a/src/fireedge/src/server/routes/entrypoints/middlewares/index.js b/src/fireedge/src/server/routes/entrypoints/middlewares/index.js deleted file mode 100644 index c7b4a345e2..0000000000 --- a/src/fireedge/src/server/routes/entrypoints/middlewares/index.js +++ /dev/null @@ -1,39 +0,0 @@ -/* ------------------------------------------------------------------------- * - * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * - * * - * 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 * - * * - * http://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. * - * ------------------------------------------------------------------------- */ - -const { - validateResourceAndSession, - setOptionalParameters, - setOptionalQueries, - clearStates, - getParamsState, - getQueriesState, - getIdUserOpennebula, - getUserOpennebula, - getPassOpennebula, -} = require('./api') - -module.exports = { - validateResourceAndSession, - setOptionalParameters, - setOptionalQueries, - clearStates, - getParamsState, - getQueriesState, - getIdUserOpennebula, - getUserOpennebula, - getPassOpennebula, -} diff --git a/src/fireedge/src/server/utils/constants/index.js b/src/fireedge/src/server/utils/constants/index.js index 5c75971d7f..52b312869b 100644 --- a/src/fireedge/src/server/utils/constants/index.js +++ b/src/fireedge/src/server/utils/constants/index.js @@ -16,12 +16,10 @@ const defaults = require('./defaults') const httpCodes = require('./http-codes') -const params = require('./params') const opennebulaCommands = require('./commands') module.exports = { defaults, httpCodes, - params, opennebulaCommands, } diff --git a/src/fireedge/src/server/utils/index.js b/src/fireedge/src/server/utils/index.js deleted file mode 100644 index e91b84481a..0000000000 --- a/src/fireedge/src/server/utils/index.js +++ /dev/null @@ -1,122 +0,0 @@ -/* ------------------------------------------------------------------------- * - * Copyright 2002-2021, OpenNebula Project, OpenNebula Systems * - * * - * 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 * - * * - * http://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. * - * ------------------------------------------------------------------------- */ - -const params = require('./constants/params') -const functionRoutes = require('../routes/api') -const { validateAuth } = require('./jwt') -const { httpResponse, getDataZone } = require('./server') -const { messageTerminal, addPrintf, checkEmptyObject } = require('./general') -const { getFireedgeConfig } = require('./yml') - -const { - responseOpennebula, - opennebulaConnect, - getMethodForOpennebulaCommand, - commandXMLRPC, - getAllowedQueryParams, - getRouteForOpennebulaCommand, - checkOpennebulaCommand, - fillResourceforHookConnection, -} = require('./opennebula') - -/** - * Create params http request state. - * - * @returns {object} params state - */ -const createParamsState = () => { - const rtn = {} - if (params && Array.isArray(params)) { - params.forEach((param) => { - rtn[param] = null - }) - } - - return rtn -} - -/** - * Create Queries http request state. - * - * @returns {object} queries state - */ -const createQueriesState = () => { - const rtn = {} - const queries = getAllowedQueryParams() - if (queries && Array.isArray(queries)) { - queries.forEach((query) => { - rtn[query] = null - }) - } - - return rtn -} - -/** - * Check if route id a function. - * - * @param {string} route - route - * @param {string} httpMethod - http method - * @param {boolean} authenticated - user authenticated - * @returns {object|undefined} route function - */ -const checkIfIsARouteFunction = (route, httpMethod, authenticated) => { - if (route && route.length) { - const { private: functionPrivate, public: functionPublic } = functionRoutes - const functions = authenticated ? functionPrivate : functionPublic - /** - * Finder command. - * - * @param {object} rtnCommand - command to validate - * @returns {object} command - */ - - const finderCommand = (rtnCommand) => - rtnCommand && - rtnCommand.endpoint && - rtnCommand.endpoint === route && - rtnCommand.httpMethod && - rtnCommand.httpMethod === httpMethod && - rtnCommand.action && - typeof rtnCommand.action === 'function' - - const find = functions.find(finderCommand) - if (find) { - return find - } - } -} - -module.exports = { - validateAuth, - createParamsState, - getAllowedQueryParams, - createQueriesState, - opennebulaConnect, - messageTerminal, - addPrintf, - getRouteForOpennebulaCommand, - getMethodForOpennebulaCommand, - commandXMLRPC, - checkIfIsARouteFunction, - checkOpennebulaCommand, - responseOpennebula, - getFireedgeConfig, - httpResponse, - getDataZone, - checkEmptyObject, - fillResourceforHookConnection, -} diff --git a/src/fireedge/src/server/utils/jwt.js b/src/fireedge/src/server/utils/jwt.js index d13042a536..d24931e9e7 100644 --- a/src/fireedge/src/server/utils/jwt.js +++ b/src/fireedge/src/server/utils/jwt.js @@ -15,8 +15,8 @@ * ------------------------------------------------------------------------- */ const jwt = require('jwt-simple') -const { messageTerminal } = require('./general') const speakeasy = require('speakeasy') +const { messageTerminal } = require('server/utils/general') /** * Create a JWT. diff --git a/src/fireedge/src/server/utils/logger.js b/src/fireedge/src/server/utils/logger.js index 5032b8e403..fa07c8c30a 100644 --- a/src/fireedge/src/server/utils/logger.js +++ b/src/fireedge/src/server/utils/logger.js @@ -19,7 +19,8 @@ const { global } = require('window-or-global') const { transports, format, createLogger } = require('winston') const { sprintf } = require('sprintf-js') const morgan = require('morgan') -const { defaultWebpackMode } = require('./constants/defaults') +const { defaults } = require('server/utils/constants') +const { defaultWebpackMode } = defaults let logger = null diff --git a/src/fireedge/src/server/utils/opennebula.js b/src/fireedge/src/server/utils/opennebula.js index cbeb59979c..eb4fe37dcf 100644 --- a/src/fireedge/src/server/utils/opennebula.js +++ b/src/fireedge/src/server/utils/opennebula.js @@ -14,7 +14,6 @@ * limitations under the License. * * ------------------------------------------------------------------------- */ -const upcast = require('upcast') // eslint-disable-next-line node/no-deprecated-api const { parse } = require('url') const rpc = require('xmlrpc') @@ -22,17 +21,20 @@ const parser = require('fast-xml-parser') const { Map } = require('immutable') const { sprintf } = require('sprintf-js') const { global } = require('window-or-global') -const httpCodes = require('./constants/http-codes') -const commandsParams = require('./constants/commands') +const { + httpCodes, + opennebulaCommands, + defaults, +} = require('server/utils/constants') const { from, defaultEmptyFunction, defaultConfigParseXML, defaultNamespace, defaultMessageProblemOpennebula, -} = require('./constants/defaults') +} = defaults -const { getFireedgeConfig } = require('./yml') +const { getFireedgeConfig } = require('server/utils/yml') // regex for separate the commands .info const regexInfoAction = /^(\w+).info$/ @@ -255,8 +257,8 @@ const responseOpennebula = (res, err, value, response, next) => { */ const getMethodForOpennebulaCommand = () => { const rtn = [] - if (commandsParams) { - const commands = Object.keys(commandsParams) + if (opennebulaCommands) { + const commands = Object.keys(opennebulaCommands) commands.forEach((command) => { if (command && command.length) { const commandString = command.split('.') @@ -270,33 +272,6 @@ const getMethodForOpennebulaCommand = () => { return rtn } -/** - * Get a command to XMLRPC. - * - * @param {string} resource - resource - * @param {string} method - method - * @param {string} defaultMethod - default method - * @returns {string} command to XMLRPC - */ -const commandXMLRPC = (resource = '', method = '', defaultMethod = '') => { - let command = '' - const allowedActions = getMethodForOpennebulaCommand() - if (resource && resource.length) { - command = `${resource}` - } - const commandWithDefault = defaultMethod - ? `${command}.${defaultMethod}` - : command - - if (method) { - command = allowedActions.includes(method) - ? `${command}.${method}` - : commandWithDefault - } - - return command -} - /** * Get allowed query parameters. * @@ -304,11 +279,11 @@ const commandXMLRPC = (resource = '', method = '', defaultMethod = '') => { */ const getAllowedQueryParams = () => { const rtn = [] - const allowedQuerys = Object.keys(commandsParams) + const allowedQuerys = Object.keys(opennebulaCommands) if (from && from.query) { const { query } = from allowedQuerys.forEach((allowedQuery) => { - const command = commandsParams[allowedQuery] + const command = opennebulaCommands[allowedQuery] if (command && command.params) { const internalParams = Object.keys(command.params) internalParams.forEach((internalParam) => { @@ -335,8 +310,8 @@ const getAllowedQueryParams = () => { */ const getRouteForOpennebulaCommand = () => { const rtn = [] - if (commandsParams) { - const commands = Object.keys(commandsParams) + if (opennebulaCommands) { + const commands = Object.keys(opennebulaCommands) commands.forEach((command) => { if (command && command.length) { let commandString = command.split('.') @@ -386,61 +361,18 @@ const checkPositionInDataSource = (dataSource) => { * * @param {string} command - openenbula command * @param {string} method - method of opennebula command - * @param {boolean} commandParams - commands - * @returns {object} command opennebula + * @returns {object|false} command opennebula */ -const checkOpennebulaCommand = ( - command = '', - method = '', - commandParams = true -) => { - let rtn = false - if (command && method && commandsParams && from) { - if ( - commandsParams && - commandsParams[command] && - commandsParams[command].params && - commandsParams[command].httpMethod && - commandsParams[command].httpMethod === method - ) { - rtn = commandParams - ? (dataSource) => { - let rtnParams = false - if (dataSource && checkPositionInDataSource(dataSource)) { - const { params: paramsForCommand } = commandsParams[command] - const internalParams = [] - Object.keys(paramsForCommand).forEach((param) => { - const parameter = paramsForCommand[param] - if ( - 'default' in parameter && - 'from' in parameter && - parameter.from in dataSource && - param in dataSource[parameter.from] && - dataSource[parameter.from][param] - ) { - internalParams.push( - upcast.to( - dataSource[parameter.from][param], - upcast.type(parameter.default) - ) - ) - } else { - internalParams.push(parameter.default) - } - }) - if (internalParams) { - rtnParams = internalParams - } - } - - return rtnParams - } - : commandsParams[command] - } - } - - return rtn -} +const checkOpennebulaCommand = (command = '', method = '') => + command && + method && + opennebulaCommands && + opennebulaCommands[command] && + opennebulaCommands[command].params && + opennebulaCommands[command].httpMethod && + opennebulaCommands[command].httpMethod === method + ? opennebulaCommands[command] + : false /** * Get default params of opennebula command. @@ -626,11 +558,9 @@ module.exports = { opennebulaConnect, responseOpennebula, getMethodForOpennebulaCommand, - commandXMLRPC, getAllowedQueryParams, getRouteForOpennebulaCommand, checkPositionInDataSource, - checkOpennebulaCommand, getDefaultParamsOfOpennebulaCommand, generateNewResourceTemplate, fillResourceforHookConnection, diff --git a/src/fireedge/src/server/utils/server.js b/src/fireedge/src/server/utils/server.js index d3bcc630bd..1cddae2197 100644 --- a/src/fireedge/src/server/utils/server.js +++ b/src/fireedge/src/server/utils/server.js @@ -16,7 +16,6 @@ const { env } = require('process') const { Map } = require('immutable') -const multer = require('multer') const { global } = require('window-or-global') const { resolve } = require('path') const { @@ -36,14 +35,14 @@ const { statSync, removeSync, } = require('fs-extra') -const { internalServerError } = require('./constants/http-codes') +const { defaults, httpCodes } = require('server/utils/constants') const { messageTerminal } = require('server/utils/general') const { validateAuth } = require('server/utils/jwt') const { writeInLogger } = require('server/utils/logger') const { spawnSync, spawn } = require('child_process') const { + httpMethod, defaultApps, - from: fromData, defaultAppName, defaultConfigFile, defaultLogFilename, @@ -66,206 +65,12 @@ const { defaultProvisionPath, defaultProvisionConfig, defaultEmptyFunction, -} = require('./constants/defaults') - -const upload = multer({ dest: '/tmp' }) +} = defaults +const { internalServerError } = httpCodes let cert = '' let key = '' -/** - * Set functions as routes. - * - * @param {string} method - http methof - * @param {string} endpoint - http endpoint - * @param {string} action - opennebula action - * @returns {object} object function - */ -const setFunctionRoute = (method, endpoint, action) => ({ - httpMethod: method, - endpoint, - action, -}) - -/** - * Set functions to API routes. - * - * @param {object} routes - object of routes - * @param {string} path - principal route - * @returns {Array} parsed routes - */ -const setApiRoutes = (routes = {}, path = '') => { - const rtn = [] - if (Object.keys(routes).length > 0 && routes.constructor === Object) { - Object.keys(routes).forEach((route) => { - rtn.push( - setFunctionRoute( - route, - path, - (req, res, next, connection, userId, user) => { - addFunctionAsRoute(req, res, next, routes[route], user, connection) - } - ) - ) - }) - } - - return rtn -} - -/** - * Execute actions Function routes - * - * @param {Function} action - action. - * @param {object} res - response http. - * @param {Function} next - stepper. - * @param {object} routeParams - params for actions. - * @param {object} serverDataSource - server params. - * @param {user} user - user. - * @param {Function} oneConnection - ONE connection xmlrpc. - */ - -const executeAction = ( - action = defaultEmptyFunction, - res = {}, - next = defaultEmptyFunction, - routeParams = {}, - serverDataSource = {}, - user = {}, - oneConnection = defaultEmptyFunction -) => { - action( - res, - next, - getRequestParameters(routeParams, serverDataSource), - user, - oneConnection - ) -} - -/** - * Parse files for actions. - * - * @param {Array} files - files - * @returns {Array} files - */ -const parseFiles = (files = []) => { - let rtn - if (files && Array.isArray(files)) { - rtn = {} - files.forEach((file) => { - if (file.fieldname) { - rtn[file.fieldname] - ? rtn[file.fieldname].push(file) - : (rtn[file.fieldname] = [file]) - } - }) - } - - return rtn -} - -/** - * Add function as express route. - * - * @param {object} req - http request - * @param {object} res - http response - * @param {Function} next - express stepper - * @param {object} routes - new routes - * @param {object} user - user Data - * @param {Function} oneConnection - function one XMLRPC - * @param {string} index - resource index - */ -const addFunctionAsRoute = ( - req = {}, - res = {}, - next = defaultEmptyFunction, - routes = {}, - user = {}, - oneConnection = defaultEmptyFunction, - index = 0 -) => { - if (req && req.serverDataSource && res && next && routes) { - const serverDataSource = req.serverDataSource - const resources = Object.keys(serverDataSource[fromData.resource]) - let route = - routes[ - `${serverDataSource[fromData.resource][resources[index]]}`.toLowerCase() - ] - - if (!route && index === 0 && routes.null) { - route = routes.null - } - - if (route) { - if (Object.keys(route).length > 0 && route.constructor === Object) { - if ( - route.action && - route.params && - typeof route.action === 'function' - ) { - const uploadFiles = getRequestFiles(route.params) - if (uploadFiles && uploadFiles.length) { - const files = upload.array(uploadFiles) - files(req, res, (err) => { - if (err) { - const errorData = (err && err.message) || '' - writeInLogger(errorData) - messageTerminal({ - color: 'red', - message: 'Error: %s', - error: errorData, - }) - } - const dataSources = { - [fromData.resource]: serverDataSource[fromData.resource], - [fromData.query]: req.query, - [fromData.postBody]: req.body, - } - dataSources.files = parseFiles(req && req.files) - executeAction( - route.action, - res, - next, - route.params, - dataSources, - user, - oneConnection - ) - }) - } else { - executeAction( - route.action, - res, - next, - route.params, - serverDataSource, - user, - oneConnection - ) - } - } else { - addFunctionAsRoute( - req, - res, - next, - route, - user, - oneConnection, - index + 1 - ) - } - } else { - next() - } - } else { - next() - } - } else { - next() - } -} - /** * Validate if server app have certs. * @@ -297,6 +102,17 @@ const getCert = () => cert */ const getKey = () => key +/** + * Validate the route http method. + * + * @param {string} resourceHttpMethod - http method + * @returns {string|false} validate the http method of function route + */ +const validateHttpMethod = (resourceHttpMethod = '') => + resourceHttpMethod && Object.keys(httpMethod).includes(resourceHttpMethod) + ? resourceHttpMethod.toLocaleLowerCase() + : false + /** * Response http. * @@ -658,10 +474,8 @@ const getDataZone = (zone = '0', configuredZones) => { (global && global.zones) || configuredZones || defaultOpennebulaZones if (zones && Array.isArray(zones)) { rtn = zones[0] - if (zone !== null) { - rtn = zones.find( - (zn) => zn && zn.id !== undefined && String(zn.id) === zone - ) + if (Number.isInteger(parseInt(zone, 10))) { + rtn = zones.find((zn) => zn && zn.id && String(zn.id) === zone) } } @@ -775,7 +589,7 @@ const getRequestParameters = (params = {}, req = {}) => { ) { Object.entries(params).forEach(([param, value]) => { if (param && value && value.from && req[value.from]) { - rtn[param] = value.name ? req[value.from][value.name] : req[value.from] + rtn[param] = value.all ? req[value.from] : req[value.from][param] } }) } @@ -1072,9 +886,6 @@ const executeCommandAsync = ( } module.exports = { - setFunctionRoute, - setApiRoutes, - addFunctionAsRoute, encrypt, decrypt, getDataZone, @@ -1103,4 +914,5 @@ module.exports = { executeCommandAsync, checkValidApp, removeFile, + validateHttpMethod, }