-
Notifications
You must be signed in to change notification settings - Fork 261
/
init-aps-env.ts
executable file
·435 lines (397 loc) · 14.4 KB
/
init-aps-env.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
const alfrescoApi = require('@alfresco/js-api');
const program = require('commander');
const fs = require ('fs');
const path = require('path');
import { logger } from './logger';
const { throwError } = require('rxjs');
// eslint-disable-next-line @typescript-eslint/naming-convention
const { AppDefinitionsApi, RuntimeAppDefinitionsApi } = require('@alfresco/js-api');
const MAX_RETRY = 10;
let counter = 0;
const TIMEOUT = 6000;
const TENANT_DEFAULT_ID = 1;
const TENANT_DEFAULT_NAME = 'default';
const CONTENT_DEFAULT_NAME = 'adw-content';
const ACTIVITI_APPS = require('./resources').ACTIVITI_APPS;
let alfrescoJsApi;
let alfrescoJsApiRepo;
export default async function() {
await main();
}
async function main() {
program
.version('0.1.0')
.option('--host [type]', 'Remote environment host')
.option('-p, --password [type]', 'password ')
.option('-u, --username [type]', 'username ')
.option('--license [type]', 'APS license S3 path ')
.parse(process.argv);
await checkEnv();
logger.info(`***** Step 1 - Check License *****`);
let licenceUploaded = false;
const hasValidLicense = await hasLicense() ;
if (!hasValidLicense) {
logger.info(`Aps License missing`);
const isLicenseFileDownloaded = await downloadLicenseFile(program.license);
if (isLicenseFileDownloaded) {
licenceUploaded = await updateLicense();
}
} else {
licenceUploaded = true;
logger.info(`Aps License present`);
}
let tenantId;
if (licenceUploaded) {
logger.info(`***** Step 2 - Check Tenant *****`);
logger.info(`is tenandId:${TENANT_DEFAULT_ID} with name:${TENANT_DEFAULT_NAME} present?`);
try {
const hasDefault = await hasDefaultTenant(TENANT_DEFAULT_ID, TENANT_DEFAULT_NAME);
tenantId = TENANT_DEFAULT_ID;
if (!hasDefault) {
// the tenandId should be equal to TENANT_DEFAULT_ID if we choose 1 as id.
tenantId = await createDefaultTenant(TENANT_DEFAULT_NAME);
}
logger.info(`***** Step 3 - Add Content Repo *****`);
const isContentPresent = await isContenRepoPresent(TENANT_DEFAULT_ID, CONTENT_DEFAULT_NAME);
if (!isContentPresent) {
logger.info(`No content repo with name ${CONTENT_DEFAULT_NAME} found`);
await addContentRepoWithBasic(TENANT_DEFAULT_ID, CONTENT_DEFAULT_NAME);
}
logger.info(`***** Step 4 - Create users *****`);
const users = await getUserFromRealm();
if (tenantId && users && users.length > 0) {
for (let i = 0; i < users.length; i++) {
await createUsers(tenantId, users[i]);
}
for (let i = 0; i < users.length; i++) {
logger.info('Impersonate user: ' + users[i].username);
await alfrescoJsApiRepo.login(users[i].username, 'password');
await authorizeUserToContentRepo(users[i]);
const defaultUser = 'hruser';
if (users[i].username.includes(defaultUser)) {
logger.info(`***** Step initialize APS apps for user ${defaultUser} *****`);
await initializeDefaultApps();
}
}
} else {
logger.info('Something went wrong. Was not able to create the users');
}
} catch (error) {
logger.info(`Aps something went wrong. Tenant id ${tenantId}`);
}
} else {
logger.info('APS license error: check the configuration');
}
}
async function initializeDefaultApps() {
for (let x = 0; x < ACTIVITI_APPS.apps.length; x++) {
const appInfo = ACTIVITI_APPS.apps[x];
const isDefaultAppDepl = await isDefaultAppDeployed(appInfo.name);
if (isDefaultAppDepl !== undefined && !isDefaultAppDepl) {
const appDefinition = await importPublishApp(`${appInfo.name}`);
await deployApp(appDefinition.appDefinition.id);
} else {
logger.info(`***** App ${appInfo.name} already deployed *****`);
}
}
}
async function checkEnv() {
try {
alfrescoJsApi = new alfrescoApi.AlfrescoApiCompatibility({
provider: 'ALL',
hostBpm: program.host,
hostEcm: program.host,
authType: 'OAUTH',
oauth2: {
host: `${program.host}/auth/realms/alfresco`,
clientId: 'alfresco',
scope: 'openid'
}
});
alfrescoJsApiRepo = alfrescoJsApi;
await alfrescoJsApi.login(program.username, program.password);
} catch (e) {
if (e.error.code === 'ETIMEDOUT') {
logger.error('The env is not reachable. Terminating');
process.exit(1);
}
logger.info('Login error environment down or inaccessible');
counter++;
if (MAX_RETRY === counter) {
logger.error('Give up');
process.exit(1);
} else {
logger.error(`Retry in 1 minute attempt N ${counter}`);
sleep(TIMEOUT);
checkEnv();
}
}
}
async function hasDefaultTenant(tenantId, tenantName) {
let tenant;
try {
tenant = await alfrescoJsApi.activiti.adminTenantsApi.getTenant(tenantId);
} catch (error) {
logger.info(`Aps: does not have tenant with id: ${tenantId}`);
return false;
}
if (tenant.name === tenantName) {
logger.info(`Aps: has default tenantId: ${tenantId} and name ${tenantName}`);
return true;
} else {
logger.info(`Wrong configuration. Another tenant has been created with id ${tenant.id} and name ${tenant.name}`);
throwError(`Wrong configuration. Another tenant has been created with id ${tenant.id} and name ${tenant.name}`);
}
}
async function createDefaultTenant(tenantName) {
const tenantPost = {
active: true,
maxUsers: 10000,
name : tenantName
};
try {
const tenant = await alfrescoJsApi.activiti.adminTenantsApi.createTenant(tenantPost);
logger.info(`APS: Tenant ${tenantName} created with id: ${tenant.id}`);
return tenant.id;
} catch (error) {
logger.info(`APS: not able to create the default tenant: ${JSON.parse(error.message)}` );
}
}
async function createUsers(tenandId, user) {
logger.info(`Create user ${user.email} on tenant: ${tenandId}`);
const passwordCamelCase = 'Password';
const userJson = {
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
status: 'active',
type: 'enterprise',
password: passwordCamelCase,
tenantId: tenandId
};
try {
const userInfo = await alfrescoJsApi.activiti.adminUsersApi.createNewUser(userJson);
logger.info(`APS: User ${userInfo.email} created with id: ${userInfo.id}`);
return user;
} catch (error) {
logger.info(`APS: not able to create the default user: ${error.message}` );
}
}
async function updateLicense() {
const fileContent = fs.createReadStream(path.join(__dirname, '/activiti.lic'));
try {
await alfrescoJsApi.oauth2Auth.callCustomApi(
`${program.host}/activiti-app/app/rest/license`,
'POST',
{},
{},
{},
{ file: fileContent },
{},
['multipart/form-data'],
['application/json']
);
logger.info(`Aps License uploaded!`);
return true;
} catch (error) {
logger.error(`Aps License failed!` );
return false;
}
}
async function isDefaultAppDeployed(appName: string) {
logger.info(`Verify ${appName} already deployed`);
try {
const runtimeAppDefinitionsApi = new RuntimeAppDefinitionsApi(alfrescoJsApiRepo);
const availableApps = await runtimeAppDefinitionsApi.getAppDefinitions();
const defaultApp = availableApps.data && availableApps.data.filter( app => app.name && app.name.includes(appName));
return defaultApp && defaultApp.length > 0;
} catch (error) {
logger.error(`Aps app failed to import/Publish!`);
}
}
async function importPublishApp(appName: string) {
const appNameExtension = `../resources/${appName}.zip`;
logger.info(`Import app ${appNameExtension}`);
const pathFile = path.join(__dirname, appNameExtension);
const fileContent = fs.createReadStream(pathFile);
try {
const appdefinitionsApi = new AppDefinitionsApi(alfrescoJsApiRepo);
const result = await appdefinitionsApi.importAndPublishApp(fileContent, {renewIdmEntries: true});
logger.info(`Aps app imported and published!`);
return result;
} catch (error) {
logger.error(`Aps app failed to import/Publish!`, error.message);
}
}
async function deployApp(appDefinitioId) {
logger.info(`Deploy app with id ${appDefinitioId}`);
const body = {
appDefinitions: [{id: appDefinitioId}]
};
try {
const runtimeAppDefinitionsApi = new RuntimeAppDefinitionsApi(alfrescoJsApiRepo);
await runtimeAppDefinitionsApi.deployAppDefinitions(body);
logger.info(`Aps app deployed`);
} catch (error) {
logger.error(`Aps app failed to deploy!`);
}
}
async function hasLicense() {
try {
const license = await alfrescoJsApi.oauth2Auth.callCustomApi(
`${program.host}/activiti-app/app/rest/license`,
'GET',
{},
{},
{},
{},
{},
['application/json'],
['application/json']
);
if (license && license.status === 'valid') {
logger.info(`Aps has a valid License!`);
return true;
}
logger.info(`Aps does NOT have a valid License!`);
return false;
} catch (error) {
logger.error(`Aps not able to check the license` );
}
}
async function getUserFromRealm() {
try {
const users = await alfrescoJsApi.oauth2Auth.callCustomApi(
`${program.host}/auth/admin/realms/alfresco/users`,
'GET',
{},
{},
{},
{},
{},
['application/json'],
['application/json']
);
const usersExample = users.filter(user => user.email.includes('@example.com'));
const usersWithoutAdmin = usersExample.filter(user => (user.username !== program.username && user.username !== 'client'));
logger.info(`Keycloak found ${usersWithoutAdmin.length} users`);
return usersWithoutAdmin;
} catch (error) {
logger.error(`APS: not able to fetch user: ${error.message}` );
}
}
async function isContenRepoPresent(tenantId, contentName) {
try {
const contentRepos = await alfrescoJsApi.oauth2Auth.callCustomApi(
`${program.host}/activiti-app/app/rest/integration/alfresco?tenantId=${tenantId}`,
'GET',
{},
{},
{},
{},
{},
['application/json'],
['application/json']
);
return !!contentRepos.data.find(repo => repo.name === contentName);
} catch (error) {
logger.error(`APS: not able to create content: ${error.message}` );
}
}
async function addContentRepoWithBasic(tenantId, name) {
logger.info(`Create Content with name ${name} and basic auth`);
const body = {
alfrescoTenantId: '',
authenticationType: 'basic',
name,
repositoryUrl: `${program.host}/alfresco`,
shareUrl: `${program.host}/share`,
// sitesFolder: '', not working on activiti 1.11.1.1
tenantId,
version: '6.1.1'
};
try {
const content = await alfrescoJsApi.oauth2Auth.callCustomApi(
`${program.host}/activiti-app/app/rest/integration/alfresco`,
'POST',
{},
{},
{},
{},
body,
['application/json'],
['application/json']
);
logger.info(`Content created!`);
return content;
} catch (error) {
logger.error(`APS: not able to create content: ${error.message}` );
}
}
async function authorizeUserToContentRepo(user) {
logger.info(`Authorize user ${user.email}`);
try {
const content = await alfrescoJsApiRepo.oauth2Auth.callCustomApi(
`${program.host}/activiti-app/app/rest/integration/alfresco`,
'GET',
{},
{},
{},
{},
{},
['application/json'],
['application/json']
);
logger.info(`Found ${content.data && content.data.length} contents`);
if (content.data) {
for (let i = 0; i < content.data.length; i++) {
if (content.data[i].authenticationType === 'basic') {
await authorizeUserToContentWithBasic(user.username, content.data[i].id);
}
}
}
return;
} catch (error) {
logger.error(`APS: not able to authorize content: ${error.message}` );
}
}
async function authorizeUserToContentWithBasic(username, contentId) {
logger.info(`Authorize ${username} on contentId: ${contentId} in basic auth`);
try {
const body = {username, password: 'password'};
const content = await alfrescoJsApiRepo.oauth2Auth.callCustomApi(
`${program.host}/activiti-app/app/rest/integration/alfresco/${contentId}/account`,
'POST',
{},
{},
{},
{},
body,
['application/json'],
['application/json']
);
logger.info(`User authorized!`);
return content;
} catch (error) {
logger.error(`APS: not able to authorize content: ${error.message}` );
}
}
/* eslint-disable */
async function downloadLicenseFile(apsLicensePath) {
try {
const child_process = require("child_process");
child_process.execSync(` aws s3 cp ${apsLicensePath} ./ `, {
cwd: path.resolve(__dirname, `./`)
});
logger.info(`Aps license file download from S3 bucket`);
return true;
} catch (error) {
logger.error(`Not able to download the APS license from S3 bucket` );
return false;
}
}
/* eslint-enable */
function sleep(delay) {
const start = new Date().getTime();
while (new Date().getTime() < start + delay) { }
}