added svcapi ui and camunda code
[it/otf.git] / otf-frontend / server / src / feathers / services / jobs / jobs.hooks.js
diff --git a/otf-frontend/server/src/feathers/services/jobs/jobs.hooks.js b/otf-frontend/server/src/feathers/services/jobs/jobs.hooks.js
new file mode 100644 (file)
index 0000000..f119833
--- /dev/null
@@ -0,0 +1,218 @@
+/*  Copyright (c) 2019 AT&T Intellectual Property.                             #\r
+#                                                                              #\r
+#   Licensed under the Apache License, Version 2.0 (the "License");            #\r
+#   you may not use this file except in compliance with the License.           #\r
+#   You may obtain a copy of the License at                                    #\r
+#                                                                              #\r
+#       http://www.apache.org/licenses/LICENSE-2.0                             #\r
+#                                                                              #\r
+#   Unless required by applicable law or agreed to in writing, software        #\r
+#   distributed under the License is distributed on an "AS IS" BASIS,          #\r
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #\r
+#   See the License for the specific language governing permissions and        #\r
+#   limitations under the License.                                             #\r
+##############################################################################*/\r
+\r
+\r
+const { authenticate } = require('@feathersjs/authentication').hooks;\r
+const { iff, disallow } = require('feathers-hooks-common');\r
+const logger = require('../../../lib/logger');\r
+const request = require('request-promise');\r
+const agendaJobPopulate = require('../../hooks/agendaJobPopulate');\r
+const utils = require('../../../lib/otf-util');\r
+const axios = require('axios');\r
+const util = require('../../../lib/otf-util');\r
+const checkLocks = require('../../hooks/checkLocks');\r
+const { permissions, limitFields } = require('../../hooks/permissions/permissions');\r
+const errors = require('@feathersjs/errors');\r
+\r
+const canExecute = function(){\r
+       return async (context) => {\r
+               let id = context.id || context.data.testInstanceId;\r
+\r
+               let testInstanceId = id;\r
+\r
+               if(context.method == 'remove'){\r
+                       let job = await context.app.services[context.app.get('base-path') + 'jobs'].get(id, {provider: undefined});\r
+                       console.log(job)\r
+                       testInstanceId = job.data.testSchedule._testInstanceId;\r
+                       console.log(testInstanceId)\r
+               }\r
+\r
+               //get group id of the test instance that is being executed\r
+               let testInstance = await context.app.services[context.app.get('base-path') + 'test-instances'].get(testInstanceId, {provider: undefined, query: { $select: ['groupId', 'testDefinitionId', 'disabled'] } });\r
+\r
+               //check if its locked\r
+               let testDefinition = await context.app.services[context.app.get('base-path') + 'test-definitions'].get(testInstance.testDefinitionId, {provider: undefined, query: { $select: ['disabled'] } });\r
+\r
+               if((testInstance.disabled || testDefinition.disabled) && context.method == 'create'){\r
+                       throw new errors.Unavailable('The test instance or definition is locked.');\r
+               }\r
+\r
+               testInstance = new context.app.services[context.app.get('base-path') + 'test-instances'].Model(testInstance);\r
+               if(context.params.ability.cannot('execute', testInstance)){\r
+                       throw new errors.Forbidden(`You are not allowed to execute this instance.`);\r
+               }\r
+       }\r
+}\r
+\r
+module.exports = {\r
+       before: {\r
+               all: [authenticate('jwt')],\r
+               find: [\r
+                       async function(context){\r
+                               if(context.params.query.testInstanceId){\r
+                                       const mongoose = context.app.get('mongooseClient');\r
+                                       const toObjectId = v => mongoose.Types.ObjectId(v);\r
+\r
+                                       let Model = context.app.service(context.app.get('base-path') + 'jobs').Model;\r
+                                       const conditions = [{\r
+                                               $match:{\r
+                                                        "data.testSchedule._testInstanceId": toObjectId(context.params.query.testInstanceId),\r
+                                                        "nextRunAt":  {\r
+                                                                $ne: null\r
+                                                        }//{\r
+                                                       //      "testSchedule": {\r
+                                                       //              "_testInstanceId": toObjectId(context.params.query.testInstanceId)\r
+                                                       //      }\r
+                                                       // }\r
+                                               }\r
+                                       }];\r
+\r
+                                       await new Promise(function(resolve, reject){\r
+                                               Model.aggregate(conditions).exec(function(error, result){\r
+                                                       if(error){\r
+                                                               reject(error);\r
+                                                       }\r
+                                                       resolve(result);\r
+                                               });\r
+                                       }).then(result => {\r
+                                               if(result.length){\r
+                                                       if(result.length == 1){\r
+                                                               context.params.query._id = result[0]._id;\r
+                                                       }else if(result.length == 0){\r
+                                                               //do nothing\r
+                                                       }else{\r
+                                                               let ids = [];\r
+                                                               result.forEach(elem => {\r
+                                                                       ids.push(elem._id);\r
+                                                               });\r
+                                                               context.params.query._id = {\r
+                                                                       $in: ids\r
+                                                               }\r
+                                                       }\r
+                                               }else{\r
+                                                       context.params.query._id = result._id;\r
+                                               }\r
+                                       }).catch(err => {\r
+                                               console.log(err);\r
+                                       });\r
+\r
+                                       delete context.params.query.testInstanceId;\r
+                               }\r
+                               return context;\r
+                       }\r
+               ],\r
+               get: [],\r
+               create: [\r
+                       permissions('jobs'),\r
+                       (context) => { console.log("AFTER PERMISSIONS")},\r
+                       canExecute(), \r
+                       async (context) => {\r
+                               const fullUrl = 'https://localhost/' + context.app.get('base-path') + 'schedule-test';\r
+\r
+                               context.data.executorId = context.params.user._id;\r
+\r
+                               await request({\r
+                                       method: 'post',\r
+                                       url: fullUrl,\r
+                                       body: JSON.stringify(context.data),\r
+                                       headers: {\r
+                                               'Content-Type': 'application/json',\r
+                                               'Authorization': 'Basic ' +\r
+                                                       util.base64Encode(\r
+                                                               context.app.get('serviceApi').aafId + ':' +\r
+                                                               context.app.get('serviceApi').aafPassword)\r
+                                       },\r
+                                       rejectUnauthorized: false\r
+                               }, function (err, res, body) {\r
+                                       if (err) {\r
+                                               logger.error(err);\r
+                                       }\r
+\r
+                                       if (body) {\r
+                                               context.result = JSON.parse(body);\r
+                                       }\r
+\r
+                               });\r
+\r
+                               return context;\r
+                       }\r
+               ],\r
+               update: [],\r
+               patch: [],\r
+               remove: [\r
+                       permissions('jobs'),\r
+                       canExecute(),\r
+                       async function (context) {\r
+                       const fullUrl = 'https://localhost/' + context.app.get('base-path') + 'cancel-test';\r
+\r
+                       if (context.id == null || context.params.user._id == null ||\r
+                               utils.isValidObjectId(context.id) || utils.isValidObjectId(context.params.user._id)) {\r
+                               context.result = {\r
+                                       status: 400,\r
+                                       message: 'Request is invalid.'\r
+                               };\r
+                       }\r
+\r
+                       const postData = {\r
+                               jobId: context.id,\r
+                               executorId: context.params.user._id\r
+                       };\r
+\r
+                       // console.log(JSON.stringify(postData));\r
+\r
+                       await request({\r
+                               method: 'post',\r
+                               url: fullUrl,\r
+                               body: JSON.stringify(postData),\r
+                               headers: {\r
+                                       'Content-Type': 'application/json',\r
+                                       'Authorization': 'Basic ' +\r
+                                               util.base64Encode(\r
+                                                       context.app.get('serviceApi').aafId + ':' +\r
+                                                       context.app.get('serviceApi').aafPassword)\r
+                               },\r
+                               rejectUnauthorized: false\r
+                       }, function (err, res, body) {\r
+                               if (err) {\r
+                                       logger.error(err);\r
+                               }\r
+\r
+                               context.result = JSON.parse(body);\r
+                       });\r
+\r
+                       return context;\r
+               }]\r
+       },\r
+\r
+       after: {\r
+               all: [],\r
+               find: [agendaJobPopulate()],\r
+               get: [agendaJobPopulate()],\r
+               create: [],\r
+               update: [],\r
+               patch: [],\r
+               remove: []\r
+       },\r
+\r
+       error: {\r
+               all: [],\r
+               find: [],\r
+               get: [],\r
+               create: [],\r
+               update: [],\r
+               patch: [],\r
+               remove: []\r
+       }\r
+};\r