-
Notifications
You must be signed in to change notification settings - Fork 36
/
Role.js
330 lines (316 loc) · 12.6 KB
/
Role.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
'use strict';
const TYPE = require('../../types/mcdev.d');
const MetadataType = require('./MetadataType');
const Util = require('../util/util');
const File = require('../util/file');
const cache = require('../util/cache');
/**
* ImportFile MetadataType
*
* @augments MetadataType
*/
class Role extends MetadataType {
/**
* Gets metadata from Marketing Cloud
*
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {string[]} _ Returns specified fields even if their retrieve definition is not set to true
* @param {void} [___] unused parameter
* @param {string} [key] customer key of single item to retrieve
* @returns {Promise.<TYPE.MetadataTypeMapObj>} Metadata store object
*/
static async retrieve(retrieveDir, _, ___, key) {
if (retrieveDir && this.buObject.eid !== this.buObject.mid) {
// don't run for BUs other than Parent BU
// this check does not work during caching
Util.logger.info(' - Skipping Role retrieval on non-parent BU');
return;
}
const fields = super.getFieldNamesToRetrieve(null, !retrieveDir);
let requestParams = {
// filter individual roles
filter: {
leftOperand: 'IsPrivate',
operator: 'equals',
rightOperand: false,
},
};
/** @type {TYPE.SoapRequestParams} */
if (key) {
// move original filter down one level into rightOperand and add key filter into leftOperand
const keyFilter = {
leftOperand: 'CustomerKey',
operator: 'equals',
rightOperand: key,
};
requestParams = requestParams
? {
filter: {
leftOperand: keyFilter,
operator: 'AND',
rightOperand: requestParams.filter,
},
}
: keyFilter;
}
const results = await this.client.soap.retrieve('Role', fields, requestParams);
const parsed = this.parseResponseBody(results);
if (!retrieveDir) {
// retrieve "Marketing Cloud%" roles not returned by SOAP API
const { roles, timeZones } = await this.client.rest.get(
'/platform/v1/setup/quickflow/data'
);
// this endpoint does not provide keys
const roleNameKeyMap = {
'Marketing Cloud Administrator': 'SYS_DEF_IMHADMIN',
'Marketing Cloud Channel Manager': 'SYS_DEF_CHANNELMANAGER',
'Marketing Cloud Content Editor/Publisher': 'SYS_DEF_CONTENTEDIT',
'Marketing Cloud Security Administrator': 'SYS_DEF_SECURITYADMIN',
'Marketing Cloud Viewer': 'SYS_DEF_VIEWER',
};
for (const role of roles) {
if (roleNameKeyMap[role.roleName]) {
parsed[roleNameKeyMap[role.roleName]] = {
CustomerKey: roleNameKeyMap[role.roleName],
Name: role.roleName,
ObjectID: role.roleID,
Desscription: role.description,
CreatedDate: '2012-02-21T02:09:19.983',
IsSystemDefined: true,
c__notAssignable: true,
};
}
}
// the languages object is incomplete. the actual list is much longer --> ignoring it here
// convert timeZones to object
const timeZonesObj = {};
for (const timeZone of timeZones) {
timeZonesObj[timeZone.id] = timeZone;
}
// cache timeZones to share it with other type-classes
cache.setMetadata('_timezone', timeZonesObj);
}
if (retrieveDir) {
const savedMetadata = await super.saveResults(parsed, retrieveDir, null);
Util.logger.info(
`Downloaded: ${this.definition.type} (${Object.keys(savedMetadata).length})` +
Util.getKeysString(key)
);
await this.runDocumentOnRetrieve(key, savedMetadata);
}
return { metadata: parsed, type: this.definition.type };
}
/**
* Gets executed before deploying metadata
*
* @param {TYPE.MetadataTypeItem} metadata a single metadata item
* @returns {TYPE.MetadataTypeItem} Promise of a single metadata item
*/
static preDeployTasks(metadata) {
if (this.definition.deployBlacklist.includes(metadata.CustomerKey)) {
throw new Error(
`Skipped ${metadata.Name} (${metadata.CustomerKey}) because its CustomerKey is reserved for a default system role.`
);
}
return metadata;
}
/**
* Create a single Role.
*
* @param {TYPE.MetadataTypeItem} metadata single metadata entry
* @returns {Promise} Promise
*/
static create(metadata) {
return super.createSOAP(metadata);
}
/**
* Updates a single Role.
*
* @param {TYPE.MetadataTypeItem} metadata single metadata entry
* @returns {Promise} Promise
*/
static update(metadata) {
return super.updateSOAP(metadata);
}
/**
* Creates markdown documentation of all roles
*
* @param {TYPE.MetadataTypeMap} [metadata] role definitions
* @returns {Promise.<void>} -
*/
static async document(metadata) {
if (this.buObject.eid !== this.buObject.mid) {
Util.logger.error(
`Roles can only be retrieved & documented for the ${Util.parentBuName}`
);
return;
}
if (!metadata) {
try {
metadata = this.readBUMetadataForType(
File.normalizePath([
this.properties.directories.retrieve,
this.buObject.credential,
Util.parentBuName,
]),
true
).role;
} catch (ex) {
Util.logger.error(ex.message);
return;
}
}
const directory = File.normalizePath([this.properties.directories.docs, 'role']);
// initialize permission object
this.allPermissions = {};
// traverse all permissions recursively and write them into allPermissions object once it has reached the end
for (const role in metadata) {
// filter standard rules
if (
this.properties.options?.documentStandardRoles === false &&
'string' === typeof metadata[role]?.CustomerKey && // key could be numeric
metadata[role].CustomerKey.startsWith('SYS_DEF')
) {
delete metadata[role];
} else {
for (const element of metadata[role].PermissionSets.PermissionSet) {
this._traverseRoles(role, element);
}
}
}
// Create output markdown
let output = `# Permission Overview - ${this.buObject.credential}\n\n`;
output += `> **Legend**
>
> <hr>
>
> **[Role Name]** = System Default Role
>
> **Role Name** = Custom Role
>
> **+** = _Allow_: User has access to the application or functionality
>
> ** •** = _Not Set_: User permission for this app or functionality is not explicitely granted nor denied, but defaults to Deny
>
> **-** = _Deny_: User does not have access to the app or functionality
>
> <hr>\n\n`;
// Loop through all permissions
for (const permGroup in this.allPermissions) {
output += '## ' + permGroup + '\n\n';
// create table header
output += '| Permission |';
let separator = '| --- |';
for (const role in metadata) {
output +=
metadata[role].IsSystemDefined === true
? ` [${metadata[role].Name}] |`
: ` ${metadata[role].Name} |`;
separator += ' --- |';
}
output += '\n' + separator + '\n';
// Write all permissions of a major permission group
// output += '| ';
for (const permission in this.allPermissions[permGroup]) {
output += '| ' + permission + ' |';
for (const role in this.allPermissions[permGroup][permission]) {
if (this.allPermissions[permGroup][permission][role] === true) {
output += ' + |';
} else if (this.allPermissions[permGroup][permission][role] === false) {
output += ' - |';
} else if (
'undefined' === typeof this.allPermissions[permGroup][permission][role]
) {
output += ' • |';
} else {
output += ' ' + this.allPermissions[permGroup][permission][role] + ' |';
}
}
output += '\n';
}
output += '\n';
}
try {
const filename = this.buObject.credential;
// write to disk
await File.writeToFile(directory, filename + '.roles', 'md', output);
Util.logger.info(`Created ${File.normalizePath([directory, filename])}.roles.md`);
if (['html', 'both'].includes(this.properties.options.documentType)) {
Util.logger.warn(' - HTML-based documentation of roles currently not supported.');
}
} catch (ex) {
Util.logger.error(`Roles.document():: error | `, ex.message);
}
}
/**
* iterates through permissions to output proper row-names for nested permissionss
*
* @static
* @param {string} role name of the user role
* @param {object} element data of the permission
* @param {string} [permission] name of the permission
* @param {string} [isAllowed] "true" / "false" from the
* @memberof Role
* @returns {void}
*/
static _traverseRoles(role, element, permission, isAllowed) {
const _permission = permission ? permission + ' > ' + element.Name : element.Name;
// Reached end: write permission into this.allPermissions
if (element.Operation) {
const permSplit = _permission.split(' > ');
const permOperation = permSplit.pop();
let basePermission = permSplit.shift();
if (basePermission === 'Interactive Marketing Hub') {
basePermission = 'Salesforce Marketing Cloud';
}
const permissionName = `<nobr><b>${permSplit.join(
' > '
)}</b> > ${permOperation}</nobr>`;
if (!this.allPermissions[basePermission]) {
this.allPermissions[basePermission] = {};
}
if (!this.allPermissions[basePermission][permissionName]) {
this.allPermissions[basePermission][permissionName] = {};
}
this.allPermissions[basePermission][permissionName][role] =
element.IsAllowed || isAllowed;
// Not at end: Traverse more
} else if (element.PermissionSets) {
if (Array.isArray(element.PermissionSets.PermissionSet)) {
for (const nextElement of element.PermissionSets.PermissionSet) {
this._traverseRoles(role, nextElement, _permission);
}
} else {
this._traverseRoles(
role,
element.PermissionSets.PermissionSet,
_permission,
element.IsAllowed,
isAllowed
);
}
// Not at end: Traverse more
} else if (element.Permissions) {
if (Array.isArray(element.Permissions.Permission)) {
for (const nextElement of element.Permissions.Permission) {
this._traverseRoles(
role,
nextElement,
_permission,
element.IsAllowed || isAllowed
);
}
} else {
this._traverseRoles(
role,
element.Permissions.Permission,
_permission,
element.IsAllowed || isAllowed
);
}
}
}
}
// Assign definition to static attributes
Role.definition = require('../MetadataTypeDefinitions').role;
module.exports = Role;