-
Notifications
You must be signed in to change notification settings - Fork 36
/
User.js
1203 lines (1159 loc) · 47.9 KB
/
User.js
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
import MetadataType from './MetadataType.js';
import { Util } from '../util/util.js';
import File from '../util/file.js';
import cache from '../util/cache.js';
/**
* @typedef {import('../../types/mcdev.d.js').BuObject} BuObject
* @typedef {import('../../types/mcdev.d.js').CodeExtract} CodeExtract
* @typedef {import('../../types/mcdev.d.js').CodeExtractItem} CodeExtractItem
* @typedef {import('../../types/mcdev.d.js').MetadataTypeItem} MetadataTypeItem
* @typedef {import('../../types/mcdev.d.js').MetadataTypeItemDiff} MetadataTypeItemDiff
* @typedef {import('../../types/mcdev.d.js').MetadataTypeItemObj} MetadataTypeItemObj
* @typedef {import('../../types/mcdev.d.js').MetadataTypeMap} MetadataTypeMap
* @typedef {import('../../types/mcdev.d.js').MetadataTypeMapObj} MetadataTypeMapObj
* @typedef {import('../../types/mcdev.d.js').SoapRequestParams} SoapRequestParams
* @typedef {import('../../types/mcdev.d.js').TemplateMap} TemplateMap
*/
/**
* @typedef {import('../../types/mcdev.d.js').UserDocument} UserDocument
* @typedef {import('../../types/mcdev.d.js').UserDocumentDocument} UserDocumentDocument
* @typedef {import('../../types/mcdev.d.js').UserDocumentDiff} UserDocumentDiff
* @typedef {import('../../types/mcdev.d.js').UserDocumentMap} UserDocumentMap
* @typedef {import('../../types/mcdev.d.js').AccountUserConfiguration} AccountUserConfiguration
*/
/**
* MetadataType
*
* @augments MetadataType
*/
class User extends MetadataType {
static userBUassignments;
/**
* Retrieves SOAP based metadata of metadata type into local filesystem. executes callback with retrieved metadata
*
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {void | string[]} _ unused parameter
* @param {void | string[]} [__] unused parameter
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<MetadataTypeMapObj>} Promise of metadata
*/
static async retrieve(retrieveDir, _, __, key) {
if (this.buObject.eid !== this.buObject.mid) {
Util.logger.info(' - Skipping User retrieval on non-parent BU');
return;
}
return this._retrieve(retrieveDir, key);
}
/**
* Retrieves import definition metadata for caching
*
* @returns {Promise.<MetadataTypeMapObj>} Promise
*/
static async retrieveForCache() {
return this.retrieve(null);
}
/**
* Create a single item.
*
* @param {MetadataTypeItem} metadata single metadata entry
* @returns {Promise} Promise
*/
static async create(metadata) {
if (this.buObject.eid !== this.buObject.mid) {
Util.logger.info(' - Skipping User creation on non-parent BU');
return;
}
return super.createSOAP(metadata);
}
/**
* Updates a single item.
*
* @param {MetadataTypeItem} metadata single metadata entry
* @returns {Promise} Promise
*/
static async update(metadata) {
if (this.buObject.eid !== this.buObject.mid) {
Util.logger.info(' - Skipping User update on non-parent BU');
return;
}
return super.updateSOAP(metadata);
}
/**
* prepares a item for deployment
*
* @param {UserDocument} metadata of a single item
* @returns {Promise.<UserDocument>} metadata object
*/
static async preDeployTasks(metadata) {
metadata.Client = {
ID: this.buObject.mid,
};
// convert roles into API compliant format
if (metadata.c__RoleNamesGlobal?.length) {
metadata.Roles = {
Role: metadata.c__RoleNamesGlobal
.filter(
// individual role (which are not manageable nor visible in the GUI)
(roleName) => !roleName.startsWith('Individual role for ')
)
.map((roleName) => {
let roleCache;
try {
const roleKey = cache.searchForField(
'role',
roleName,
'Name',
'CustomerKey'
);
roleCache = cache.getByKey('role', roleKey + '');
} catch {
// skip this role in case of errors
return;
}
if (roleCache?.c__notAssignable) {
throw new Error(
`Default roles starting on 'Marketing Cloud' are not assignable via API and get removed upon update. Please create/update the user manually in the GUI or remove that role.`
);
}
return {
ObjectID: roleCache.ObjectID,
Name: roleName,
};
})
.filter(Boolean),
};
}
delete metadata.c__RoleNamesGlobal;
// check if DefaultBusinessUnit is listed in AssociatedBUs
if (!metadata.c__AssociatedBusinessUnits.includes(metadata.DefaultBusinessUnit)) {
metadata.c__AssociatedBusinessUnits.push(metadata.DefaultBusinessUnit);
Util.logger.info(
Util.getGrayMsg(
` - adding DefaultBusinessUnit to list of associated Business Units (${metadata.CustomerKey} / ${metadata.Name}): ${metadata.DefaultBusinessUnit}`
)
);
}
if (metadata.c__AssociatedBusinessUnits.length) {
// ensure we do not have duplicates in the list - could happen due to user error or due to templating
metadata.c__AssociatedBusinessUnits = [...new Set(metadata.c__AssociatedBusinessUnits)];
}
// Timezone
if (metadata.c__TimeZoneName) {
// find the ID of the timezone
metadata.TimeZone = { Name: metadata.c__TimeZoneName };
metadata.TimeZone.ID =
'' +
cache.searchForField('_timezone', metadata.c__TimeZoneName, 'description', 'id');
delete metadata.c__TimeZoneName;
}
// Locale
if (metadata.c__LocaleCode) {
// we cannot easily confirm if hte code is valid but SFMC's API will likely throw an error if not
metadata.Locale = { LocaleCode: metadata.c__LocaleCode };
delete metadata.c__LocaleCode;
}
// convert SSO / Federation Token into API compliant format
if (metadata.SsoIdentity || metadata.SsoIdentities) {
const ssoIdentity = {};
let error = false;
if (metadata.SsoIdentity) {
// assume metadata.SsoIdentity is an object
ssoIdentity.IsActive = metadata.SsoIdentity.IsActive;
ssoIdentity.FederatedID = metadata.SsoIdentity.FederatedID;
delete metadata.SsoIdentity;
} else if (Array.isArray(metadata.SsoIdentities)) {
// be nice and allow SsoIdentities as an alternative if its an array of objects
ssoIdentity.IsActive = metadata.SsoIdentities[0].IsActive;
ssoIdentity.FederatedID = metadata.SsoIdentities[0].FederatedID;
} else if (
Array.isArray(metadata.SsoIdentities?.SsoIdentity) &&
metadata.SsoIdentities?.SsoIdentity.length
) {
// API-compliant format already provided; just use it
ssoIdentity.IsActive = metadata.SsoIdentities.SsoIdentity[0]?.IsActive;
ssoIdentity.FederatedID = metadata.SsoIdentities.SsoIdentity[0]?.FederatedID;
} else {
error = true;
}
if (
(ssoIdentity.IsActive !== true && ssoIdentity.IsActive !== false) ||
!ssoIdentity.FederatedID ||
error
) {
throw new TypeError(
'SsoIdentity should be an object with IsActive and FederatedID properties.'
);
}
// if SsoIdentity is set, assume this was on purpose and bring it
metadata.SsoIdentities = {
SsoIdentity: [
{
IsActive: ssoIdentity.IsActive,
FederatedID: ssoIdentity.FederatedID,
},
],
};
}
delete metadata.c__type;
delete metadata.c__AccountUserID;
delete metadata.c__IsLocked_readOnly;
return metadata;
}
/**
* helper for {@link MetadataType.upsert}
*
* @param {MetadataTypeMap} metadata list of metadata
* @param {string} metadataKey key of item we are looking at
* @param {boolean} hasError error flag from previous code
* @param {UserDocumentDiff[]} metadataToUpdate list of items to update
* @param {UserDocument[]} metadataToCreate list of items to create
* @returns {Promise.<'create'|'update'|'skip'>} action to take
*/
static async createOrUpdate(
metadata,
metadataKey,
hasError,
metadataToUpdate,
metadataToCreate
) {
const action = await super.createOrUpdate(
metadata,
metadataKey,
hasError,
metadataToUpdate,
metadataToCreate
);
if (action === 'create') {
const createItem = metadataToCreate.at(-1);
User._setPasswordForNewUser(createItem);
User._prepareRoleAssignments({ before: null, after: createItem });
User._prepareBuAssignments(metadata[metadataKey], null, createItem);
} else if (action === 'update') {
const updateItem = metadataToUpdate.at(-1);
User._prepareRoleAssignments(updateItem);
User._prepareBuAssignments(metadata[metadataKey], updateItem, null);
}
return action;
}
/**
*
* @private
* @param {MetadataTypeItem} metadata single metadata itme
* @param {UserDocumentDiff} [updateItem] item to update
* @param {UserDocument} [createItem] item to create
*/
static _prepareBuAssignments(metadata, updateItem, createItem) {
this.userBUassignments ||= { add: {}, delete: {} };
if (updateItem) {
// remove business units that were unassigned
const deletedBUs = [];
updateItem.before.c__AssociatedBusinessUnits =
this.userIdBuMap[updateItem.before.ID] || [];
for (const oldBuAssignment of updateItem.before.c__AssociatedBusinessUnits) {
// check if oldRole is missing in list of new roles
if (!updateItem.after.c__AssociatedBusinessUnits.includes(oldBuAssignment)) {
deletedBUs.push(oldBuAssignment);
}
}
if (deletedBUs.length > 0) {
this.userBUassignments['delete'][updateItem.before.AccountUserID] = deletedBUs;
}
// add business units that were newly assigned
const addedBUs = [];
for (const newBuAssignment of updateItem.after.c__AssociatedBusinessUnits) {
// check if oldRole is missing in list of new roles
if (!updateItem.before.c__AssociatedBusinessUnits.includes(newBuAssignment)) {
addedBUs.push(newBuAssignment);
}
}
if (addedBUs.length > 0) {
this.userBUassignments['add'][updateItem.before.AccountUserID] = addedBUs;
}
}
// add BUs for new users
if (createItem) {
const addedBUs = createItem.c__AssociatedBusinessUnits || [];
if (addedBUs.length > 0) {
this.userBUassignments['add']['key:' + createItem.CustomerKey] = addedBUs;
}
}
delete metadata.c__AssociatedBusinessUnits;
}
/**
* Gets executed after deployment of metadata type
*
* @param {UserDocumentMap} upsertResults metadata mapped by their keyField
* @returns {Promise.<void>} promise
*/
static async postDeployTasks(upsertResults) {
if (Object.keys(upsertResults).length) {
await this._handleBuAssignments(upsertResults);
}
}
/**
* create/update business unit assignments
*
* @private
* @param {UserDocumentMap} upsertResults metadata mapped by their keyField
* @returns {Promise.<void>} -
*/
static async _handleBuAssignments(upsertResults) {
/** @type {AccountUserConfiguration[]} */
const configs = [];
for (const action in this.userBUassignments) {
for (const data of Object.entries(this.userBUassignments[action])) {
const buIds = data[1];
let userId = data[0];
if (!userId) {
continue;
}
userId = userId.startsWith('key:') ? upsertResults[userId.slice(4)].ID : userId;
configs.push(
/** @type {AccountUserConfiguration} */ {
Client: { ID: this.buObject.eid },
ID: userId,
BusinessUnitAssignmentConfiguration: {
BusinessUnitIds: { BusinessUnitId: buIds },
IsDelete: action === 'delete',
},
}
);
}
}
if (configs.length > 0) {
Util.logger.info('Deploying: BU assignment changes');
// run update
// @ts-expect-error bad jsodc in SFMC-SDK
const buResponse = await this.client.soap.configure('AccountUser', configs);
// process response
if (buResponse.OverallStatus === 'OK') {
// get userIdNameMap
const userIdNameMap = {};
for (const user of Object.values(upsertResults)) {
userIdNameMap[user.ID] = `${user.CustomerKey} / ${user.Name}`;
}
// log what was added / removed
let configureResults = buResponse.Results?.[0]?.Result;
if (!configureResults) {
Util.logger.debug(
'buResponse.Results?.[0]?.Result not defined: ' + JSON.stringify(buResponse)
);
return;
}
if (!Array.isArray(configureResults)) {
configureResults = [configureResults];
}
const userBUresults = {};
for (const result of configureResults) {
if (result.StatusCode === 'OK') {
/** @type {AccountUserConfiguration} */
const config = result.Object;
const buArr =
config.BusinessUnitAssignmentConfiguration.BusinessUnitIds
.BusinessUnitId;
userBUresults[config.ID] ||= {
add: [],
delete: [],
};
userBUresults[config.ID][
config.BusinessUnitAssignmentConfiguration.IsDelete ? 'delete' : 'add'
] = Array.isArray(buArr) ? buArr : [buArr];
} else {
Util.logger.debug(
`Unknown error occured during processing of BU assignment reponse: ${JSON.stringify(
result
)}`
);
}
}
for (const [userId, buResult] of Object.entries(userBUresults)) {
// show CLI log
const msgs = [];
if (buResult['add']?.length) {
msgs.push(`MID ${buResult['add'].join(', ')} access granted`);
} else {
msgs.push('no new access granted');
}
if (buResult['delete']?.length) {
msgs.push(`MID ${buResult['delete'].join(', ')} access removed`);
} else {
msgs.push('no access removed');
}
Util.logger.info(` - user ${userIdNameMap[userId]}: ${msgs.join(' / ')}`);
// update BU map in local variable
if (buResult['add']?.length) {
this.userIdBuMap[userId] ||= [];
this.userIdBuMap[userId].push(
...buResult['add'].filter(
(item) => !this.userIdBuMap[userId].includes(item)
)
);
}
if (buResult['delete']?.length) {
this.userIdBuMap[userId] ||= [];
this.userIdBuMap[userId] = this.userIdBuMap[userId].filter(
(item) => !buResult['delete'].includes(item)
);
}
}
}
}
}
/**
* helper for {@link User.createOrUpdate}
*
* @private
* @param {UserDocument} metadata single created user
* @returns {void}
*/
static _setPasswordForNewUser(metadata) {
// if Password is not set during CREATE, generate one
// avoids error "Name, Email, UserID, and Password are required fields when creating a new user. (Code 11003)"
if (!metadata.Password) {
metadata.Password = this._generatePassword();
Util.logger.info(
` - Password for ${metadata.UserID} was not given. Generated password:`
);
// use console.log here to print the generated password to bypass the logfile
// eslint-disable-next-line no-console
console.log(metadata.Password);
}
}
/**
* helper for {@link User.createOrUpdate}
* It searches for roles that were removed from the user and unassigns them; it also prints a summary of added/removed roles
* Adding roles works automatically for roles listed on the user
*
* @private
* @param {UserDocumentDiff} item updated user with before and after state
* @returns {void}
*/
static _prepareRoleAssignments(item) {
// delete global roles from user that were not in the c__RoleNamesGlobal array / Roles.Role
const deletedRoles = [];
const deletedRoleNames = [];
if (item.after?.Roles?.Role && !Array.isArray(item.after.Roles.Role)) {
item.after.Roles.Role = [item.after.Roles.Role];
}
if (item.before?.Roles?.Role) {
if (!Array.isArray(item.before.Roles.Role)) {
item.before.Roles.Role = [item.before.Roles.Role];
}
for (const oldRole of item.before.Roles.Role) {
// check if oldRole is missing in list of new roles --> removing role
let oldRoleFound = false;
if (item.after.Roles?.Role) {
for (const newRole of item.after.Roles.Role) {
if (newRole.ObjectID == oldRole.ObjectID) {
oldRoleFound = true;
break;
}
}
}
if (!oldRoleFound && !oldRole.Name.startsWith('Individual role for ')) {
// delete role unless it is an individual role (which are not manageable nor visible in the GUI)
deletedRoles.push({ ObjectID: oldRole.ObjectID, Name: oldRole.Name });
deletedRoleNames.push(oldRole.Name);
}
}
}
const addedRoleNames = [];
if (item.after?.Roles?.Role) {
for (const newRole of item.after.Roles.Role) {
// check if newRole is missing in list of old roles --> adding role
let roleAlreadyExisting = false;
if (item.before?.Roles?.Role) {
for (const oldRole of item.before.Roles.Role) {
if (newRole.ObjectID == oldRole.ObjectID) {
roleAlreadyExisting = true;
break;
}
}
}
if (!roleAlreadyExisting) {
addedRoleNames.push(newRole.Name);
// Note: no AssignmentConfigurations property is needed to ADD global roles
}
}
if (addedRoleNames.length) {
Util.logger.info(
Util.getGrayMsg(
` - adding role-assignment (${item.after.CustomerKey} / ${
item.after.Name
}): ${addedRoleNames.join(', ')}`
)
);
}
}
if (deletedRoles.length) {
Util.logger.info(
Util.getGrayMsg(
` - removing role-assignment (${item.after.CustomerKey} / ${
item.after.Name
}): ${deletedRoleNames.join(', ')}`
)
);
// add deleted roles to payload with IsDelete=true
if (!item.after.Roles) {
item.after.Roles = { Role: [] };
} else if (!item.after.Roles.Role) {
item.after.Roles.Role = [];
}
item.after.Roles.Role.push(
...deletedRoles.map((role) =>
this._getRoleObjectForDeploy(
role.ObjectID,
role.Name,
item.after.AccountUserID,
false,
true
)
)
);
}
}
/**
* helper for {@link User._prepareRoleAssignments}
*
* @param {string} roleId role.ObjectID
* @param {string} roleName role.Name
* @param {number} userId user.AccountUserID
* @param {boolean} assignmentOnly if true, only assignment configuration will be returned
* @param {boolean} [isRoleRemovale] if true, role will be removed from user; otherwise added
* @returns {object} format needed by API
*/
static _getRoleObjectForDeploy(
roleId,
roleName,
userId,
assignmentOnly,
isRoleRemovale = false
) {
const assignmentConfigurations = {
AssignmentConfiguration: [
{
AccountUserId: userId,
AssignmentConfigureType: 'RoleUser',
IsDelete: isRoleRemovale,
},
],
};
return assignmentOnly
? assignmentConfigurations
: {
ObjectID: roleId,
Name: roleName,
AssignmentConfigurations: assignmentConfigurations,
};
}
/**
* Retrieves SOAP based metadata of metadata type into local filesystem. executes callback with retrieved metadata
*
* @returns {Promise.<MetadataTypeMapObj>} Promise of metadata
*/
static async retrieveChangelog() {
return this._retrieve();
}
/**
* Retrieves SOAP based metadata of metadata type into local filesystem. executes callback with retrieved metadata
*
* @private
* @param {string} [retrieveDir] Directory where retrieved metadata directory will be saved
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<MetadataTypeMapObj>} Promise of metadata
*/
static async _retrieve(retrieveDir, key) {
this.userIdBuMap = {};
/** @type {SoapRequestParams} */
const requestParams = {
QueryAllAccounts: true,
filter: {
// normal users
leftOperand: 'Email',
operator: 'like',
rightOperand: '@',
},
};
if (key) {
// move original filter down one level into rightOperand and add key filter into leftOperand
requestParams.filter = {
leftOperand: {
leftOperand: 'CustomerKey',
operator: 'equals',
rightOperand: key,
},
operator: 'AND',
rightOperand: requestParams.filter,
};
} else {
// if we are not filtering by key the following requests will take long. Warn the user
Util.logger.info(` - Loading ${this.definition.type}s. This might take a while...`);
}
// get actual user details
return this.retrieveSOAP(retrieveDir, requestParams, key);
}
/**
* Retrieves SOAP via generic fuel-soap wrapper based metadata of metadata type into local filesystem. executes callback with retrieved metadata
*
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {SoapRequestParams} [requestParams] required for the specific request (filter for example)
* @param {string} [singleRetrieve] key of single item to filter by
* @param {string[]} [additionalFields] Returns specified fields even if their retrieve definition is not set to true
* @returns {Promise.<MetadataTypeMapObj>} Promise of item map
*/
static async retrieveSOAP(retrieveDir, requestParams, singleRetrieve, additionalFields) {
// to avoid not retrieving roles and userPermissions for users above the 2500 records limit we need to retrieve users twice, once with ActiveFlag=true and once with ActiveFlag=false
const requestParamsUser = {
QueryAllAccounts: true,
filter: {
leftOperand: {
leftOperand: 'ActiveFlag',
operator: 'equals',
rightOperand: null,
},
operator: 'AND',
rightOperand: requestParams.filter,
},
};
const fields = this.getFieldNamesToRetrieve(additionalFields, !retrieveDir);
const soapType = this.definition.soapType || this.definition.type;
let resultsBulk;
let foundSingle = false;
for (const active of [true, false]) {
requestParamsUser.filter.leftOperand.rightOperand = active;
try {
const resultsBatch = await this.client.soap.retrieveBulk(
soapType,
fields,
requestParamsUser
);
if (Array.isArray(resultsBatch?.Results)) {
Util.logger.debug(
Util.getGrayMsg(
` - found ${resultsBatch?.Results.length} ${
active ? 'active' : 'inactive'
} ${this.definition.type}s`
)
);
if (resultsBulk) {
// once first batch is done, the follow just add to result payload
resultsBulk.Results.push(...resultsBatch.Results);
} else {
resultsBulk = resultsBatch;
}
if (singleRetrieve && resultsBatch?.Results.length) {
foundSingle = true;
break;
}
}
} catch (ex) {
this._handleSOAPErrors(ex, 'retrieving');
return;
}
}
if (
!foundSingle &&
!(await this._retrieveSOAP_installedPackage(
requestParams,
soapType,
fields,
resultsBulk
))
) {
return;
}
const metadata = this.parseResponseBody(resultsBulk);
// get BUs that each users have access to
if (resultsBulk?.Results?.length > 0) {
if (!singleRetrieve) {
Util.logger.info(
Util.getGrayMsg(` - found ${resultsBulk?.Results.length} users`)
);
}
// split array resultsBulk?.Results into chunks to avoid not getting all roles
const chunkSize = 100;
this.userIdBuMap = {};
Util.logger.info(` - Caching dependent Metadata: Business Unit assignments`);
for (let i = 0; i < resultsBulk?.Results?.length; i += chunkSize) {
if (i > 0) {
Util.logger.info(
Util.getGrayMsg(` - Requesting next batch (retrieved BUs for ${i} users)`)
);
}
const chunk = resultsBulk?.Results?.slice(i, i + chunkSize);
const resultsBatch = (
await this.client.soap.retrieveBulk(
'AccountUserAccount',
['AccountUser.AccountUserID', 'Account.ID'],
{
filter: {
leftOperand: 'AccountUser.AccountUserID',
operator: chunk.length > 1 ? 'IN' : 'equals', // API does not allow IN for single item
rightOperand: chunk.map((item) => item.AccountUserID),
},
}
)
).Results;
for (const item of resultsBatch) {
this.userIdBuMap[item.AccountUser.AccountUserID] ||= [];
// push to array if not already in array
if (
!this.userIdBuMap[item.AccountUser.AccountUserID].includes(item.Account.ID)
) {
this.userIdBuMap[item.AccountUser.AccountUserID].push(item.Account.ID);
}
}
}
}
if (retrieveDir) {
const savedMetadata = await this.saveResults(metadata, retrieveDir, null);
Util.logger.info(
`Downloaded: ${this.definition.type} (${Object.keys(savedMetadata).length})` +
Util.getKeysString(singleRetrieve)
);
if (!singleRetrieve) {
// print summary to cli
const counter = {
userActive: 0,
userInactive: 0,
installedPackage: 0,
};
for (const id in savedMetadata) {
const item = savedMetadata[id];
if (item.c__type === 'Installed Package') {
counter.installedPackage++;
} else if (item.ActiveFlag) {
counter.userActive++;
} else {
counter.userInactive++;
}
}
Util.logger.info(
Util.getGrayMsg(
`Found ${counter.userActive} active users / ${counter.userInactive} inactive users / ${counter.installedPackage} installed packages`
)
);
}
await this.runDocumentOnRetrieve(singleRetrieve, savedMetadata);
}
return { metadata: metadata, type: this.definition.type };
}
/**
* helper for {@link User.retrieveSOAP}
*
* @private
* @param {SoapRequestParams} requestParams required for the specific request (filter for example)
* @param {string} soapType e.g. AccountUser
* @param {string[]} fields list of fields to retrieve
* @param {object} resultsBulk actual return value of this method
* @returns {Promise.<boolean>} success flag
*/
static async _retrieveSOAP_installedPackage(requestParams, soapType, fields, resultsBulk) {
/** @type {SoapRequestParams} */
const requestParamsInstalledPackage = {
QueryAllAccounts: true,
filter: {
leftOperand: {
leftOperand: 'ActiveFlag',
operator: 'equals',
rightOperand: true, // inactive installed packages are not visible in UI and hence cannot be reactivated there. Let's not retrieve them
},
operator: 'AND',
rightOperand: {
leftOperand: {
// filter out normal users
leftOperand: 'Email',
operator: 'isNull',
},
operator: 'OR',
rightOperand: {
// installed packages
leftOperand: {
leftOperand: 'Name',
operator: 'like',
rightOperand: ' app user', // ! will not work if the name was too long as "app user" might be cut off
},
operator: 'AND',
rightOperand: {
// this is used to filter out system generated installed packages. in our testing, at least those installed packages created in the last few years have hat set this to false while additional (hidden) installed packages have it set to true.
leftOperand: 'MustChangePassword',
operator: 'equals',
rightOperand: 'false',
},
},
},
},
};
if (
'object' === typeof requestParams?.filter?.leftOperand &&
requestParams?.filter?.leftOperand?.leftOperand === 'CustomerKey'
) {
requestParamsInstalledPackage.filter = {
leftOperand: requestParams?.filter?.leftOperand,
operator: 'AND',
rightOperand: requestParamsInstalledPackage.filter,
};
}
try {
const resultsBatch = await this.client.soap.retrieveBulk(
soapType,
fields,
requestParamsInstalledPackage
);
if (Array.isArray(resultsBatch?.Results)) {
Util.logger.debug(
Util.getGrayMsg(` - found ${resultsBatch?.Results.length} installed packages`)
);
if (resultsBulk) {
// once first batch is done, the follow just add to result payload
resultsBulk.Results.push(...resultsBatch.Results);
} else {
resultsBulk = resultsBatch;
}
}
} catch (ex) {
this._handleSOAPErrors(ex, 'retrieving');
return false;
}
return true;
}
/**
*
* @param {string} dateStr first date
* @param {string} interval defaults to 'days'
* @returns {string} time difference
*/
static #timeSinceDate(dateStr, interval = 'days') {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24,
week = day * 7;
const date = new Date(dateStr);
const now = new Date();
// get difference in miliseconds
const timediff = now.valueOf() - date.valueOf();
if (Number.isNaN(timediff)) {
return '';
}
let result;
switch (interval) {
case 'years': {
result = now.getFullYear() - date.getFullYear();
break;
}
case 'months': {
result =
now.getFullYear() * 12 +
now.getMonth() -
(date.getFullYear() * 12 + date.getMonth());
break;
}
case 'weeks': {
result = Math.floor(timediff / week);
break;
}
case 'days': {
result = Math.floor(timediff / day);
break;
}
case 'hours': {
result = Math.floor(timediff / hour);
break;
}
case 'minutes': {
result = Math.floor(timediff / minute);
break;
}
case 'seconds': {
result = Math.floor(timediff / second);
break;
}
default: {
return;
}
}
return result + ' ' + interval;
}
/**
* helper to print bu names
*
* @private
* @param {number} id bu id
* @returns {string} "bu name (bu id)""
*/
static _getBuName(id) {
const name = this.buObject.eid == id ? '_ParentBU_' : this.buIdName[id];
return `<nobr>${name} (${id})</nobr>`;
}
/**
* helper that gets BU names from config
*
* @private
*/
static _getBuNames() {
this.buIdName = {};
for (const cred in this.properties.credentials) {
for (const buName in this.properties.credentials[cred].businessUnits) {
this.buIdName[this.properties.credentials[cred].businessUnits[buName]] = buName;
}
}
}
/**
* helper for {@link User.createOrUpdate} to generate a random initial password for new users
* note: possible minimum length values in SFMC are 6, 8, 10, 15 chars. Therefore we should default here to 15 chars.
*
* @private
* @param {number} [length] length of password; defaults to 15
* @returns {string} random password
*/
static _generatePassword(length = 15) {
const alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const special = '!@#$%&';
const numeric = '0123456789';
const charset = alpha + special + numeric;
let retVal;
do {
retVal = '';
for (let i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
// check if password contains at least one of each character type or else generate a new one
} while (
!/[a-z]/.test(retVal) ||
!/[A-Z]/.test(retVal) ||
!/[0-9]/.test(retVal) ||
!/[!@#$%&]/.test(retVal)
);
return retVal;
}
/**
* Creates markdown documentation of all roles
*
* @param {UserDocumentMap} [metadata] user list
* @returns {Promise.<void>} -
*/
static async document(metadata) {
if (this.buObject.eid !== this.buObject.mid) {
Util.logger.error(
`Users can only be retrieved & documented for the ${Util.parentBuName}`
);
return;
}
if (!metadata) {
// load users from disk if document was called directly and not part of a retrieve
try {
metadata = await this.readBUMetadataForType(
File.normalizePath([
this.properties.directories.retrieve,
this.buObject.credential,
Util.parentBuName,
]),
true
).user;
} catch (ex) {
Util.logger.error(ex.message);
return;
}
}
// init map of BU Ids > BU Name
this._getBuNames();
/** @type {UserDocumentDocument[]} */
const users = [];
for (const id in metadata) {
const user = metadata[id];
// TODO resolve user permissions to something readable
// user roles