added svcapi ui and camunda code
[it/otf.git] / otf-frontend / server / src / feathers / services / jobs / jobs.hooks.js
1 /*  Copyright (c) 2019 AT&T Intellectual Property.                             #\r
2 #                                                                              #\r
3 #   Licensed under the Apache License, Version 2.0 (the "License");            #\r
4 #   you may not use this file except in compliance with the License.           #\r
5 #   You may obtain a copy of the License at                                    #\r
6 #                                                                              #\r
7 #       http://www.apache.org/licenses/LICENSE-2.0                             #\r
8 #                                                                              #\r
9 #   Unless required by applicable law or agreed to in writing, software        #\r
10 #   distributed under the License is distributed on an "AS IS" BASIS,          #\r
11 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #\r
12 #   See the License for the specific language governing permissions and        #\r
13 #   limitations under the License.                                             #\r
14 ##############################################################################*/\r
15 \r
16 \r
17 const { authenticate } = require('@feathersjs/authentication').hooks;\r
18 const { iff, disallow } = require('feathers-hooks-common');\r
19 const logger = require('../../../lib/logger');\r
20 const request = require('request-promise');\r
21 const agendaJobPopulate = require('../../hooks/agendaJobPopulate');\r
22 const utils = require('../../../lib/otf-util');\r
23 const axios = require('axios');\r
24 const util = require('../../../lib/otf-util');\r
25 const checkLocks = require('../../hooks/checkLocks');\r
26 const { permissions, limitFields } = require('../../hooks/permissions/permissions');\r
27 const errors = require('@feathersjs/errors');\r
28 \r
29 const canExecute = function(){\r
30         return async (context) => {\r
31                 let id = context.id || context.data.testInstanceId;\r
32 \r
33                 let testInstanceId = id;\r
34 \r
35                 if(context.method == 'remove'){\r
36                         let job = await context.app.services[context.app.get('base-path') + 'jobs'].get(id, {provider: undefined});\r
37                         console.log(job)\r
38                         testInstanceId = job.data.testSchedule._testInstanceId;\r
39                         console.log(testInstanceId)\r
40                 }\r
41 \r
42                 //get group id of the test instance that is being executed\r
43                 let testInstance = await context.app.services[context.app.get('base-path') + 'test-instances'].get(testInstanceId, {provider: undefined, query: { $select: ['groupId', 'testDefinitionId', 'disabled'] } });\r
44 \r
45                 //check if its locked\r
46                 let testDefinition = await context.app.services[context.app.get('base-path') + 'test-definitions'].get(testInstance.testDefinitionId, {provider: undefined, query: { $select: ['disabled'] } });\r
47 \r
48                 if((testInstance.disabled || testDefinition.disabled) && context.method == 'create'){\r
49                         throw new errors.Unavailable('The test instance or definition is locked.');\r
50                 }\r
51 \r
52                 testInstance = new context.app.services[context.app.get('base-path') + 'test-instances'].Model(testInstance);\r
53                 if(context.params.ability.cannot('execute', testInstance)){\r
54                         throw new errors.Forbidden(`You are not allowed to execute this instance.`);\r
55                 }\r
56         }\r
57 }\r
58 \r
59 module.exports = {\r
60         before: {\r
61                 all: [authenticate('jwt')],\r
62                 find: [\r
63                         async function(context){\r
64                                 if(context.params.query.testInstanceId){\r
65                                         const mongoose = context.app.get('mongooseClient');\r
66                                         const toObjectId = v => mongoose.Types.ObjectId(v);\r
67 \r
68                                         let Model = context.app.service(context.app.get('base-path') + 'jobs').Model;\r
69                                         const conditions = [{\r
70                                                 $match:{\r
71                                                          "data.testSchedule._testInstanceId": toObjectId(context.params.query.testInstanceId),\r
72                                                          "nextRunAt":  {\r
73                                                                  $ne: null\r
74                                                          }//{\r
75                                                         //      "testSchedule": {\r
76                                                         //              "_testInstanceId": toObjectId(context.params.query.testInstanceId)\r
77                                                         //      }\r
78                                                         // }\r
79                                                 }\r
80                                         }];\r
81 \r
82                                         await new Promise(function(resolve, reject){\r
83                                                 Model.aggregate(conditions).exec(function(error, result){\r
84                                                         if(error){\r
85                                                                 reject(error);\r
86                                                         }\r
87                                                         resolve(result);\r
88                                                 });\r
89                                         }).then(result => {\r
90                                                 if(result.length){\r
91                                                         if(result.length == 1){\r
92                                                                 context.params.query._id = result[0]._id;\r
93                                                         }else if(result.length == 0){\r
94                                                                 //do nothing\r
95                                                         }else{\r
96                                                                 let ids = [];\r
97                                                                 result.forEach(elem => {\r
98                                                                         ids.push(elem._id);\r
99                                                                 });\r
100                                                                 context.params.query._id = {\r
101                                                                         $in: ids\r
102                                                                 }\r
103                                                         }\r
104                                                 }else{\r
105                                                         context.params.query._id = result._id;\r
106                                                 }\r
107                                         }).catch(err => {\r
108                                                 console.log(err);\r
109                                         });\r
110 \r
111                                         delete context.params.query.testInstanceId;\r
112                                 }\r
113                                 return context;\r
114                         }\r
115                 ],\r
116                 get: [],\r
117                 create: [\r
118                         permissions('jobs'),\r
119                         (context) => { console.log("AFTER PERMISSIONS")},\r
120                         canExecute(), \r
121                         async (context) => {\r
122                                 const fullUrl = 'https://localhost/' + context.app.get('base-path') + 'schedule-test';\r
123 \r
124                                 context.data.executorId = context.params.user._id;\r
125 \r
126                                 await request({\r
127                                         method: 'post',\r
128                                         url: fullUrl,\r
129                                         body: JSON.stringify(context.data),\r
130                                         headers: {\r
131                                                 'Content-Type': 'application/json',\r
132                                                 'Authorization': 'Basic ' +\r
133                                                         util.base64Encode(\r
134                                                                 context.app.get('serviceApi').aafId + ':' +\r
135                                                                 context.app.get('serviceApi').aafPassword)\r
136                                         },\r
137                                         rejectUnauthorized: false\r
138                                 }, function (err, res, body) {\r
139                                         if (err) {\r
140                                                 logger.error(err);\r
141                                         }\r
142 \r
143                                         if (body) {\r
144                                                 context.result = JSON.parse(body);\r
145                                         }\r
146 \r
147                                 });\r
148 \r
149                                 return context;\r
150                         }\r
151                 ],\r
152                 update: [],\r
153                 patch: [],\r
154                 remove: [\r
155                         permissions('jobs'),\r
156                         canExecute(),\r
157                         async function (context) {\r
158                         const fullUrl = 'https://localhost/' + context.app.get('base-path') + 'cancel-test';\r
159 \r
160                         if (context.id == null || context.params.user._id == null ||\r
161                                 utils.isValidObjectId(context.id) || utils.isValidObjectId(context.params.user._id)) {\r
162                                 context.result = {\r
163                                         status: 400,\r
164                                         message: 'Request is invalid.'\r
165                                 };\r
166                         }\r
167 \r
168                         const postData = {\r
169                                 jobId: context.id,\r
170                                 executorId: context.params.user._id\r
171                         };\r
172 \r
173                         // console.log(JSON.stringify(postData));\r
174 \r
175                         await request({\r
176                                 method: 'post',\r
177                                 url: fullUrl,\r
178                                 body: JSON.stringify(postData),\r
179                                 headers: {\r
180                                         'Content-Type': 'application/json',\r
181                                         'Authorization': 'Basic ' +\r
182                                                 util.base64Encode(\r
183                                                         context.app.get('serviceApi').aafId + ':' +\r
184                                                         context.app.get('serviceApi').aafPassword)\r
185                                 },\r
186                                 rejectUnauthorized: false\r
187                         }, function (err, res, body) {\r
188                                 if (err) {\r
189                                         logger.error(err);\r
190                                 }\r
191 \r
192                                 context.result = JSON.parse(body);\r
193                         });\r
194 \r
195                         return context;\r
196                 }]\r
197         },\r
198 \r
199         after: {\r
200                 all: [],\r
201                 find: [agendaJobPopulate()],\r
202                 get: [agendaJobPopulate()],\r
203                 create: [],\r
204                 update: [],\r
205                 patch: [],\r
206                 remove: []\r
207         },\r
208 \r
209         error: {\r
210                 all: [],\r
211                 find: [],\r
212                 get: [],\r
213                 create: [],\r
214                 update: [],\r
215                 patch: [],\r
216                 remove: []\r
217         }\r
218 };\r