diff --git a/src/fireedge/package.json b/src/fireedge/package.json index 105d637910..087a871c6a 100644 --- a/src/fireedge/package.json +++ b/src/fireedge/package.json @@ -12,6 +12,7 @@ "pot": "node potfile.js", "po2json": "node po2json.js", "lint": "eslint ./src/client/", + "lint-server": "eslint ./src/server/", "lint-fix": "eslint ./src/client/ --fix" }, "author": "opennebula.io", diff --git a/src/fireedge/src/server/index.js b/src/fireedge/src/server/index.js index 55ab24891a..2b4ab3d68c 100644 --- a/src/fireedge/src/server/index.js +++ b/src/fireedge/src/server/index.js @@ -1,17 +1,18 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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. * + * ------------------------------------------------------------------------- */ import path from 'path' import express from 'express' @@ -51,7 +52,7 @@ import { entrypointApp } from './routes/entrypoints' import { websockets } from './routes/websockets' -import { vmrcUpgrade } from './routes/websockets/vmrc' +import { vmrc } from './routes/websockets/vmrc' import { guacamole } from './routes/websockets/guacamole' import { messageTerminal, getConfig } from './utils' @@ -177,10 +178,13 @@ appServer.listen(port, host, err => { } messageTerminal(config) }) -vmrcUpgrade(appServer) +vmrc(appServer) guacamole(appServer) -function handleBreak (code) { +/** + * Handle sigterm and sigint. + */ +const handleBreak = () => { if (appServer && appServer.close && typeof appServer.close === 'function') { appServer.close(() => { // this close sockets diff --git a/src/fireedge/src/server/routes/api/2fa/functions.js b/src/fireedge/src/server/routes/api/2fa/functions.js deleted file mode 100644 index 85ee974a0b..0000000000 --- a/src/fireedge/src/server/routes/api/2fa/functions.js +++ /dev/null @@ -1,279 +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 speakeasy = require('speakeasy') -const qrcode = require('qrcode') -const { Map } = require('immutable') -const { httpResponse } = require('server/utils/server') // '../../../utils/server' -const { getConfig } = require('server/utils/yml') // '../../../utils/yml' -const { Actions } = require('server/utils/constants/commands/user') -const { - httpMethod, - default2FAIssuer, - default2FAOpennebulaVar, - default2FAOpennebulaTmpVar -} = require('server/utils/constants/defaults') - -const { POST, GET } = httpMethod -const { - responseOpennebula, - checkOpennebulaCommand, - generateNewTemplate, - check2Fa -} = require('server/utils/opennebula') -const { from: fromData } = require('server/utils/constants/defaults') -const { - ok, - unauthorized, - internalServerError -} = require('server/utils/constants/http-codes') - -// user config -const appConfig = getConfig() - -const twoFactorAuthIssuer = - appConfig.TWO_FACTOR_AUTH_ISSUER || default2FAIssuer - -const getUserInfoAuthenticated = (connect, userId, callback, next) => { - if ( - connect && - !!userId && - callback && - next && - typeof connect === 'function' && - typeof callback === 'function' && - typeof next === 'function' && - Actions.USER_INFO - ) { - const connectOpennebula = connect() - const dataUser = {} - // empty positions for validate... - dataUser[fromData.resource] = {} - dataUser[fromData.query] = {} - dataUser[fromData.postBody] = {} - dataUser[fromData.resource].id = userId - const getOpennebulaMethod = checkOpennebulaCommand( - Actions.USER_INFO, - GET - ) - connectOpennebula( - Actions.USER_INFO, - getOpennebulaMethod(dataUser), - (err, value) => { - responseOpennebula( - () => undefined, - err, - value, - info => { - if (info !== undefined && info !== null) { - callback(info) - } else { - next() - } - }, - next - ) - } - ) - } -} - -const generateQR = (req, res, next, connect, userId) => { - const secret = speakeasy.generateSecret({ - length: 10, - name: twoFactorAuthIssuer - }) - if (secret && secret.otpauth_url && secret.base32) { - const { otpauth_url: otpURL, base32 } = secret - qrcode.toDataURL(otpURL, (err, dataURL) => { - if (err) { - res.locals.httpCode = httpResponse(internalServerError) - next() - } else { - const connectOpennebula = connect() - getUserInfoAuthenticated( - connect, - userId, - info => { - if (info && info.USER && info.USER.TEMPLATE && req) { - const dataUser = Map(req).toObject() - const emptyTemplate = {} - emptyTemplate[default2FAOpennebulaTmpVar] = base32 - - dataUser[fromData.resource].id = userId - dataUser[fromData.postBody].template = generateNewTemplate( - info.USER.TEMPLATE.SUNSTONE || {}, - emptyTemplate, - [default2FAOpennebulaVar] - ) - const getOpennebulaMethod = checkOpennebulaCommand( - Actions.USER_UPDATE, - POST - ) - connectOpennebula( - Actions.USER_UPDATE, - getOpennebulaMethod(dataUser), - (error, value) => { - responseOpennebula( - () => undefined, - error, - value, - pass => { - if (pass !== undefined && pass !== null) { - res.locals.httpCode = httpResponse(ok, { - img: dataURL - }) - next() - } else { - next() - } - }, - next - ) - } - ) - } else { - next() - } - }, - next - ) - } - }) - } else { - next() - } -} - -const twoFactorSetup = (req, res, next, connect, userId) => { - const connectOpennebula = connect() - getUserInfoAuthenticated( - connect, - userId, - info => { - if ( - info && - info.USER && - info.USER.TEMPLATE && - info.USER.TEMPLATE.SUNSTONE && - info.USER.TEMPLATE.SUNSTONE[default2FAOpennebulaTmpVar] && - fromData && - fromData.postBody && - req && - req[fromData.postBody] && - req[fromData.postBody].token - ) { - const sunstone = info.USER.TEMPLATE.SUNSTONE - const token = req[fromData.postBody].token - const secret = sunstone[default2FAOpennebulaTmpVar] - if (check2Fa(secret, token)) { - const emptyTemplate = {} - emptyTemplate[default2FAOpennebulaVar] = secret - - const dataUser = Map(req).toObject() - dataUser[fromData.resource].id = userId - dataUser[fromData.postBody].template = generateNewTemplate( - sunstone || {}, - emptyTemplate, - [default2FAOpennebulaTmpVar] - ) - const getOpennebulaMethodUpdate = checkOpennebulaCommand( - Actions.USER_UPDATE, - POST - ) - connectOpennebula( - Actions.USER_UPDATE, - getOpennebulaMethodUpdate(dataUser), - (err, value) => { - responseOpennebula( - () => undefined, - err, - value, - pass => { - if (pass !== undefined && pass !== null) { - res.locals.httpCode = httpResponse(ok) - } - next() - }, - next - ) - } - ) - } else { - res.locals.httpCode = httpResponse(unauthorized) - next() - } - } else { - next() - } - }, - next - ) -} -const twoFactorDelete = (req, res, next, connect, userId) => { - const connectOpennebula = connect() - getUserInfoAuthenticated( - connect, - userId, - info => { - if ( - info && - info.USER && - info.USER.TEMPLATE && - info.USER.TEMPLATE.SUNSTONE - ) { - const emptyTemplate = {} - const dataUser = Map(req).toObject() - dataUser[fromData.resource].id = userId - dataUser[fromData.postBody].template = generateNewTemplate( - info.USER.TEMPLATE.SUNSTONE || {}, - emptyTemplate, - [default2FAOpennebulaTmpVar, default2FAOpennebulaVar] - ) - const getOpennebulaMethodUpdate = checkOpennebulaCommand( - Actions.USER_UPDATE, - POST - ) - connectOpennebula( - Actions.USER_UPDATE, - getOpennebulaMethodUpdate(dataUser), - (err, value) => { - responseOpennebula( - () => undefined, - err, - value, - pass => { - if (pass !== undefined && pass !== null) { - res.locals.httpCode = httpResponse(ok) - } - next() - }, - next - ) - } - ) - } else { - next() - } - }, - next - ) -} -module.exports = { - getUserInfoAuthenticated, - generateQR, - twoFactorSetup, - twoFactorDelete -} diff --git a/src/fireedge/src/server/routes/api/2fa/index.js b/src/fireedge/src/server/routes/api/2fa/index.js index c5813f2b3c..3ea75e82cd 100644 --- a/src/fireedge/src/server/routes/api/2fa/index.js +++ b/src/fireedge/src/server/routes/api/2fa/index.js @@ -1,50 +1,58 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { generateQR, twoFactorSetup, twoFactorDelete } = require('./functions') -const { httpMethod } = require('server/utils/constants/defaults') // ../../../utils/constants/defaults' -const { - TWO_FACTOR_QR, - TWO_FACTOR_DELETE, - TWO_FACTOR_SETUP -} = require('./string-routes') - -const { POST, DELETE } = httpMethod - -const privateRoutes = [ - { - httpMethod: POST, - endpoint: TWO_FACTOR_QR, - action: generateQR - }, - { - httpMethod: POST, - endpoint: TWO_FACTOR_SETUP, - action: twoFactorSetup - }, - { - httpMethod: DELETE, - endpoint: TWO_FACTOR_DELETE, - action: twoFactorDelete - } -] +const { addFunctionAsRoute, setFunctionRoute } = require('server/utils/server') +const { routes: tfaRoutes } = require('./tfa') +const { TFA } = require('./string-routes') +const privateRoutes = [] const publicRoutes = [] +/** + * Set private routes. + * + * @param {object} routes - object of routes + * @param {string} path - principal route + * @param {Function} action - function of route + */ +const setPrivateRoutes = (routes = {}, path = '', action = () => undefined) => { + if (Object.keys(routes).length > 0 && routes.constructor === Object) { + Object.keys(routes).forEach((route) => { + privateRoutes.push( + setFunctionRoute(route, path, + (req, res, next, connection, userId, user) => { + action(req, res, next, routes[route], user, connection) + }) + ) + }) + } +} + +/** + * Add routes. + * + * @returns {Array} routes + */ +const generatePrivateRoutes = () => { + setPrivateRoutes(tfaRoutes, TFA, addFunctionAsRoute) + return privateRoutes +} + const functionRoutes = { - private: privateRoutes, + private: generatePrivateRoutes(), public: publicRoutes } diff --git a/src/fireedge/src/server/routes/api/2fa/string-routes.js b/src/fireedge/src/server/routes/api/2fa/string-routes.js index 52ba330b0b..b3f68566da 100644 --- a/src/fireedge/src/server/routes/api/2fa/string-routes.js +++ b/src/fireedge/src/server/routes/api/2fa/string-routes.js @@ -1,26 +1,23 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 TWO_FACTOR_SETUP = '2fsetup'; -const TWO_FACTOR_QR = '2fqr'; -const TWO_FACTOR_DELETE = '2fdelete'; +const TFA = 'tfa' const Actions = { - TWO_FACTOR_SETUP, - TWO_FACTOR_QR, - TWO_FACTOR_DELETE -}; + TFA +} -module.exports = Actions; +module.exports = Actions diff --git a/src/fireedge/src/server/routes/api/2fa/tfa-functions.js b/src/fireedge/src/server/routes/api/2fa/tfa-functions.js new file mode 100644 index 0000000000..da8057cfd1 --- /dev/null +++ b/src/fireedge/src/server/routes/api/2fa/tfa-functions.js @@ -0,0 +1,270 @@ +/* ------------------------------------------------------------------------- * + * 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 speakeasy = require('speakeasy') +const qrcode = require('qrcode') + +const { + httpMethod, + default2FAIssuer, + defaultEmptyFunction, + default2FAOpennebulaVar, + default2FAOpennebulaTmpVar +} = require('server/utils/constants/defaults') +const { httpResponse } = require('server/utils/server') +const { getConfig } = require('server/utils/yml') +const { check2Fa } = require('server/utils/jwt') +const { Actions } = require('server/utils/constants/commands/user') +const { + responseOpennebula, + getDefaultParamsOfOpennebulaCommand, + generateNewResourceTemplate +} = require('server/utils/opennebula') + +// user config +const appConfig = getConfig() +const twoFactorAuthIssuer = + appConfig.TWO_FACTOR_AUTH_ISSUER || default2FAIssuer + +const { GET } = httpMethod + +const { + ok, + unauthorized, + internalServerError +} = require('server/utils/constants/http-codes') + +/** + * Get information for opennebula authenticated user. + * + * @param {Function} connect - xmlrpc function + * @param {Function} next - express stepper + * @param {Function} callback - run if have user information + */ +const getUserInfoAuthenticated = (connect = defaultEmptyFunction, next = defaultEmptyFunction, callback = defaultEmptyFunction) => { + connect( + Actions.USER_INFO, + getDefaultParamsOfOpennebulaCommand(Actions.USER_INFO, GET), + (err, value) => { + responseOpennebula( + () => undefined, + err, + value, + info => { + if (info !== undefined && info !== null) { + callback(info) + } else { + next() + } + }, + next + ) + } + ) +} + +/** + * Add 2FA user. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + * @param {Function} oneConnection - function of xmlrpc + */ +const setup = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}, oneConnection = defaultEmptyFunction) => { + const { token } = params + const oneConnect = oneConnection() + getUserInfoAuthenticated( + oneConnect, + next, + userData => { + if ( + userData && + userData.USER && + userData.USER.ID && + userData.USER.TEMPLATE && + userData.USER.TEMPLATE.SUNSTONE && + userData.USER.TEMPLATE.SUNSTONE[default2FAOpennebulaTmpVar] && + token + ) { + const sunstone = userData.USER.TEMPLATE.SUNSTONE + const secret = sunstone[default2FAOpennebulaTmpVar] + if (check2Fa(secret, token)) { + oneConnect( + Actions.USER_UPDATE, + [ + parseInt(userData.USER.ID, 10), + generateNewResourceTemplate( + userData.USER.TEMPLATE.SUNSTONE || {}, + { [default2FAOpennebulaVar]: secret }, + [default2FAOpennebulaTmpVar] + ), + 1 + ], + (error, value) => { + responseOpennebula( + () => undefined, + error, + value, + pass => { + if (pass !== undefined && pass !== null) { + res.locals.httpCode = httpResponse(ok) + } + next() + }, + next + ) + } + ) + } else { + res.locals.httpCode = httpResponse(unauthorized) + next() + } + } else { + next() + } + } + ) +} + +/** + * Generate QR. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + * @param {Function} oneConnection - function of xmlrpc + */ +const qr = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}, oneConnection = defaultEmptyFunction) => { + const secret = speakeasy.generateSecret({ + length: 10, + name: twoFactorAuthIssuer + }) + if (secret && secret.otpauth_url && secret.base32) { + const { otpauth_url: otpURL, base32 } = secret + qrcode.toDataURL(otpURL, (err, dataURL) => { + if (err) { + res.locals.httpCode = httpResponse(internalServerError) + next() + } else { + const oneConnect = oneConnection() + getUserInfoAuthenticated( + oneConnect, + next, + userData => { + if (userData && userData.USER && userData.USER.ID && userData.USER.TEMPLATE) { + oneConnect( + Actions.USER_UPDATE, + [ + parseInt(userData.USER.ID, 10), + generateNewResourceTemplate( + userData.USER.TEMPLATE.SUNSTONE || {}, + { [default2FAOpennebulaTmpVar]: base32 }, + [default2FAOpennebulaVar] + ), + 1 + ], + (error, value) => { + responseOpennebula( + () => undefined, + error, + value, + pass => { + if (pass !== undefined && pass !== null) { + res.locals.httpCode = httpResponse(ok, { + img: dataURL + }) + next() + } else { + next() + } + }, + next + ) + } + ) + } else { + next() + } + } + ) + } + }) + } else { + next() + } +} + +/** + * Delete 2fa. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + * @param {Function} oneConnection - function of xmlrpc + */ +const del = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}, oneConnection = defaultEmptyFunction) => { + const oneConnect = oneConnection() + getUserInfoAuthenticated( + oneConnect, + next, + userData => { + if ( + userData && + userData.USER && + userData.USER.ID && + userData.USER.TEMPLATE && + userData.USER.TEMPLATE.SUNSTONE + ) { + oneConnect( + Actions.USER_UPDATE, + [ + parseInt(userData.USER.ID, 10), + generateNewResourceTemplate( + userData.USER.TEMPLATE.SUNSTONE || {}, + {}, + [default2FAOpennebulaTmpVar, default2FAOpennebulaVar] + ), + 1 + ], + (err, value) => { + responseOpennebula( + () => undefined, + err, + value, + pass => { + if (pass !== undefined && pass !== null) { + res.locals.httpCode = httpResponse(ok) + } + next() + }, + next + ) + } + ) + } + } + ) +} +const tfaApi = { + setup, + qr, + del +} +module.exports = tfaApi diff --git a/src/fireedge/src/server/routes/api/2fa/tfa.js b/src/fireedge/src/server/routes/api/2fa/tfa.js new file mode 100644 index 0000000000..d8984bef4d --- /dev/null +++ b/src/fireedge/src/server/routes/api/2fa/tfa.js @@ -0,0 +1,50 @@ +/* ------------------------------------------------------------------------- * + * 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 { setup, qr, del } = require('./tfa-functions') +const { POST, DELETE, GET } = httpMethod + +const routes = { + [POST]: { + null: { + action: setup, + params: { + token: { + from: fromData.postBody, + name: 'token' + } + } + } + }, + [GET]: { + null: { + action: qr, + params: {} + } + }, + [DELETE]: { + null: { + action: del, + params: {} + } + } +} + +const authApi = { + routes +} +module.exports = authApi diff --git a/src/fireedge/src/server/routes/api/auth/auth-functions.js b/src/fireedge/src/server/routes/api/auth/auth-functions.js new file mode 100644 index 0000000000..87861d5ffb --- /dev/null +++ b/src/fireedge/src/server/routes/api/auth/auth-functions.js @@ -0,0 +1,117 @@ +/* ------------------------------------------------------------------------- * + * 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 { + login, + setUser, + setPass, + setType, + setTfaToken, + setExtended, + setNext, + setRes, + setNodeConnect, + connectOpennebula, + updaterResponse +} = require('./functions') + +const { internalServerError, unauthorized } = require('server/utils/constants/http-codes') +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') + +/** + * Login user. + * + * @param {error} err - run if no have user data + * @param {string} value - opennebula information + * @param {Function} success - success + * @param {Function} error - error + */ +const loginUser = (err = '', value = '', success = defaultEmptyFunction, error = defaultEmptyFunction) => { + if (value && value.USER && !err) { + success(value) + } else { + error() + } +} + +/** + * Fireedge user auth. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + * @param {Function} oneConnection - function of xmlrpc + */ +const auth = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}, oneConnection = defaultEmptyFunction) => { + const { user, token, type, token2fa, extended } = params + setRes(res) + setNext(next) + setNodeConnect(oneConnection) + updaterResponse(new Map(internalServerError).toObject()) + if (user && token) { + const oneConnect = connectOpennebula(user, token) + + /** + * Run if have information. + * + * @param {object} oneValue - opennebula value + */ + const success = oneValue => { + setUser(user || '') + setPass(token || '') + setType(type || '') + setTfaToken(token2fa || '') + setExtended(extended || '') + login(oneValue) + } + + /** + * Run if no have information. + */ + const error = () => { + updaterResponse(new Map(unauthorized).toObject()) + next() + } + + oneConnect( + Actions.USER_INFO, + getDefaultParamsOfOpennebulaCommand(Actions.USER_INFO, GET), + (err, value) => { + loginUser(err, value, success, error) + }, + false + ) + } else { + next() + } +} + +const authApi = { + auth +} +module.exports = authApi diff --git a/src/fireedge/src/server/routes/api/auth/auth.js b/src/fireedge/src/server/routes/api/auth/auth.js index b74a02feb7..085e40fd9f 100644 --- a/src/fireedge/src/server/routes/api/auth/auth.js +++ b/src/fireedge/src/server/routes/api/auth/auth.js @@ -1,108 +1,54 @@ -/* 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 { - login, - getUser, - getPass, - setUser, - setPass, - setType, - setTfaToken, - setExtended, - setNext, - setReq, - setRes, - setNodeConnect, - connectOpennebula, - updaterResponse -} = require('./functions') -const { internalServerError } = require('server/utils/constants/http-codes') -const { Actions } = require('server/utils/constants/commands/user') -const { - httpMethod -} = require('server/utils/constants/defaults') -const { - paramsDefaultByCommandOpennebula, - responseOpennebula, - checkOpennebulaCommand -} = require('server/utils/opennebula') -const { from } = require('server/utils/constants/defaults') +/* ------------------------------------------------------------------------- * + * 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 { POST, GET } = httpMethod +const { httpMethod, from: fromData } = require('server/utils/constants/defaults') +const { auth } = require('./auth-functions') +const { POST } = httpMethod -const auth = (req, res, next, connect) => { - if (req && res && connect) { - setReq(req) - setRes(res) - setNext(next) - updaterResponse(new Map(internalServerError).toObject()) - const getOpennebulaMethod = checkOpennebulaCommand( - Actions.USER_LOGIN, - POST - ) - if (getOpennebulaMethod) { - setUser( - (req && - from.postBody && - req[from.postBody] && - req[from.postBody].user) || - '' - ) - setPass( - (req && - from.postBody && - req[from.postBody] && - req[from.postBody].token) || - '' - ) - setType( - (req && - from.postBody && - req[from.postBody] && - req[from.postBody].type && - req[from.postBody].type.toLowerCase()) || - '' - ) - setTfaToken( - (req && req[from.postBody] && req[from.postBody].token2fa) || '' - ) - setExtended( - (req && req[from.postBody] && req[from.postBody].extended) || '' - ) - setNodeConnect(connect) - if (getUser() && getPass()) { - const oneConnect = connectOpennebula() - oneConnect( - Actions.USER_INFO, - paramsDefaultByCommandOpennebula(Actions.USER_INFO, GET), - (err, value) => { - responseOpennebula(updaterResponse, err, value, login, next) - }, - false - ) +const routes = { + [POST]: { + null: { + action: auth, + params: { + user: { + from: fromData.postBody, + name: 'user' + }, + token: { + from: fromData.postBody, + name: 'token' + }, + type: { + from: fromData.postBody, + name: 'type' + }, + token2fa: { + from: fromData.postBody, + name: 'token2fa' + }, + extended: { + from: fromData.postBody, + name: 'extended' + } } - } else { - next() } - } else { - next() } } const authApi = { - auth + routes } module.exports = authApi diff --git a/src/fireedge/src/server/routes/api/auth/functions.js b/src/fireedge/src/server/routes/api/auth/functions.js index f1ff8fc8c9..aad7dc3c5b 100644 --- a/src/fireedge/src/server/routes/api/auth/functions.js +++ b/src/fireedge/src/server/routes/api/auth/functions.js @@ -1,19 +1,20 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { DateTime } = require('luxon') -const { Map } = require('immutable') // eslint-disable-next-line node/no-deprecated-api const { parse } = require('url') const { global, Array } = require('window-or-global') @@ -23,7 +24,8 @@ const { httpMethod, defaultOpennebulaExpiration, default2FAOpennebulaVar, - defaultNamespace + defaultNamespace, + defaultEmptyFunction } = require('server/utils/constants/defaults') const { getConfig } = require('server/utils/yml') const { @@ -32,21 +34,18 @@ const { accepted, internalServerError } = require('server/utils/constants/http-codes') -const { createToken } = require('server/utils/jwt') +const { createJWT, check2Fa } = require('server/utils/jwt') const { httpResponse, encrypt, getSunstoneAuth } = require('server/utils/server') const { responseOpennebula, - checkOpennebulaCommand, - check2Fa + getDefaultParamsOfOpennebulaCommand } = require('server/utils/opennebula') const appConfig = getConfig() const namespace = appConfig.namespace || defaultNamespace -const { POST } = httpMethod - -const getOpennebulaMethod = checkOpennebulaCommand(ActionUsers.USER_LOGIN, POST) +const { GET } = httpMethod let user = '' let key = '' @@ -55,75 +54,174 @@ let pass = '' let type = '' let tfatoken = '' let extended = '' -let next = () => undefined +let next = defaultEmptyFunction let req = {} let res = {} -let nodeConnect = () => undefined +let nodeConnect = defaultEmptyFunction let now = '' let nowUnix = '' let nowWithMinutes = '' let relativeTime = '' -const dataSourceWithExpirateDate = () => Map(req).toObject() - +/** + * Get key opennebula. + * + * @returns {string} get key + */ const getKey = () => key + +/** + * Get initialization vector. + * + * @returns {string} get initialization vector + */ const getIV = () => iv + +/** + * Get user opennebula. + * + * @returns {string} user opennebula + */ const getUser = () => user + +/** + * Get user password openebula. + * + * @returns {string} get password user opennebula + */ const getPass = () => pass + +/** + * Get relative time. + * + * @returns {string} date + */ const getRelativeTime = () => relativeTime +/** + * Opennebula encode-decode key. + * + * @param {string} newKey - new key + * @returns {string} get key + */ const setKey = newKey => { key = newKey return key } +/** + * Initialization vector (encrypt). + * + * @param {string} newIV - //16 characters + * @returns {string} get IV + */ const setIV = newIV => { iv = newIV return iv } +/** + * Username opennebula. + * + * @param {string} newUser - new user data + * @returns {string} get user + */ const setUser = newUser => { user = newUser return user } +/** + * User password opennebula. + * + * @param {string} newPass - set new opennebula password user + * @returns {string} password user + */ const setPass = newPass => { pass = newPass return pass } +/** + * Type app. + * + * @param {string} newtype - new type (application) + * @returns {string} get type + */ const setType = newtype => { type = newtype return type } +/** + * Set 2FA token. + * + * @param {string} newTfaToken - new TFA token + * @returns {string} get TFA token + */ const setTfaToken = newTfaToken => { tfatoken = newTfaToken return tfatoken } +/** + * Set extended. + * + * @param {boolean} newExtended - new extended + * @returns {boolean} extended + */ const setExtended = newExtended => { extended = newExtended return extended } -const setNext = newNext => { + +/** + * Set express stepper. + * + * @param {Function} newNext - new stepper + * @returns {Function} http response + */ +const setNext = (newNext = defaultEmptyFunction) => { next = newNext return next } -const setReq = newReq => { + +/** + * Set http resquest. + * + * @param {object} newReq - new request + * @returns {object} http resquest + */ +const setReq = (newReq = {}) => { req = newReq return req } -const setNodeConnect = newConnect => { + +/** + * Set xlmrpc connection function. + * + * @param {Function} newConnect - new connect opennebula + * @returns {Function} xmlrpc function + */ +const setNodeConnect = (newConnect = defaultEmptyFunction) => { nodeConnect = newConnect return nodeConnect } -const setRes = newRes => { +/** + * Set http response. + * + * @param {object} newRes - new response + * @returns {object} http response + */ +const setRes = (newRes = {}) => { res = newRes return res } +/** + * Set dates. + */ const setDates = () => { const limitToken = appConfig.opennebula_expiration || defaultOpennebulaExpiration now = DateTime.local() @@ -133,12 +231,24 @@ const setDates = () => { relativeTime = diff.seconds } +/** + * Connect to function xmlrpc. + * + * @param {string} usr - user + * @param {string} pss - password + * @returns {Function} xmlrpc function + */ const connectOpennebula = (usr = '', pss = '') => { const connectUser = usr || user const connectPass = pss || pass return nodeConnect(connectUser, connectPass) } +/** + * Updater http request. + * + * @param {string} code - http code + */ const updaterResponse = code => { if ( 'id' in code && @@ -151,6 +261,12 @@ const updaterResponse = code => { } } +/** + * Validate 2FA. + * + * @param {object} informationUser - user data + * @returns {boolean} return if data is valid + */ const validate2faAuthentication = informationUser => { let rtn = false if ( @@ -182,12 +298,18 @@ const validate2faAuthentication = informationUser => { return rtn } +/** + * Generate a JWT. + * + * @param {string} token - opennebula token + * @param {object} informationUser - user data + */ const genJWT = (token, informationUser) => { if (token && token.token && informationUser && informationUser.ID && informationUser.NAME) { const { ID: id, TEMPLATE: userTemplate, NAME: user } = informationUser const dataJWT = { id, user, token: token.token } const addTime = token.expiration_time || nowWithMinutes.toSeconds() - const jwt = createToken(dataJWT, nowUnix, addTime) + const jwt = createJWT(dataJWT, nowUnix, addTime) if (jwt) { if (!global.users) { global.users = {} @@ -202,13 +324,15 @@ const genJWT = (token, informationUser) => { } } +/** + * Get zones. + */ const setZones = () => { if (global && !global.zones) { const oneConnect = connectOpennebula() - const dataSource = dataSourceWithExpirateDate() oneConnect( ActionZones.ZONEPOOL_INFO, - getOpennebulaMethod(dataSource), + getDefaultParamsOfOpennebulaCommand(ActionZones.ZONEPOOL_INFO, GET), (err, value) => { // res, err, value, response, next responseOpennebula( @@ -245,6 +369,13 @@ const setZones = () => { } } +/** + * Create token server admin. + * + * @param {string} serverAdmin - serveradmin name + * @param {string} username - user name + * @returns {string} data encrypted serveradmin + */ const createTokenServerAdmin = (serverAdmin = '', username = '') => { let rtn const key = getKey() @@ -259,6 +390,12 @@ const createTokenServerAdmin = (serverAdmin = '', username = '') => { return rtn } +/** + * Wrap user with serveradmin. + * + * @param {object} serverAdminData - opennebula serveradmin data + * @param {object} userData - opennebula user data + */ const wrapUserWithServerAdmin = (serverAdminData = {}, userData = {}) => { const relativeTime = getRelativeTime() let serverAdminName = '' @@ -303,6 +440,11 @@ const wrapUserWithServerAdmin = (serverAdminData = {}, userData = {}) => { } } +/** + * Get server admin and wrap user. + * + * @param {object} userData - opennebula user data + */ const getServerAdminAndWrapUser = (userData = {}) => { const serverAdminData = getSunstoneAuth() if (serverAdminData && @@ -316,7 +458,7 @@ const getServerAdminAndWrapUser = (userData = {}) => { const oneConnect = connectOpennebula(`${serverAdminData.username}:${serverAdminData.username}`, tokenWithServerAdmin) oneConnect( ActionUsers.USER_INFO, - [-1, false], + getDefaultParamsOfOpennebulaCommand(ActionUsers.USER_INFO, GET), (err, value) => { responseOpennebula( updaterResponse, @@ -330,6 +472,11 @@ const getServerAdminAndWrapUser = (userData = {}) => { } } +/** + * Login route function. + * + * @param {object} userData - opennebula user data + */ const login = userData => { let rtn = false if (userData) { diff --git a/src/fireedge/src/server/routes/api/auth/index.js b/src/fireedge/src/server/routes/api/auth/index.js index 5f57ad3645..b1723da303 100644 --- a/src/fireedge/src/server/routes/api/auth/index.js +++ b/src/fireedge/src/server/routes/api/auth/index.js @@ -1,36 +1,59 @@ -/* 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 { AUTH } = require('./string-routes') -const { httpMethod } = require('server/utils/constants/defaults') -const { auth } = require('./auth') +/* ------------------------------------------------------------------------- * + * 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 { POST } = httpMethod +const { addFunctionAsRoute, setFunctionRoute } = require('server/utils/server') +const { routes: authRoutes } = require('./auth') +const { AUTH } = require('./string-routes') const privateRoutes = [] +const publicRoutes = [] -const publicRoutes = [ - { - httpMethod: POST, - endpoint: AUTH, - action: auth +/** + * Set private routes. + * + * @param {object} routes - object of routes + * @param {string} path - principal route + * @param {Function} action - function of route + */ +const setPublicRoutes = (routes = {}, path = '', action = () => undefined) => { + if (Object.keys(routes).length > 0 && routes.constructor === Object) { + Object.keys(routes).forEach((route) => { + publicRoutes.push( + setFunctionRoute(route, path, + (req, res, next, connection, userId, user) => { + action(req, res, next, routes[route], user, connection) + }) + ) + }) } -] +} + +/** + * Add routes. + * + * @returns {Array} routes + */ +const generatePublicRoutes = () => { + setPublicRoutes(authRoutes, AUTH, addFunctionAsRoute) + return publicRoutes +} const functionRoutes = { private: privateRoutes, - public: publicRoutes + public: generatePublicRoutes() } module.exports = functionRoutes diff --git a/src/fireedge/src/server/routes/api/auth/string-routes.js b/src/fireedge/src/server/routes/api/auth/string-routes.js index dc46f7319d..f209c20655 100644 --- a/src/fireedge/src/server/routes/api/auth/string-routes.js +++ b/src/fireedge/src/server/routes/api/auth/string-routes.js @@ -1,22 +1,23 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 AUTH = 'auth'; +const AUTH = 'auth' const Actions = { AUTH -}; +} -module.exports = Actions; +module.exports = Actions diff --git a/src/fireedge/src/server/routes/api/index.js b/src/fireedge/src/server/routes/api/index.js index 65e1ae0315..3ae33cece9 100644 --- a/src/fireedge/src/server/routes/api/index.js +++ b/src/fireedge/src/server/routes/api/index.js @@ -1,18 +1,18 @@ -/* eslint-disable import/no-dynamic-require */ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { messageTerminal } = require('server/utils/general') const { getRouteForOpennebulaCommand } = require('server/utils/opennebula') diff --git a/src/fireedge/src/server/routes/api/oneflow/functions.js b/src/fireedge/src/server/routes/api/oneflow/functions.js index 63ca6bc4e7..40d908478c 100644 --- a/src/fireedge/src/server/routes/api/oneflow/functions.js +++ b/src/fireedge/src/server/routes/api/oneflow/functions.js @@ -1,17 +1,19 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { request: axios } = require('axios') const btoa = require('btoa') @@ -24,16 +26,35 @@ const { GET, DELETE } = httpMethod const appConfig = getConfig() +/** + * Return schema error. + * + * @param {string} error - get error for schema + * @returns {string} schema + */ const returnSchemaError = (error = []) => error .map(element => (element && element.stack ? element.stack : '')) .toString() +/** + * Parse number to int. + * + * @param {string} validate - number to validate + * @returns {number}number to int + */ const parseToNumber = validate => isNaN(parseInt(validate, 10)) ? validate : parseInt(validate, 10) +/** + * Connection to one flow server. + * + * @param {object} requestData - data for request + * @param {Function} success - callback success function + * @param {Function} error - callback error function + */ const oneFlowConection = (requestData = {}, success = () => undefined, error = () => undefined) => { const { method, path, user, password, request, post } = requestData const optionMethod = method || GET diff --git a/src/fireedge/src/server/routes/api/oneflow/index.js b/src/fireedge/src/server/routes/api/oneflow/index.js index 9be0eaa0bb..631e4fd77f 100644 --- a/src/fireedge/src/server/routes/api/oneflow/index.js +++ b/src/fireedge/src/server/routes/api/oneflow/index.js @@ -1,19 +1,20 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { addFunctionToRoute, fillFunctionRoute } = require('server/utils/server') +const { addFunctionAsRoute, setFunctionRoute } = require('server/utils/server') const { routes: serviceRoutes } = require('./service') const { routes: serviceTemplateRoutes } = require('./service_template') @@ -22,11 +23,18 @@ const { SERVICE, SERVICE_TEMPLATE } = require('./string-routes') const privateRoutes = [] const publicRoutes = [] -const fillPrivateRoutes = (methods = {}, path = '', action = () => undefined) => { +/** + * Set private routes. + * + * @param {object} methods - object of routes + * @param {string} path - principal route + * @param {Function} action - function of route + */ +const setPrivateRoutes = (methods = {}, path = '', action = () => undefined) => { if (Object.keys(methods).length > 0 && methods.constructor === Object) { Object.keys(methods).forEach((method) => { privateRoutes.push( - fillFunctionRoute(method, path, + setFunctionRoute(method, path, (req, res, next, connection, userId, user) => { action(req, res, next, methods[method], user, connection) }) @@ -35,9 +43,14 @@ const fillPrivateRoutes = (methods = {}, path = '', action = () => undefined) => } } +/** + * Add routes. + * + * @returns {Array} routes + */ const generatePrivateRoutes = () => { - fillPrivateRoutes(serviceRoutes, SERVICE, addFunctionToRoute) - fillPrivateRoutes(serviceTemplateRoutes, SERVICE_TEMPLATE, addFunctionToRoute) + setPrivateRoutes(serviceRoutes, SERVICE, addFunctionAsRoute) + setPrivateRoutes(serviceTemplateRoutes, SERVICE_TEMPLATE, addFunctionAsRoute) return privateRoutes } diff --git a/src/fireedge/src/server/routes/api/oneflow/schemas.js b/src/fireedge/src/server/routes/api/oneflow/schemas.js index e976f854db..d9ee80881b 100644 --- a/src/fireedge/src/server/routes/api/oneflow/schemas.js +++ b/src/fireedge/src/server/routes/api/oneflow/schemas.js @@ -1,17 +1,18 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 action = { id: '/Action', 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 f13213df70..fb48597a5a 100644 --- a/src/fireedge/src/server/routes/api/oneflow/service-functions.js +++ b/src/fireedge/src/server/routes/api/oneflow/service-functions.js @@ -1,22 +1,23 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { Validator } = require('jsonschema') const { action } = require('./schemas') const { oneFlowConection } = require('./functions') -const { httpMethod } = require('server/utils/constants/defaults') +const { httpMethod, defaultEmptyFunction } = require('server/utils/constants/defaults') const { httpResponse, parsePostData } = require('server/utils/server') const { ok, @@ -26,41 +27,69 @@ const { const { returnSchemaError } = require('./functions') const { GET, POST, DELETE } = httpMethod -const service = (res = {}, next = () => undefined, params = {}, userData = {}) => { - const { user, password } = userData - const success = data => { +/** + * Response http when have information. + * + * @param {Function} next - express stepper + * @param {object} res - response http + * @param {string} data - data response http + */ +const success = (next = defaultEmptyFunction, res = {}, data = '') => { + if ((next && typeof next === 'function') && (res && res.locals && res.locals.httpCode)) { res.locals.httpCode = httpResponse(ok, data) next() } - const error = data => { +} + +/** + * Response http when no have information. + * + * @param {Function} next - express stepper + * @param {object} res - response http + * @param {string} data - data response http + */ +const error = (next = defaultEmptyFunction, res = {}, data = '') => { + if ((next && typeof next === 'function') && (res && res.locals && res.locals.httpCode)) { res.locals.httpCode = httpResponse(internalServerError, data && data.message) next() } +} + +/** + * Get service. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params + * @param {object} userData - user data + */ +const service = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { + const { user, password } = userData if (user && password) { const config = { method: GET, path: '/service', user, password } if (params && params.id) { config.path = '/service/{0}' config.request = params.id - oneFlowConection(config, success, error) + oneFlowConection(config, data => success(next, res, data), data => error(next, res, data)) } else { - oneFlowConection(config, success, error) + oneFlowConection(config, data => success(next, res, data), data => error(next, res, data)) } } } -const serviceDelete = (res = {}, next = () => undefined, params = {}, userData = {}) => { +/** + * Delete service. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params + * @param {object} userData - user data + */ +const serviceDelete = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData - const success = data => { - res.locals.httpCode = httpResponse(ok, data) - next() - } - const error = data => { - res.locals.httpCode = httpResponse(internalServerError, data && data.message) - next() - } if (params && params.id && user && password) { const config = { method: DELETE, path: '/service/{0}', user, password, request: params.id } - oneFlowConection(config, success, error) + oneFlowConection(config, data => success(next, res, data), data => error(next, res, data)) } else { res.locals.httpCode = httpResponse( methodNotAllowed, @@ -71,16 +100,16 @@ const serviceDelete = (res = {}, next = () => undefined, params = {}, userData = } } -const serviceAddAction = (res = {}, next = () => undefined, params = {}, userData = {}) => { +/** + * Add action service. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params + * @param {object} userData - user data + */ +const serviceAddAction = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData - const success = data => { - res.locals.httpCode = httpResponse(ok, data) - next() - } - const error = data => { - res.locals.httpCode = httpResponse(internalServerError, data && data.message) - next() - } if (params && params.id && params.action && user && password) { const v = new Validator() const postAction = parsePostData(params.action) @@ -94,7 +123,7 @@ const serviceAddAction = (res = {}, next = () => undefined, params = {}, userDat request: params.id, post: postAction } - oneFlowConection(config, success, error) + oneFlowConection(config, data => success(next, res, data), data => error(next, res, data)) } else { res.locals.httpCode = httpResponse( internalServerError, @@ -113,16 +142,16 @@ const serviceAddAction = (res = {}, next = () => undefined, params = {}, userDat } } -const serviceAddScale = (res = {}, next = () => undefined, params = {}, userData = {}) => { +/** + * Add scale service. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params + * @param {object} userData - user data + */ +const serviceAddScale = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData - const success = data => { - res.locals.httpCode = httpResponse(ok, data) - next() - } - const error = data => { - res.locals.httpCode = httpResponse(internalServerError, data && data.message) - next() - } if (params && params.id && params.action && user && password) { const v = new Validator() const postAction = parsePostData(params.action) @@ -136,7 +165,7 @@ const serviceAddScale = (res = {}, next = () => undefined, params = {}, userData request: params.id, post: postAction } - oneFlowConection(config, success, error) + oneFlowConection(config, data => success(next, res, data), data => error(next, res, data)) } else { res.locals.httpCode = httpResponse( internalServerError, @@ -155,16 +184,16 @@ const serviceAddScale = (res = {}, next = () => undefined, params = {}, userData } } -const serviceAddRoleAction = (res = {}, next = () => undefined, params = {}, userData = {}) => { +/** + * Add service role action. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params + * @param {object} userData - user data + */ +const serviceAddRoleAction = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData - const success = data => { - res.locals.httpCode = httpResponse(ok, data) - next() - } - const error = data => { - res.locals.httpCode = httpResponse(internalServerError, data && data.message) - next() - } if (params && params.role && params.id && params.action && user && password) { const v = new Validator() const postAction = parsePostData(params.action) @@ -178,7 +207,7 @@ const serviceAddRoleAction = (res = {}, next = () => undefined, params = {}, use request: [params.role, params.id], post: postAction } - oneFlowConection(config, success, error) + oneFlowConection(config, data => success(next, res, data), data => error(next, res, data)) } else { res.locals.httpCode = httpResponse( internalServerError, diff --git a/src/fireedge/src/server/routes/api/oneflow/service.js b/src/fireedge/src/server/routes/api/oneflow/service.js index 3ec3a08446..4fa91e4c27 100644 --- a/src/fireedge/src/server/routes/api/oneflow/service.js +++ b/src/fireedge/src/server/routes/api/oneflow/service.js @@ -1,20 +1,20 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { getParamsForObject } = require('server/utils/server') const { service, serviceDelete, diff --git a/src/fireedge/src/server/routes/api/oneflow/service_template-functions.js b/src/fireedge/src/server/routes/api/oneflow/service_template-functions.js index f99865479f..98897f3afb 100644 --- a/src/fireedge/src/server/routes/api/oneflow/service_template-functions.js +++ b/src/fireedge/src/server/routes/api/oneflow/service_template-functions.js @@ -1,21 +1,23 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { Validator } = require('jsonschema') const { role, service, action } = require('./schemas') const { oneFlowConection } = require('./functions') -const { httpMethod } = require('server/utils/constants/defaults') +const { httpMethod, defaultEmptyFunction } = require('server/utils/constants/defaults') const { httpResponse, parsePostData } = require('server/utils/server') const { ok, @@ -25,41 +27,71 @@ const { const { returnSchemaError } = require('./functions') const { GET, POST, DELETE, PUT } = httpMethod -const serviceTemplate = (res = {}, next = () => undefined, params = {}, userData = {}) => { - const { user, password } = userData - const success = data => { +/** + * Response http when have information. + * + * @param {Function} next - express stepper + * @param {object} res - response http + * @param {string} data - data response http + */ +const success = (next = defaultEmptyFunction, res = {}, data = '') => { + if ((next && typeof next === 'function') && (res && res.locals && res.locals.httpCode)) { res.locals.httpCode = httpResponse(ok, data) next() } - const error = data => { +} + +/** + * Response http when no have information. + * + * @param {Function} next - express stepper + * @param {object} res - response http + * @param {string} data - data response http + */ +const error = (next = defaultEmptyFunction, res = {}, data = '') => { + if ((next && typeof next === 'function') && (res && res.locals && res.locals.httpCode)) { res.locals.httpCode = httpResponse(internalServerError, data && data.message) next() } +} + +/** + * Get service template. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params + * @param {object} userData - user data + */ +const serviceTemplate = (res = {}, next = () => undefined, params = {}, userData = {}) => { + const { user, password } = userData + if (user && password) { const config = { method: GET, path: '/service_template', user, password } if (params && params.id) { config.path = '/service_template/{0}' config.request = params.id - oneFlowConection(config, success, error) + oneFlowConection(config, data => success(next, res, data), data => error(next, res, data)) } else { - oneFlowConection(config, success, error) + oneFlowConection(config, data => success(next, res, data), data => error(next, res, data)) } } } +/** + * Delete service template. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params + * @param {object} userData - user data + */ const serviceTemplateDelete = (res = {}, next = () => undefined, params = {}, userData = {}) => { const { user, password } = userData - const success = data => { - res.locals.httpCode = httpResponse(ok, data) - next() - } - const error = data => { - res.locals.httpCode = httpResponse(internalServerError, data && data.message) - next() - } + if (params && params.id && user && password) { const config = { method: DELETE, path: '/service_template/{0}', user, password, request: params.id } - oneFlowConection(config, success, error) + oneFlowConection(config, data => success(next, res, data), data => error(next, res, data)) } else { res.locals.httpCode = httpResponse( methodNotAllowed, @@ -70,16 +102,16 @@ const serviceTemplateDelete = (res = {}, next = () => undefined, params = {}, us } } +/** + * Create service template. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params + * @param {object} userData - user data + */ const serviceTemplateCreate = (res = {}, next = () => undefined, params = {}, userData = {}) => { const { user, password } = userData - const success = data => { - res.locals.httpCode = httpResponse(ok, data) - next() - } - const error = data => { - res.locals.httpCode = httpResponse(internalServerError, data && data.message) - next() - } if (params && params.template && user && password) { const v = new Validator() const template = parsePostData(params.template) @@ -93,7 +125,7 @@ const serviceTemplateCreate = (res = {}, next = () => undefined, params = {}, us password, post: template } - oneFlowConection(config, success, error) + oneFlowConection(config, data => success(next, res, data), data => error(next, res, data)) } else { res.locals.httpCode = httpResponse( internalServerError, @@ -111,16 +143,16 @@ const serviceTemplateCreate = (res = {}, next = () => undefined, params = {}, us } } +/** + * Update service template. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params + * @param {object} userData - user data + */ const serviceTemplateUpdate = (res = {}, next = () => undefined, params = {}, userData = {}) => { const { user, password } = userData - const success = data => { - res.locals.httpCode = httpResponse(ok, data) - next() - } - const error = data => { - res.locals.httpCode = httpResponse(internalServerError, data && data.message) - next() - } if (params && params.id && params.template && user && password) { const v = new Validator() v.addSchema(role, '/Role') @@ -135,7 +167,7 @@ const serviceTemplateUpdate = (res = {}, next = () => undefined, params = {}, us request: params.id, post: template } - oneFlowConection(config, success, error) + oneFlowConection(config, data => success(next, res, data), data => error(next, res, data)) } else { res.locals.httpCode = httpResponse( internalServerError, @@ -154,16 +186,16 @@ const serviceTemplateUpdate = (res = {}, next = () => undefined, params = {}, us } } +/** + * Add service action. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params + * @param {object} userData - user data + */ const serviceTemplateAction = (res = {}, next = () => undefined, params = {}, userData = {}) => { const { user, password } = userData - const success = data => { - res.locals.httpCode = httpResponse(ok, data) - next() - } - const error = data => { - res.locals.httpCode = httpResponse(internalServerError, data && data.message) - next() - } if (params && params.id && params.template && user && password) { const v = new Validator() const template = parsePostData(params.template) @@ -177,7 +209,7 @@ const serviceTemplateAction = (res = {}, next = () => undefined, params = {}, us request: params.id, post: template } - oneFlowConection(config, success, error) + oneFlowConection(config, data => success(next, res, data), data => error(next, res, data)) } else { res.locals.httpCode = httpResponse( internalServerError, diff --git a/src/fireedge/src/server/routes/api/oneflow/service_template.js b/src/fireedge/src/server/routes/api/oneflow/service_template.js index be374a1291..1a3e80a844 100644 --- a/src/fireedge/src/server/routes/api/oneflow/service_template.js +++ b/src/fireedge/src/server/routes/api/oneflow/service_template.js @@ -1,17 +1,18 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { diff --git a/src/fireedge/src/server/routes/api/oneflow/string-routes.js b/src/fireedge/src/server/routes/api/oneflow/string-routes.js index 8e31f43200..3eed3f8fff 100644 --- a/src/fireedge/src/server/routes/api/oneflow/string-routes.js +++ b/src/fireedge/src/server/routes/api/oneflow/string-routes.js @@ -1,17 +1,18 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 SERVICE = 'service' const SERVICE_TEMPLATE = 'service_template' diff --git a/src/fireedge/src/server/routes/api/provision/functions.js b/src/fireedge/src/server/routes/api/provision/functions.js index 97840cb3f1..bb3c309cde 100644 --- a/src/fireedge/src/server/routes/api/provision/functions.js +++ b/src/fireedge/src/server/routes/api/provision/functions.js @@ -1,17 +1,19 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { v4 } = require('uuid') const { dirname, basename } = require('path') // eslint-disable-next-line node/no-deprecated-api @@ -31,16 +33,28 @@ const { const { getConfig } = require('server/utils/yml') const { spawnSync, spawn } = require('child_process') const { messageTerminal } = require('server/utils/general') -const { defaultError, getDirectories } = require('server/utils/server') +const { defaultError } = require('server/utils/server') const eventsEmitter = new events.EventEmitter() +/** + * Create a event emiter. + * + * @param {string} eventName - name event + * @param {object} message - object message + */ const publish = (eventName = '', message = {}) => { if (eventName && message) { eventsEmitter.emit(eventName, message) } } +/** + * Subscriber to event emitter. + * + * @param {string} eventName - event name + * @param {Function} callback - function executed when event is emited + */ const subscriber = (eventName = '', callback = () => undefined) => { if (eventName && callback && @@ -56,6 +70,14 @@ const subscriber = (eventName = '', callback = () => undefined) => { } } +/** + * Create folder with files. + * + * @param {string} path - path to create files + * @param {Array} files - files to create + * @param {string} filename - return name + * @returns {object} object with files created + */ const createFolderWithFiles = (path = '', files = [], filename = '') => { const rtn = { name: '', files: [] } const name = filename || v4().replace(/-/g, '').toUpperCase() @@ -68,9 +90,8 @@ const createFolderWithFiles = (path = '', files = [], filename = '') => { if (files && Array.isArray(files)) { files.forEach(file => { if (file && file.name && file.ext) { - const filePath = `${internalPath}/${file.name}.${file.ext}` - rtn.files.push({ name: file.name, ext: file.ext, path: filePath }) - writeFileSync(filePath, (file && file.content) || '') + rtn.files.push({ name: file.name, ext: file.ext, path: `${internalPath}/${file.name}.${file.ext}` }) + createTemporalFile(internalPath, file.ext, (file && file.content) || '', file.name) } }) } @@ -80,6 +101,15 @@ const createFolderWithFiles = (path = '', files = [], filename = '') => { return rtn } +/** + * Create a temporal file. + * + * @param {string} path - path of temporal file + * @param {string} ext - extension of the temporal file + * @param {string} content - content of the temporal file + * @param {string} filename - name of the temporal file + * @returns {object} if file is created + */ const createTemporalFile = (path = '', ext = '', content = '', filename = '') => { let rtn const name = filename || v4().replace(/-/g, '').toUpperCase() @@ -96,6 +126,12 @@ const createTemporalFile = (path = '', ext = '', content = '', filename = '') => return rtn } +/** + * Parse content of yaml to json. + * + * @param {string} content - content yaml + * @returns {string} data yaml in json + */ const createYMLContent = (content = '') => { let rtn try { @@ -114,6 +150,11 @@ const createYMLContent = (content = '') => { return rtn } +/** + * Delete file. + * + * @param {string} path - the path for delete + */ const removeFile = (path = '') => { if (path) { try { @@ -124,6 +165,15 @@ const removeFile = (path = '') => { } } +/** + * Rename folder. + * + * @param {string} path - path of folder + * @param {string} name - new name of folder + * @param {string} type - must be "prepend", "append" or "replace" + * @param {Function} callback - function that runs before renaming the folder + * @returns {string} if the folder name was changed + */ const renameFolder = (path = '', name = '', type = 'replace', callback) => { let rtn = false if (path) { @@ -158,6 +208,13 @@ const renameFolder = (path = '', name = '', type = 'replace', callback) => { return rtn } +/** + * Move file to path. + * + * @param {string} path - path of file + * @param {string} relative - relative path + * @returns {boolean} check if file is moved + */ const moveToFolder = (path = '', relative = '/../') => { let rtn = false if (path && relative) { @@ -171,6 +228,13 @@ const moveToFolder = (path = '', relative = '/../') => { return rtn } +/** + * Add prepend of command example: 'ssh xxxx:'". + * + * @param {string} command - cli command + * @param {string} resource - resource by command + * @returns {object} command and resource + */ const addPrependCommand = (command = '', resource = '') => { const appConfig = getConfig() const prependCommand = appConfig.oneprovision_prepend_command || '' @@ -197,12 +261,24 @@ const addPrependCommand = (command = '', resource = '') => { } } +/** + * Add command optional params from fireedge server config. + * + * @returns {Array} command optional params + */ const addOptionalCreateCommand = () => { const appConfig = getConfig() const optionalCreateCommand = appConfig.oneprovision_optional_create_command || '' - return [optionalCreateCommand].filter(Boolean) + return [optionalCreateCommand] } +/** + * Run Asynchronous commands for CLI. + * + * @param {string} command - command to execute + * @param {string} resource - params for the command to execute + * @param {object} callbacks - the functions in case the command emits by the stderr(err), stdout(out) and when it finishes(close) + */ const executeCommandAsync = ( command = '', resource = '', @@ -241,6 +317,14 @@ const executeCommandAsync = ( } } +/** + * Run Synchronous commands for CLI. + * + * @param {string} command - command to execute + * @param {string} resource - params for the command to execute + * @param {object} options - optional params for the command + * @returns {object} CLI output + */ const executeCommand = (command = '', resource = '', options = {}) => { let rtn = { success: false, data: null } const { cmd, rsc } = addPrependCommand(command, resource) @@ -256,6 +340,14 @@ const executeCommand = (command = '', resource = '', options = {}) => { return rtn } +/** + * Get recursive folder from a directory. + * + * @param {string} path - path to create files + * @param {string} finder - finder path + * @param {boolean} rtn - return of function (recursive) + * @returns {string} paths + */ const findRecursiveFolder = (path = '', finder = '', rtn = false) => { if (path && finder) { try { @@ -277,6 +369,11 @@ const findRecursiveFolder = (path = '', finder = '', rtn = false) => { return rtn } +/** + * Get the xmlrpc connection endpoint. + * + * @returns {Array} array endpoint xmlrpc connection + */ const getEndpoint = () => { let rtn = [] const appConfig = getConfig() diff --git a/src/fireedge/src/server/routes/api/provision/index.js b/src/fireedge/src/server/routes/api/provision/index.js index db41613347..7085df3627 100644 --- a/src/fireedge/src/server/routes/api/provision/index.js +++ b/src/fireedge/src/server/routes/api/provision/index.js @@ -1,18 +1,20 @@ -/* 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 { addFunctionToRoute, fillFunctionRoute } = require('server/utils/server') +/* ------------------------------------------------------------------------- * + * 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 { addFunctionAsRoute, setFunctionRoute } = require('server/utils/server') const { routes: provisionRoutes } = require('./provision') const { routes: provisionTemplateRoutes } = require('./provision_template') const { routes: providerRoutes } = require('./provider') @@ -22,23 +24,35 @@ const { PROVIDER, PROVISION, PROVISION_TEMPLATE } = require('./string-routes') const privateRoutes = [] const publicRoutes = [] -const fillPrivateRoutes = (methods = {}, path = '', action = () => undefined) => { - if (Object.keys(methods).length > 0 && methods.constructor === Object) { - Object.keys(methods).forEach((method) => { +/** + * Set private routes. + * + * @param {object} routes - object of routes + * @param {string} path - principal route + * @param {Function} action - function of route + */ +const setPrivateRoutes = (routes = {}, path = '', action = () => undefined) => { + if (Object.keys(routes).length > 0 && routes.constructor === Object) { + Object.keys(routes).forEach((route) => { privateRoutes.push( - fillFunctionRoute(method, path, + setFunctionRoute(route, path, (req, res, next, connection, userId, user) => { - action(req, res, next, methods[method], user, connection) + action(req, res, next, routes[route], user, connection) }) ) }) } } +/** + * Add routes. + * + * @returns {Array} routes + */ const generatePrivateRoutes = () => { - fillPrivateRoutes(provisionRoutes, PROVISION, addFunctionToRoute) - fillPrivateRoutes(provisionTemplateRoutes, PROVISION_TEMPLATE, addFunctionToRoute) - fillPrivateRoutes(providerRoutes, PROVIDER, addFunctionToRoute) + setPrivateRoutes(provisionRoutes, PROVISION, addFunctionAsRoute) + setPrivateRoutes(provisionTemplateRoutes, PROVISION_TEMPLATE, addFunctionAsRoute) + setPrivateRoutes(providerRoutes, PROVIDER, addFunctionAsRoute) return privateRoutes } diff --git a/src/fireedge/src/server/routes/api/provision/provider-functions.js b/src/fireedge/src/server/routes/api/provision/provider-functions.js index 745745aec4..b08f79fc0a 100644 --- a/src/fireedge/src/server/routes/api/provision/provider-functions.js +++ b/src/fireedge/src/server/routes/api/provision/provider-functions.js @@ -1,24 +1,26 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { Validator } = require('jsonschema') const { defaultFolderTmpProvision, defaultCommandProvider, defaultHideCredentials, - defaultHideCredentialReplacer + defaultHideCredentialReplacer, + defaultEmptyFunction } = require('server/utils/constants/defaults') const { @@ -31,7 +33,15 @@ const { provider, providerUpdate } = require('./schemas') const httpInternalError = httpResponse(internalServerError, '', '') -const getConnectionProviders = (res = {}, next = () => undefined, params = {}, userData = {}) => { +/** + * Get connection providers. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ +const getConnectionProviders = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError if (user && password) { @@ -63,7 +73,15 @@ const getConnectionProviders = (res = {}, next = () => undefined, params = {}, u next() } -const getListProviders = (res = {}, next = () => undefined, params = {}, userData = {}) => { +/** + * Get list providers. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ +const getListProviders = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError if (user && password) { @@ -77,12 +95,20 @@ const getListProviders = (res = {}, next = () => undefined, params = {}, userDat try { const response = executedCommand.success ? ok : internalServerError const data = JSON.parse(executedCommand.data) + + /** + * Parse provision.TEMPLATE.PLAIN to JSON. + * + * @param {object} provision - provision + * @returns {object} provision with TEMPLATE.PLAIN in JSON + */ const parseTemplatePlain = provision => { if (provision && provision.TEMPLATE && provision.TEMPLATE.PLAIN) { provision.TEMPLATE.PLAIN = JSON.parse(provision.TEMPLATE.PLAIN) } return provision } + if (data && data.DOCUMENT_POOL && data.DOCUMENT_POOL.DOCUMENT && Array.isArray(data.DOCUMENT_POOL.DOCUMENT)) { data.DOCUMENT_POOL.DOCUMENT = data.DOCUMENT_POOL.DOCUMENT.map(parseTemplatePlain) } @@ -119,7 +145,15 @@ const getListProviders = (res = {}, next = () => undefined, params = {}, userDat next() } -const createProviders = (res = {}, next = () => undefined, params = {}, userData = {}) => { +/** + * Create provider. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ +const createProviders = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError if (params && params.resource && user && password) { @@ -164,7 +198,15 @@ const createProviders = (res = {}, next = () => undefined, params = {}, userData next() } -const updateProviders = (res = {}, next = () => undefined, params = {}, userData = {}) => { +/** + * Update provision. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ +const updateProviders = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError if (params && params.resource && params.id && user && password) { @@ -200,7 +242,15 @@ const updateProviders = (res = {}, next = () => undefined, params = {}, userData next() } -const deleteProvider = (res = {}, next = () => undefined, params = {}, userData = {}) => { +/** + * Delete provider. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ +const deleteProvider = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError if (params && params.id && user && password) { diff --git a/src/fireedge/src/server/routes/api/provision/provider.js b/src/fireedge/src/server/routes/api/provision/provider.js index 299c2d4c61..e36efdb213 100644 --- a/src/fireedge/src/server/routes/api/provision/provider.js +++ b/src/fireedge/src/server/routes/api/provision/provider.js @@ -1,19 +1,20 @@ -/* 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, defaultEmptyFunction } = require('server/utils/constants/defaults') -const { getParamsForObject } = require('server/utils/server') +/* ------------------------------------------------------------------------- * + * 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 { getListProviders, getConnectionProviders, diff --git a/src/fireedge/src/server/routes/api/provision/provision-functions.js b/src/fireedge/src/server/routes/api/provision/provision-functions.js index 41fc63731a..46b968285f 100644 --- a/src/fireedge/src/server/routes/api/provision/provision-functions.js +++ b/src/fireedge/src/server/routes/api/provision/provision-functions.js @@ -1,17 +1,18 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { parse } = require('yaml') const { v4 } = require('uuid') @@ -65,7 +66,7 @@ const logFile = { name: 'stdouterr', ext: 'log' } -const configFile = { +const provisionFile = { name: 'provision', ext: 'yaml' } @@ -77,6 +78,14 @@ const relName = 'provision-mapping' const ext = 'yml' const appendError = '.ERROR' +/** + * Execute command Async and emit in WS. + * + * @param {string} command - command to execute + * @param {object} actions - external functions when command emit in stderr, stdout and finalize + * @param {*} dataForLog - data + * @returns {boolean} check if emmit data + */ const executeWithEmit = (command = [], actions = {}, dataForLog = {}) => { let rtn = false if ( @@ -99,12 +108,23 @@ const executeWithEmit = (command = [], actions = {}, dataForLog = {}) => { let pendingMessages = '' - // send data of command + /** + * Emit data of command. + * + * @param {string} message - line of command CLI + * @param {Function} callback - function when recieve a information + */ const emit = (message, callback = defaultEmptyFunction) => { + /** + * Publisher data to WS. + * + * @param {string} line - command CLI line + */ const publisher = (line = '') => { const resposeData = callback(line, uuid) || { id, data: line, command: commandName, commandId: uuid } publish(defaultCommandProvision, resposeData) } + message.toString().split(regexpSplitLine).map(line => { if (line) { if ( @@ -147,6 +167,13 @@ const executeWithEmit = (command = [], actions = {}, dataForLog = {}) => { return rtn } +/** + * Find log data. + * + * @param {string} id - id of provision + * @param {boolean} fullPath - if need return the path of log + * @returns {object} data of log + */ const logData = (id, fullPath = false) => { let rtn = false if (typeof id !== 'undefined') { @@ -154,9 +181,20 @@ const logData = (id, fullPath = false) => { const relFile = `${basePath}/${relName}` const relFileYML = `${relFile}.${ext}` const find = findRecursiveFolder(basePath, id) + + /** + * Not found log. + */ const rtnNotFound = () => { rtn = false } + + /** + * Found log. + * + * @param {string} path - path of log + * @param {string} uuid - uuid of log + */ const rtnFound = (path = '', uuid) => { if (path) { const stringPath = `${path}/${logFile.name}.${logFile.ext}` @@ -203,6 +241,14 @@ const logData = (id, fullPath = false) => { return rtn } +/** + * Get default provisions. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const getProvisionDefaults = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const extFiles = 'yml' const { user, password } = userData @@ -217,11 +263,22 @@ const getProvisionDefaults = (res = {}, next = defaultEmptyFunction, params = {} let description = '' let providers = {} let provisions = {} + /** + * Fill description of provision. + * + * @param {string} content - content of description provision + */ const fillDescription = (content = '') => { if (content) { description = content } } + /** + * Fill providers. + * + * @param {string} content - content of provider + * @param {string} name - name of provider + */ const fillProviders = (content = '', name = '') => { if (content && name) { if (!providers[name]) { @@ -233,6 +290,13 @@ const getProvisionDefaults = (res = {}, next = defaultEmptyFunction, params = {} } } } + /** + * Fill provisions. + * + * @param {string} content - content of provision + * @param {string} filePath - path of provision yamls + * @param {string} path - path for command + */ const fillProvisions = (content = '', filePath = '', path = '') => { if (content && filePath && path) { const name = basename(filePath).replace(`.${extFiles}`, '') @@ -307,7 +371,15 @@ const getProvisionDefaults = (res = {}, next = defaultEmptyFunction, params = {} next() } -const getList = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { +/** + * Get list for resource provisions. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ +const getListResourceProvision = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError if (params && params.resource && user && password) { @@ -327,6 +399,14 @@ const getList = (res = {}, next = defaultEmptyFunction, params = {}, userData = next() } +/** + * Get list provisions. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const getListProvisions = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError @@ -360,6 +440,14 @@ const getListProvisions = (res = {}, next = defaultEmptyFunction, params = {}, u next() } +/** + * Delete resource provisions. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const deleteResource = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError @@ -379,6 +467,15 @@ const deleteResource = (res = {}, next = defaultEmptyFunction, params = {}, user next() } +/** + * Delete provision. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + * @param {Function} oneConnection - function xmlrpc + */ const deleteProvision = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}, oneConnection = defaultEmptyFunction) => { const basePath = `${global.CPI}/provision` const relFile = `${basePath}/${relName}` @@ -398,13 +495,23 @@ const deleteProvision = (res = {}, next = defaultEmptyFunction, params = {}, use // create stream for write into file const stream = dataLog && dataLog.fullPath && createWriteStream(dataLog.fullPath, { flags: 'a' }) - // This function is performed for each command line response + /** + * This function is performed for each command line response. + * + * @param {string} lastLine - last line command + * @param {string} uuid - uuid commnand + */ const emit = (lastLine, uuid) => { const renderLine = { id: params.id, data: lastLine, command: command, commandId: uuid } stream && stream.write && stream.write(`${JSON.stringify(renderLine)}\n`) } - // This function is only executed if the command is completed + /** + * This function is only executed if the command is completed. + * + * @param {boolean} success - check in command complete succefully + * @param {string} lastLine - last line command + */ const close = (success, lastLine) => { if (success) { stream && stream.end && stream.end() @@ -463,6 +570,14 @@ const deleteProvision = (res = {}, next = defaultEmptyFunction, params = {}, use next() } +/** + * Execute command of host into provision. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const hostCommand = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError @@ -484,6 +599,14 @@ const hostCommand = (res = {}, next = defaultEmptyFunction, params = {}, userDat next() } +/** + * SSH command of host into provision. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const hostCommandSSH = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError @@ -505,6 +628,15 @@ const hostCommandSSH = (res = {}, next = defaultEmptyFunction, params = {}, user next() } +/** + * Create a provision. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + * @param {Function} oneConnection - function of xmlrpc + */ const createProvision = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}, oneConnection = defaultEmptyFunction) => { const basePath = `${global.CPI}/provision` const relFile = `${basePath}/${relName}` @@ -520,19 +652,39 @@ const createProvision = (res = {}, next = defaultEmptyFunction, params = {}, use const command = 'create' const authCommand = ['--user', user, '--password', password] const endpoint = getEndpoint() - const files = createFolderWithFiles(`${global.CPI}/provision/${id}/tmp`, [{ name: logFile.name, ext: logFile.ext }, { name: configFile.name, ext: configFile.ext, content }]) + const files = createFolderWithFiles(`${global.CPI}/provision/${id}/tmp`, [{ name: logFile.name, ext: logFile.ext }, { name: provisionFile.name, ext: provisionFile.ext, content }]) if (files && files.name && files.files) { + /** + * Find file in created files. + * + * @param {string} val - filename + * @param {string} ext - file extension + * @param {Array} arr - array of files + * @returns {Array} path file + */ const find = (val = '', ext = '', arr = files.files) => arr.find(e => e && e.path && e.ext && e.name && e.name === val && e.ext === ext) - const config = find(configFile.name, configFile.ext) + + const config = find(provisionFile.name, provisionFile.ext) const log = find(logFile.name, logFile.ext) if (config && log) { + /** + * Create provision. + * + * @param {string} filedata - provision data + */ const create = (filedata = '') => { const paramsCommand = [command, config.path, '--batch', '--debug', '--json', ...optionalCommand, ...authCommand, ...endpoint] // stream file log var stream = createWriteStream(log.path, { flags: 'a' }) - // This function is performed for each command line response + /** + * This function is performed for each command line response. + * + * @param {string} lastLine - last line command + * @param {string} uuid - UUID command + * @returns {object} string line of command + */ const emit = (lastLine, uuid) => { if (lastLine && uuid) { if (regexp.test(lastLine) && !checkSync(relFileLOCK)) { @@ -552,7 +704,12 @@ const createProvision = (res = {}, next = defaultEmptyFunction, params = {}, use } } - // This function is only executed if the command is completed + /** + * This function is only executed if the command is completed. + * + * @param {boolean} success - check if command finish successfully + * @param {string} lastLine - last line command finish + */ const close = (success, lastLine) => { stream.end() if (success && regexp.test(lastLine)) { @@ -618,6 +775,14 @@ const createProvision = (res = {}, next = defaultEmptyFunction, params = {}, use next() } +/** + * Configure provision. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const configureProvision = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData const rtn = httpInternalError @@ -633,12 +798,23 @@ const configureProvision = (res = {}, next = defaultEmptyFunction, params = {}, // create stream for write into file const stream = dataLog && dataLog.fullPath && createWriteStream(dataLog.fullPath, { flags: 'a' }) - // This function is performed for each command line response + /** + * This function is performed for each command line response. + * + * @param {string} lastLine - last line command + * @param {string} uuid - UUID command + */ const emit = (lastLine, uuid) => { const renderLine = { id: params.id, data: lastLine, command: command, commandId: uuid } stream && stream.write && stream.write(`${JSON.stringify(renderLine)}\n`) } + /** + * This function is only executed if the command is completed. + * + * @param {boolean} success - check if command complete without errors + * @param {string} lastLine - last line command + */ const close = (success, lastLine) => { stream && stream.end && stream.end() } @@ -659,6 +835,14 @@ const configureProvision = (res = {}, next = defaultEmptyFunction, params = {}, next() } +/** + * Configure host provision. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const configureHost = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData const rtn = httpInternalError @@ -674,12 +858,23 @@ const configureHost = (res = {}, next = defaultEmptyFunction, params = {}, userD // create stream for write into file const stream = dataLog && dataLog.fullPath && createWriteStream(dataLog.fullPath, { flags: 'a' }) - // This function is performed for each command line response + /** + * This function is performed for each command line response. + * + * @param {string} lastLine - last line command + * @param {string} uuid - uuid command + */ const emit = (lastLine, uuid) => { const renderLine = { id: params.id, data: lastLine, command: `host ${command}`, commandId: uuid } stream && stream.write && stream.write(`${JSON.stringify(renderLine)}\n`) } + /** + * This function is only executed if the command is completed. + * + * @param {boolean} success - check if command complete without error + * @param {string} lastLine - last line command + */ const close = (success, lastLine) => { stream && stream.end && stream.end() } @@ -700,6 +895,14 @@ const configureHost = (res = {}, next = defaultEmptyFunction, params = {}, userD next() } +/** + * Validate provision file. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const validate = (res = {}, next = defaultEmptyFunction, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError @@ -740,6 +943,13 @@ const validate = (res = {}, next = defaultEmptyFunction, params = {}, userData = next() } +/** + * Get provision log. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + */ const getLogProvisions = (res = {}, next = defaultEmptyFunction, params = {}) => { let rtn = httpInternalError if (params && params.id) { @@ -757,7 +967,7 @@ const getLogProvisions = (res = {}, next = defaultEmptyFunction, params = {}) => const provisionFunctionsApi = { getProvisionDefaults, getLogProvisions, - getList, + getListResourceProvision, getListProvisions, deleteResource, deleteProvision, diff --git a/src/fireedge/src/server/routes/api/provision/provision.js b/src/fireedge/src/server/routes/api/provision/provision.js index 0888d98dd9..44a6d53408 100644 --- a/src/fireedge/src/server/routes/api/provision/provision.js +++ b/src/fireedge/src/server/routes/api/provision/provision.js @@ -1,20 +1,22 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { - getList, + getListResourceProvision, getListProvisions, getLogProvisions, deleteResource, @@ -38,43 +40,43 @@ const routes = { } }, cluster: { - action: getList, + action: getListResourceProvision, params: { resource: { from: fromData.resource, name: 'method' } } }, datastore: { - action: getList, + action: getListResourceProvision, params: { resource: { from: fromData.resource, name: 'method' } } }, host: { - action: getList, + action: getListResourceProvision, params: { resource: { from: fromData.resource, name: 'method' } } }, image: { - action: getList, + action: getListResourceProvision, params: { resource: { from: fromData.resource, name: 'method' } } }, network: { - action: getList, + action: getListResourceProvision, params: { resource: { from: fromData.resource, name: 'method' } } }, template: { - action: getList, + action: getListResourceProvision, params: { resource: { from: fromData.resource, name: 'method' } } }, vntemplate: { - action: getList, + action: getListResourceProvision, params: { resource: { from: fromData.resource, name: 'method' } } diff --git a/src/fireedge/src/server/routes/api/provision/provision_template-functions.js b/src/fireedge/src/server/routes/api/provision/provision_template-functions.js index 4ab9b6b1d2..24984a0a64 100644 --- a/src/fireedge/src/server/routes/api/provision/provision_template-functions.js +++ b/src/fireedge/src/server/routes/api/provision/provision_template-functions.js @@ -1,17 +1,18 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { Validator } = require('jsonschema') const { defaultFolderTmpProvision, defaultCommandProvisionTemplate } = require('server/utils/constants/defaults') @@ -26,6 +27,14 @@ const { provider } = require('./schemas') const httpInternalError = httpResponse(internalServerError, '', '') +/** + * Get provision list template. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const getListProvisionTemplates = (res = {}, next = () => undefined, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError @@ -50,6 +59,14 @@ const getListProvisionTemplates = (res = {}, next = () => undefined, params = {} next() } +/** + * Create provision template. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const createProvisionTemplate = (res = {}, next = () => undefined, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError @@ -89,6 +106,14 @@ const createProvisionTemplate = (res = {}, next = () => undefined, params = {}, next() } +/** + * Instantiate provision template. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const instantiateProvisionTemplate = (res = {}, next = () => undefined, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError @@ -110,6 +135,14 @@ const instantiateProvisionTemplate = (res = {}, next = () => undefined, params = next() } +/** + * Update provision template. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const updateProvisionTemplate = (res = {}, next = () => undefined, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError @@ -149,6 +182,14 @@ const updateProvisionTemplate = (res = {}, next = () => undefined, params = {}, next() } +/** + * Delete provision. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const deleteProvisionTemplate = (res = {}, next = () => undefined, params = {}, userData = {}) => { const { user, password } = userData let rtn = httpInternalError diff --git a/src/fireedge/src/server/routes/api/provision/provision_template.js b/src/fireedge/src/server/routes/api/provision/provision_template.js index b2d46b085e..9c6258734c 100644 --- a/src/fireedge/src/server/routes/api/provision/provision_template.js +++ b/src/fireedge/src/server/routes/api/provision/provision_template.js @@ -1,17 +1,19 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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, diff --git a/src/fireedge/src/server/routes/api/provision/schemas.js b/src/fireedge/src/server/routes/api/provision/schemas.js index 7d2a6310b5..c302e2e528 100644 --- a/src/fireedge/src/server/routes/api/provision/schemas.js +++ b/src/fireedge/src/server/routes/api/provision/schemas.js @@ -1,17 +1,19 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 providers = [ 'aws', 'packet', diff --git a/src/fireedge/src/server/routes/api/provision/string-routes.js b/src/fireedge/src/server/routes/api/provision/string-routes.js index 63a805b673..fa13dd1674 100644 --- a/src/fireedge/src/server/routes/api/provision/string-routes.js +++ b/src/fireedge/src/server/routes/api/provision/string-routes.js @@ -1,17 +1,18 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 PROVIDER = 'provider' const PROVISION = 'provision' diff --git a/src/fireedge/src/server/routes/api/sunstone/index.js b/src/fireedge/src/server/routes/api/sunstone/index.js index adf602c895..6aa2d06e3a 100644 --- a/src/fireedge/src/server/routes/api/sunstone/index.js +++ b/src/fireedge/src/server/routes/api/sunstone/index.js @@ -1,18 +1,20 @@ -/* 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 { addFunctionToRoute, fillFunctionRoute } = require('server/utils/server') +/* ------------------------------------------------------------------------- * + * 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 { addFunctionAsRoute, setFunctionRoute } = require('server/utils/server') const { routes: sunstoneRoutes } = require('./sunstone') const { SUNSTONE } = require('./string-routes') @@ -20,11 +22,18 @@ const { SUNSTONE } = require('./string-routes') const privateRoutes = [] const publicRoutes = [] -const fillPrivateRoutes = (methods = {}, path = '', action = () => undefined) => { +/** + * Set private routes. + * + * @param {object} methods - object of routes + * @param {string} path - principal route + * @param {Function} action - function of route + */ +const setPrivateRoutes = (methods = {}, path = '', action = () => undefined) => { if (Object.keys(methods).length > 0 && methods.constructor === Object) { Object.keys(methods).forEach((method) => { privateRoutes.push( - fillFunctionRoute(method, path, + setFunctionRoute(method, path, (req, res, next, connection, userId, user) => { action(req, res, next, methods[method], user, connection) }) @@ -33,8 +42,13 @@ const fillPrivateRoutes = (methods = {}, path = '', action = () => undefined) => } } +/** + * Add routes. + * + * @returns {Array} routes + */ const generatePrivateRoutes = () => { - fillPrivateRoutes(sunstoneRoutes, SUNSTONE, addFunctionToRoute) + setPrivateRoutes(sunstoneRoutes, SUNSTONE, addFunctionAsRoute) return privateRoutes } diff --git a/src/fireedge/src/server/routes/api/sunstone/string-routes.js b/src/fireedge/src/server/routes/api/sunstone/string-routes.js index d06cdb0659..e393b03bdd 100644 --- a/src/fireedge/src/server/routes/api/sunstone/string-routes.js +++ b/src/fireedge/src/server/routes/api/sunstone/string-routes.js @@ -1,17 +1,18 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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' diff --git a/src/fireedge/src/server/routes/api/sunstone/sunstone-functions.js b/src/fireedge/src/server/routes/api/sunstone/sunstone-functions.js index 61811f28af..e2bbdcff55 100644 --- a/src/fireedge/src/server/routes/api/sunstone/sunstone-functions.js +++ b/src/fireedge/src/server/routes/api/sunstone/sunstone-functions.js @@ -1,17 +1,18 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 { parse } = require('yaml') const { defaultEmptyFunction } = require('server/utils/constants/defaults') @@ -27,15 +28,29 @@ const { const httpInternalError = httpResponse(internalServerError, '', '') -const getInfoZone = (connect = defaultEmptyFunction, idZone, callback = defaultEmptyFunction) => { +/** + * Get information of opennebula group. + * + * @param {Function} connect - xmlrpc function + * @param {string} idGroup - id of group + * @param {Function} callback - run function when have group information + */ +const getInfoGroup = (connect = defaultEmptyFunction, idGroup, callback = defaultEmptyFunction) => { connect( ActionsGroup.GROUP_INFO, - [parseInt(idZone, 10), false], + [parseInt(idGroup, 10), false], callback, false ) } +/** + * Response http request. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} httpCode - object http code + */ const responseHttp = (res = {}, next = defaultEmptyFunction, httpCode) => { if (res && res.locals && res.locals.httpCode && httpCode) { res.locals.httpCode = httpCode @@ -43,6 +58,15 @@ const responseHttp = (res = {}, next = defaultEmptyFunction, httpCode) => { } } +/** + * Get sunstone-server views. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + * @param {Function} oneConnection - xmlrpc function + */ const getViews = (res = {}, next = () => undefined, params = {}, userData = {}, oneConnection = defaultEmptyFunction) => { const { user, password } = userData if (user && password && global && global.SUNSTONE_VIEWS && global.SUNSTONE_PATH) { @@ -52,7 +76,7 @@ const getViews = (res = {}, next = () => undefined, params = {}, userData = {}, [-1, false], (err = {}, userData = {}) => { if (userData && userData.USER && userData.USER.GID) { - getInfoZone( + getInfoGroup( connect, userData.USER.GID, (err = {}, vmgroupData = {}) => { @@ -109,6 +133,14 @@ const getViews = (res = {}, next = () => undefined, params = {}, userData = {}, } } +/** + * Get sunstone-server config. + * + * @param {object} res - http response + * @param {Function} next - express stepper + * @param {object} params - params of http request + * @param {object} userData - user of http request + */ const getConfig = (res = {}, next = () => undefined, params = {}, userData = {}) => { if (global && global.SUNSTONE_CONFIG) { existsFile( diff --git a/src/fireedge/src/server/routes/api/sunstone/sunstone.js b/src/fireedge/src/server/routes/api/sunstone/sunstone.js index 1de3dc4ef4..e5072ed9b1 100644 --- a/src/fireedge/src/server/routes/api/sunstone/sunstone.js +++ b/src/fireedge/src/server/routes/api/sunstone/sunstone.js @@ -1,17 +1,19 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 } = require('server/utils/constants/defaults') const { getConfig, diff --git a/src/fireedge/src/server/routes/api/support/index.js b/src/fireedge/src/server/routes/api/support/index.js index 5029c0df29..1f041f5df1 100644 --- a/src/fireedge/src/server/routes/api/support/index.js +++ b/src/fireedge/src/server/routes/api/support/index.js @@ -1,25 +1,26 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 privateRoutes = []; +const privateRoutes = [] -const publicRoutes = []; +const publicRoutes = [] const functionRoutes = { private: privateRoutes, public: publicRoutes -}; +} -module.exports = functionRoutes; +module.exports = functionRoutes diff --git a/src/fireedge/src/server/routes/api/vcenter/index.js b/src/fireedge/src/server/routes/api/vcenter/index.js index 5029c0df29..1f041f5df1 100644 --- a/src/fireedge/src/server/routes/api/vcenter/index.js +++ b/src/fireedge/src/server/routes/api/vcenter/index.js @@ -1,25 +1,26 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 privateRoutes = []; +const privateRoutes = [] -const publicRoutes = []; +const publicRoutes = [] const functionRoutes = { private: privateRoutes, public: publicRoutes -}; +} -module.exports = functionRoutes; +module.exports = functionRoutes diff --git a/src/fireedge/src/server/routes/api/zendesk/index.js b/src/fireedge/src/server/routes/api/zendesk/index.js index 5029c0df29..1f041f5df1 100644 --- a/src/fireedge/src/server/routes/api/zendesk/index.js +++ b/src/fireedge/src/server/routes/api/zendesk/index.js @@ -1,25 +1,26 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 privateRoutes = []; +const privateRoutes = [] -const publicRoutes = []; +const publicRoutes = [] const functionRoutes = { private: privateRoutes, public: publicRoutes -}; +} -module.exports = functionRoutes; +module.exports = functionRoutes diff --git a/src/fireedge/src/server/routes/entrypoints/404.js b/src/fireedge/src/server/routes/entrypoints/404.js index decaf34297..50c490f7d9 100644 --- a/src/fireedge/src/server/routes/entrypoints/404.js +++ b/src/fireedge/src/server/routes/entrypoints/404.js @@ -1,28 +1,29 @@ -/* 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. */ -/* -------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- * + * 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 express = require('express'); +const express = require('express') -const router = express.Router(); +const router = express.Router() router.get('*', (req, res) => res .status(404) .send( - `