-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathuser.js
More file actions
2095 lines (1962 loc) · 89.4 KB
/
user.js
File metadata and controls
2095 lines (1962 loc) · 89.4 KB
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
import bcrypt from 'bcryptjs';
import * as R from 'ramda';
import { uniq } from 'ramda';
import { v4 as uuid } from 'uuid';
import { DateTime } from 'luxon';
import conf, {
ACCOUNT_STATUS_ACTIVE,
ACCOUNT_STATUS_EXPIRED,
ACCOUNT_STATUS_LOCKED,
ACCOUNT_STATUSES,
BUS_TOPICS,
DEFAULT_ACCOUNT_STATUS,
ENABLED_DEMO_MODE,
getRequestAuditHeaders,
logApp,
} from '../config/conf';
import { AuthenticationFailure, ConfigurationError, DatabaseError, DraftLockedError, ForbiddenAccess, FunctionalError, UnsupportedError } from '../config/errors';
import { getEntitiesListFromCache, getEntitiesMapFromCache, getEntityFromCache } from '../database/cache';
import { elLoadBy, elRawDeleteByQuery } from '../database/engine';
import { createEntity, createRelation, deleteElementById, deleteRelationsByFromAndTo, patchAttribute, updateAttribute, updatedInputsToData } from '../database/middleware';
import {
fullEntitiesList,
fullEntitiesThoughAggregationConnection,
fullEntitiesThroughRelationsToList,
fullRelationsList,
internalFindByIds,
internalLoadById,
pageEntitiesConnection,
pageRegardingEntitiesConnection,
storeLoadById,
} from '../database/middleware-loader';
import { delEditContext, notify, setEditContext } from '../database/redis';
import { findUserSessions, killSessions, killUserSessions } from '../database/session';
import {
buildPagination,
isEmptyField,
isNotEmptyField,
READ_INDEX_INTERNAL_OBJECTS,
READ_INDEX_STIX_DOMAIN_OBJECTS,
READ_RELATIONSHIPS_INDICES,
UPDATE_OPERATION_REPLACE,
} from '../database/utils';
import { extractEntityRepresentativeName } from '../database/entity-representative';
import { publishUserAction } from '../listener/UserActionListener';
import { authorizedMembers } from '../schema/attribute-definition';
import { ABSTRACT_INTERNAL_RELATIONSHIP, ABSTRACT_STIX_DOMAIN_OBJECT, OPENCTI_ADMIN_UUID } from '../schema/general';
import { generateStandardId } from '../schema/identifier';
import { ENTITY_TYPE_CAPABILITY, ENTITY_TYPE_GROUP, ENTITY_TYPE_ROLE, ENTITY_TYPE_SETTINGS, ENTITY_TYPE_USER } from '../schema/internalObject';
import { getTokensUsage, updateTokenUsage } from '../database/redis/token_usage';
import {
isInternalRelationship,
RELATION_ACCESSES_TO,
RELATION_HAS_CAPABILITY,
RELATION_HAS_CAPABILITY_IN_DRAFT,
RELATION_HAS_ROLE,
RELATION_MEMBER_OF,
RELATION_PARTICIPATE_TO,
} from '../schema/internalRelationship';
import { ENTITY_TYPE_IDENTITY_INDIVIDUAL } from '../schema/stixDomainObject';
import { ENTITY_TYPE_MARKING_DEFINITION } from '../schema/stixMetaObject';
import {
buildUserOrganizationRestrictedFiltersOptions,
BYPASS,
CAPABILITIES_IN_DRAFT_NAMES,
DEFAULT_INVALID_CONF_VALUE,
executionContext,
FilterMembersMode,
filterMembersUsersWithUsersOrgs,
findAllMembersWithOrgaRestriction,
findMembersPaginatedWithOrgaRestriction,
INTERNAL_USERS,
INTERNAL_USERS_WITHOUT_REDACTED,
isBypassUser,
isOnlyOrgaAdmin,
isUserHasCapability,
REDACTED_USER,
SETTINGS_SET_ACCESSES,
SYSTEM_USER,
VIRTUAL_ORGANIZATION_ADMIN,
} from '../utils/access';
import { ASSIGNEE_FILTER, CREATOR_FILTER, PARTICIPANT_FILTER } from '../utils/filtering/filtering-constants';
import { now, utcDate } from '../utils/format';
import { addGroup } from './grant';
import { defaultMarkingDefinitionsFromGroups, findGroupPaginated as findGroups } from './group';
import { addIndividual } from './individual';
import { ENTITY_TYPE_IDENTITY_ORGANIZATION } from '../modules/organization/organization-types';
import { ENTITY_TYPE_WORKSPACE } from '../modules/workspace/workspace-types';
import { addFilter, extractFilterKeys } from '../utils/filtering/filtering-utils';
import { testFilterGroup, testStringFilter } from '../utils/filtering/boolean-logic-engine';
import { computeUserEffectiveConfidenceLevel } from '../utils/confidence-level';
import { STATIC_NOTIFIER_EMAIL, STATIC_NOTIFIER_UI } from '../modules/notifier/notifier-statics';
import { cleanMarkings } from '../utils/markingDefinition-utils';
import { UnitSystem } from '../generated/graphql';
import { DRAFT_STATUS_OPEN } from '../modules/draftWorkspace/draftStatuses';
import { ENTITY_TYPE_DRAFT_WORKSPACE } from '../modules/draftWorkspace/draftWorkspace-types';
import { addCapabilitiesInDraftUpdatedCount, addServiceAccountIntoUserCount, addUserEmailSendCount, addUserIntoServiceAccountCount } from '../manager/telemetryManager';
import { sendMail, smtpComputeFrom } from '../database/smtp';
import { checkEnterpriseEdition } from '../enterprise-edition/ee';
import { ENTITY_TYPE_EMAIL_TEMPLATE } from '../modules/emailTemplate/emailTemplate-types';
import { doYield } from '../utils/eventloop-utils';
import { sanitizeUser } from '../utils/templateContextSanitizer';
import { safeRender } from '../utils/safeEjs.client';
import { totp } from '../utils/totp';
import { pushAll } from '../utils/arrayUtil';
import { apiTokens } from '../modules/attributes/internalObject-registrationAttributes';
import { SignJWT } from 'jose';
import { getPlatformCrypto } from '../utils/platformCrypto';
import { addUserTokenByAdmin, generateTokenHmac } from '../modules/user/user-domain';
import { memoize } from '../utils/memoize';
import { getSettings } from './settings';
import passport from 'passport';
import {
getConfigurationAdminEmail,
getConfigurationAdminPassword,
getConfigurationAdminToken,
LOCAL_STRATEGY_IDENTIFIER,
PROVIDERS,
} from '../modules/authenticationProvider/providers-configuration';
import { addOrganization } from '../modules/organization/organization-domain';
import validator from 'validator';
const BEARER = 'Bearer ';
const BASIC = 'Basic ';
export const TAXIIAPI = 'TAXIIAPI';
const PLATFORM_ORGANIZATION = 'settings_platform_organization';
const PROTECTED_USER_ATTRIBUTES = [apiTokens.name, 'external'];
const PROTECTED_EXTERNAL_ATTRIBUTES = ['user_email', 'user_name'];
const ME_USER_MODIFIABLE_ATTRIBUTES = [
'user_email',
'user_name',
'description',
'firstname',
'lastname',
'theme',
'language',
'personal_notifiers',
'default_dashboard',
'default_time_field',
'unit_system',
'submenu_show_icons',
'submenu_auto_collapse',
'monochrome_labels',
'password',
'draft_context',
];
const AVAILABLE_LANGUAGES = ['auto', 'es-es', 'fr-fr', 'ja-jp', 'zh-cn', 'en-us', 'de-de', 'ko-kr', 'ru-ru', 'it-it'];
const computeImpactedUsers = async (context, user, roleId) => {
// Get all groups that have this role
const groupsRoles = await fullRelationsList(context, user, RELATION_HAS_ROLE, { toId: roleId, fromTypes: [ENTITY_TYPE_GROUP] });
const groupIds = groupsRoles.map((group) => group.fromId);
// Get all users for groups
const usersGroups = await fullRelationsList(context, user, RELATION_MEMBER_OF, { toId: groupIds, toTypes: [ENTITY_TYPE_GROUP] });
const userIds = R.uniq(usersGroups.map((u) => u.fromId));
// Mark for refresh all impacted sessions
return internalFindByIds(context, user, userIds);
};
const roleUsersCacheRefresh = async (context, user, roleId) => {
const users = await computeImpactedUsers(context, user, roleId);
await notify(BUS_TOPICS[ENTITY_TYPE_USER].EDIT_TOPIC, users, user);
};
export const userWithOrigin = (req, user) => {
// /!\ This metadata information is used in different ways
// - In audit logs to identify the user
// - In stream message to also identifier the user
// - In logging system to know the level of the error message
// Additional header from "authentication with header" authentication mode
const sso_headers_metadata = R.mergeAll((user.headers_audit ?? [])
.map((header) => ({ [header]: req.header(header) })));
const tracing_headers_metadata = getRequestAuditHeaders(req);
const origin = {
socket: 'query',
ip: req?.ip,
user_id: user.id,
group_ids: user.groups?.map((g) => g.internal_id) ?? [],
organization_ids: user.organizations?.map((o) => o.internal_id) ?? [],
user_metadata: { ...sso_headers_metadata, ...tracing_headers_metadata },
referer: req?.headers.referer,
applicant_id: req?.headers['opencti-applicant-id'],
call_retry_number: req?.headers['opencti-retry-number'],
playbook_id: req?.headers['opencti-playbook-id'],
};
return { ...user, origin };
};
const extractTokenFromBearer = (authorization) => {
const isBearer = authorization && authorization.startsWith(BEARER);
return isBearer ? authorization.substring(BEARER.length) : null;
};
const extractInfoFromBasicAuth = (authorization) => {
const isBasic = authorization && authorization.startsWith(BASIC);
if (isBasic) {
const b64auth = authorization.substring(BASIC.length);
const [username, password] = Buffer.from(b64auth, 'base64').toString().split(':');
return { username, password };
}
return {};
};
const extractUserFromBasicAuth = async (authorization) => {
const { username, password } = extractInfoFromBasicAuth(authorization);
if (username && password) {
return { username, password };
}
return null;
};
export const findById = async (context, user, userId) => {
if (!isUserHasCapability(user, SETTINGS_SET_ACCESSES) && user.id !== userId) {
// if no organization in common with the logged user administrated organizations
const memberOrganizations = await fullEntitiesThroughRelationsToList(context, user, userId, RELATION_PARTICIPATE_TO, ENTITY_TYPE_IDENTITY_ORGANIZATION);
const myOrganizationsIds = user.administrated_organizations.map((organization) => organization.id);
if (!memberOrganizations.map((organization) => organization.id).find((orgaId) => myOrganizationsIds.includes(orgaId))) {
throw ForbiddenAccess();
}
}
if (INTERNAL_USERS[userId]) {
return INTERNAL_USERS[userId];
}
const data = await storeLoadById(context, user, userId, ENTITY_TYPE_USER);
const withoutPassword = data ? R.dissoc('password', data) : data;
return buildCompleteUser(context, withoutPassword);
};
export const findAllUser = async (context, user, args) => {
const { filters, noRegardingOfFilterIdsCheck } = buildUserOrganizationRestrictedFiltersOptions(user, args.filters);
return fullEntitiesList(context, user, [ENTITY_TYPE_USER], { ...args, filters, noRegardingOfFilterIdsCheck });
};
export const findUserPaginated = async (context, user, args) => {
const { filters, noRegardingOfFilterIdsCheck } = buildUserOrganizationRestrictedFiltersOptions(user, args.filters);
return pageEntitiesConnection(context, user, [ENTITY_TYPE_USER], { ...args, filters, noRegardingOfFilterIdsCheck });
};
const postResolveMembersFunction = (context, user) => {
return async (usersResult) => {
return filterMembersUsersWithUsersOrgs(context, user, usersResult, FilterMembersMode.EXCLUDE);
};
};
export const findCreators = (context, user, args) => {
const { entityTypes = [] } = args;
const creatorsFilter = postResolveMembersFunction(context, user);
return fullEntitiesThoughAggregationConnection(context, user, CREATOR_FILTER, ENTITY_TYPE_USER, { ...args, types: entityTypes, postResolveFilter: creatorsFilter });
};
export const findAssignees = (context, user, args) => {
const { entityTypes = [] } = args;
const assigneesFilter = postResolveMembersFunction(context, user);
return fullEntitiesThoughAggregationConnection(context, user, ASSIGNEE_FILTER, ENTITY_TYPE_USER, { ...args, types: entityTypes, postResolveFilter: assigneesFilter });
};
export const findParticipants = (context, user, args) => {
const { entityTypes = [] } = args;
const participantsFilter = postResolveMembersFunction(context, user);
return fullEntitiesThoughAggregationConnection(context, user, PARTICIPANT_FILTER, ENTITY_TYPE_USER, { ...args, types: entityTypes, postResolveFilter: participantsFilter });
};
export const findMembersPaginated = async (context, user, args) => {
return findMembersPaginatedWithOrgaRestriction(context, user, args);
};
export const findAllMembers = async (context, user, args) => {
return findAllMembersWithOrgaRestriction(context, user, args);
};
export const findUserWithCapabilities = async (context, user, capabilities) => {
const users = await getEntitiesListFromCache(context, user, ENTITY_TYPE_USER);
return users.filter((u) => u.capabilities.some((userCapability) => capabilities.some((capability) => capability === userCapability.name)));
};
export const findAllSystemMemberPaginated = () => {
const members = R.values(INTERNAL_USERS_WITHOUT_REDACTED);
return buildPagination(0, null, members.map((r) => ({ node: r })), members.length);
};
// build only a creator object with what we need to expose of users
const buildCreatorUser = (user) => {
if (!user) {
return user;
}
return {
id: user.id,
entity_type: user.entity_type,
name: ENABLED_DEMO_MODE ? REDACTED_USER.name : user.name,
description: user.description,
standard_id: user.id,
[RELATION_PARTICIPATE_TO]: user[RELATION_PARTICIPATE_TO],
};
};
export const batchCreator = async (context, user, userIds) => {
const platformUsers = await getEntitiesMapFromCache(context, SYSTEM_USER, ENTITY_TYPE_USER);
return userIds.map((id) => INTERNAL_USERS[id] || buildCreatorUser(platformUsers.get(id)) || SYSTEM_USER);
};
export const batchCreators = async (context, user, userListIds) => {
const userIds = userListIds.map((u) => (Array.isArray(u) ? u : [u]));
const platformUsers = await getEntitiesMapFromCache(context, SYSTEM_USER, ENTITY_TYPE_USER);
return userIds.map((ids) => ids.map((id) => INTERNAL_USERS[id] || buildCreatorUser(platformUsers.get(id)) || SYSTEM_USER));
};
export const userOrganizationsPaginatedWithoutInferences = async (context, user, userId, opts) => {
const args = { ...opts, withInferences: false };
return pageRegardingEntitiesConnection(context, user, userId, RELATION_PARTICIPATE_TO, ENTITY_TYPE_IDENTITY_ORGANIZATION, false, args);
};
export const userOrganizationsPaginated = async (context, user, userId, opts) => {
return pageRegardingEntitiesConnection(context, user, userId, RELATION_PARTICIPATE_TO, ENTITY_TYPE_IDENTITY_ORGANIZATION, false, opts);
};
export const userRoles = async (context, _user, userId, opts) => {
const { orderBy, orderMode } = opts;
const platformUsers = await getEntitiesMapFromCache(context, SYSTEM_USER, ENTITY_TYPE_USER);
const userLoaded = platformUsers.get(userId);
if (orderBy) {
if (orderMode === 'desc') {
return R.sortWith([R.descend(R.prop(orderBy))])(userLoaded.roles);
}
return R.sortWith([R.ascend(R.prop(orderBy))])(userLoaded.roles);
}
return userLoaded.roles;
};
export const userGroupsPaginated = async (context, user, userId, opts) => {
return pageRegardingEntitiesConnection(context, user, userId, RELATION_MEMBER_OF, ENTITY_TYPE_GROUP, false, opts);
};
export const groupRolesPaginated = async (context, user, groupId, opts) => {
return pageRegardingEntitiesConnection(context, user, groupId, RELATION_HAS_ROLE, ENTITY_TYPE_ROLE, false, opts);
};
export const batchUserTokens = async (__, _, batchUsers) => {
const tokenIds = batchUsers.flatMap((u) => u.api_tokens ?? []).map((token) => token.id);
const tokensMap = await getTokensUsage(tokenIds);
return batchUsers.map((u) => (u.api_tokens ?? []).map((token) => ({ ...token, last_used_at: tokensMap[token.id] })));
};
export const batchRolesForUsers = async (context, user, userIds, opts = {}) => {
// Get all groups for users
const usersGroups = await fullRelationsList(context, user, RELATION_MEMBER_OF, { fromId: userIds, toTypes: [ENTITY_TYPE_GROUP] });
const groupIds = [];
const usersWithGroups = {};
usersGroups.forEach((userGroup) => {
if (!groupIds.includes(userGroup.toId)) {
groupIds.push(userGroup.toId);
}
if (usersWithGroups[userGroup.fromId]) {
usersWithGroups[userGroup.fromId] = [...usersWithGroups[userGroup.fromId], userGroup.toId];
} else {
usersWithGroups[userGroup.fromId] = [userGroup.toId];
}
});
// Get all roles for groups
const roleIds = [];
const groupWithRoles = {};
const groupsRoles = await fullRelationsList(context, user, RELATION_HAS_ROLE, { fromId: groupIds, toTypes: [ENTITY_TYPE_ROLE] });
groupsRoles.forEach((groupRole) => {
if (!roleIds.includes(groupRole.toId)) {
roleIds.push(groupRole.toId);
}
if (groupWithRoles[groupRole.fromId]) {
groupWithRoles[groupRole.fromId] = [...groupWithRoles[groupRole.fromId], groupRole.toId];
} else {
groupWithRoles[groupRole.fromId] = [groupRole.toId];
}
});
const roles = await fullEntitiesList(context, user, [ENTITY_TYPE_ROLE], { ...opts, ids: roleIds });
return userIds.map((u) => {
const groups = usersWithGroups[u] ?? [];
const idRoles = uniq(groups.map((g) => groupWithRoles[g] ?? []).flat());
return roles.filter((t) => idRoles.includes(t.internal_id));
});
};
export const computeAvailableMarkings = (userMarkings, allMarkings) => {
const computedMarkings = [];
for (let index = 0; index < userMarkings.length; index += 1) {
const userMarking = userMarkings[index];
// Find all marking of same type with rank <=
const findMarking = R.find((m) => m.id === userMarking.id, allMarkings);
if (isNotEmptyField(findMarking)) {
// Add the marking in the list
computedMarkings.push(findMarking);
// Compute accessible lower markings
const { x_opencti_order: order, definition_type: type } = findMarking;
const lowerMatchingMarkings = R.filter((m) => {
return userMarking.id !== m.id && m.definition_type === type && m.x_opencti_order <= order;
}, allMarkings);
pushAll(computedMarkings, lowerMatchingMarkings);
} else {
const error = { marking: userMarking, available_markings: allMarkings };
throw UnsupportedError('[ACCESS] USER MARKING INACCESSIBLE', { error });
}
}
return R.uniqBy((m) => m.id, computedMarkings);
};
// Return all the available markings a user can share
export const getAvailableDataSharingMarkings = async (context, user) => {
const maxMarkings = user.max_shareable_marking;
const allMarkings = await getEntitiesListFromCache(context, SYSTEM_USER, ENTITY_TYPE_MARKING_DEFINITION);
return computeAvailableMarkings(maxMarkings, allMarkings);
};
export const checkUserCanShareMarkings = async (context, user, markingsToShare) => {
const shareableMarkings = await getAvailableDataSharingMarkings(context, user);
const contentMaxMarkingsIsShareable = markingsToShare.every((m) => (
shareableMarkings.some((shareableMarking) => m.definition_type === shareableMarking.definition_type && m.x_opencti_order <= shareableMarking.x_opencti_order)));
if (!contentMaxMarkingsIsShareable) {
throw ForbiddenAccess('You are not allowed to share these markings', { markings: markingsToShare });
}
};
const getUserAndGlobalMarkings = async (context, userId, userGroups, userMarkings, capabilities) => {
const userCapabilities = capabilities.map((c) => c.name);
const shouldBypass = userCapabilities.includes(BYPASS) || userId === OPENCTI_ADMIN_UUID;
const allMarkingsPromise = getEntitiesListFromCache(context, SYSTEM_USER, ENTITY_TYPE_MARKING_DEFINITION);
const defaultGroupMarkingsPromise = defaultMarkingDefinitionsFromGroups(context, userGroups);
let computeUserMarkings;
let maxShareableMarkings;
const [all, defaultMarkings] = await Promise.all([allMarkingsPromise, defaultGroupMarkingsPromise]);
if (shouldBypass) { // Bypass user have all platform markings and can share all markings
computeUserMarkings = all;
maxShareableMarkings = all;
} else { // Standard user have markings related to his groups
computeUserMarkings = userMarkings;
const notShareableMarkings = userGroups.flatMap(({ max_shareable_markings }) => max_shareable_markings?.filter(({ value }) => value === 'none').map(({ type }) => type));
maxShareableMarkings = userGroups.flatMap(({ max_shareable_markings }) => max_shareable_markings?.filter(({ value }) => value !== 'none')).filter((m) => !!m);
const allShareableMarkings = all.filter(({ definition_type }) => (
!notShareableMarkings.includes(definition_type) && !maxShareableMarkings.some(({ type }) => type === definition_type)
)).filter(({ id }) => computeUserMarkings.some((m) => m.id === id)).map(({ id }) => id);
maxShareableMarkings = [...maxShareableMarkings.map(({ value }) => value), ...allShareableMarkings];
}
const computedMarkings = computeAvailableMarkings(computeUserMarkings, all);
return { user: computedMarkings, default: defaultMarkings, max_shareable: await cleanMarkings(context, maxShareableMarkings) };
};
export const roleCapabilities = async (context, user, roleId, relationshipType = RELATION_HAS_CAPABILITY) => {
return await fullEntitiesThroughRelationsToList(context, user, roleId, relationshipType, ENTITY_TYPE_CAPABILITY);
};
export const getDefaultHiddenTypes = (entities) => {
let userDefaultHiddenTypes = entities.map((entity) => entity.default_hidden_types).flat();
userDefaultHiddenTypes = uniq(userDefaultHiddenTypes.filter((type) => type !== undefined));
return userDefaultHiddenTypes;
};
export const findRoleById = (context, user, roleId) => {
return storeLoadById(context, user, roleId, ENTITY_TYPE_ROLE);
};
export const findRoles = (context, user, args) => {
return pageEntitiesConnection(context, user, [ENTITY_TYPE_ROLE], args);
};
export const findCapabilities = async (context, user, args, relationship_type = RELATION_HAS_CAPABILITY) => {
const filters = relationship_type === RELATION_HAS_CAPABILITY_IN_DRAFT
? addFilter(args.filters, 'name', CAPABILITIES_IN_DRAFT_NAMES)
: args.filters;
return await pageEntitiesConnection(context, user, [ENTITY_TYPE_CAPABILITY], {
...args,
filters,
orderBy: 'attribute_order',
});
};
export const findRolesWithCapabilityInDraft = async (context, user, args) => {
return R.uniqBy((relation) => relation.fromId,
await fullRelationsList(
context,
user,
RELATION_HAS_CAPABILITY_IN_DRAFT, {
...args,
fromTypes: [ENTITY_TYPE_ROLE],
toTypes: [ENTITY_TYPE_CAPABILITY],
}),
);
};
export const roleDelete = async (context, user, roleId) => {
const deleted = await deleteElementById(context, user, roleId, ENTITY_TYPE_ROLE);
await publishUserAction({
user,
event_type: 'mutation',
event_scope: 'delete',
event_access: 'administration',
message: `deletes role \`${deleted.name}\``,
context_data: { id: roleId, entity_type: ENTITY_TYPE_ROLE, input: deleted },
});
await roleUsersCacheRefresh(context, user, roleId);
return notify(BUS_TOPICS[ENTITY_TYPE_ROLE].DELETE_TOPIC, deleted, user).then(() => roleId);
};
export const roleCleanContext = async (context, user, roleId) => {
await delEditContext(user, roleId);
return storeLoadById(context, user, roleId, ENTITY_TYPE_ROLE).then((role) => {
return notify(BUS_TOPICS[ENTITY_TYPE_ROLE].EDIT_TOPIC, role, user);
});
};
export const roleEditContext = async (context, user, roleId, input) => {
await setEditContext(user, roleId, input);
return storeLoadById(context, user, roleId, ENTITY_TYPE_ROLE).then((role) => {
return notify(BUS_TOPICS[ENTITY_TYPE_ROLE].EDIT_TOPIC, role, user);
});
};
const isUserAdministratingOrga = (user, organizationId) => {
return user.administrated_organizations.some(({ id }) => id === organizationId);
};
const loadUserToUpdateWithAccessCheck = async (context, user, userId) => {
const userToUpdate = await internalLoadById(context, user, userId, { type: ENTITY_TYPE_USER });
if (!userToUpdate) {
throw FunctionalError(`${ENTITY_TYPE_USER} cannot be found.`, { userId });
}
if (!isUserHasCapability(user, SETTINGS_SET_ACCESSES) && user.id !== userId) {
// Check in an organization admin edits a user that's not in its administrated organizations
if (isOnlyOrgaAdmin(user)) {
const myAdministratedOrganizationsIds = user.administrated_organizations.map((orga) => orga.id);
if (!userToUpdate[RELATION_PARTICIPATE_TO]?.find((orga) => myAdministratedOrganizationsIds.includes(orga))) {
throw ForbiddenAccess();
}
} else {
throw ForbiddenAccess();
}
}
return userToUpdate;
};
export const assignOrganizationToUser = async (context, user, userId, organizationId) => {
if (isOnlyOrgaAdmin(user)) {
// When user is organization admin, we make sure she is also admin of organization added
if (!isUserAdministratingOrga(user, organizationId)) {
throw ForbiddenAccess();
}
}
// check the user is accessible
const targetUser = await loadUserToUpdateWithAccessCheck(context, user, userId);
const input = { fromId: userId, toId: organizationId, relationship_type: RELATION_PARTICIPATE_TO };
const created = await createRelation(context, user, input);
const actionEmail = ENABLED_DEMO_MODE ? REDACTED_USER.user_email : created.from.user_email;
await publishUserAction({
user,
event_type: 'mutation',
event_scope: 'update',
event_access: 'administration',
message: `adds ${created.toType} \`${extractEntityRepresentativeName(created.to)}\` to user \`${actionEmail}\``,
context_data: { id: targetUser.id, entity_type: ENTITY_TYPE_USER, input },
});
return notify(BUS_TOPICS[ENTITY_TYPE_USER].EDIT_TOPIC, targetUser, user);
};
export const assignOrganizationNameToUser = async (context, user, userId, organizationName) => {
const organization = { name: organizationName, identity_class: 'organization' };
const generateToId = generateStandardId(ENTITY_TYPE_IDENTITY_ORGANIZATION, organization);
return assignOrganizationToUser(context, user, userId, generateToId);
};
export const assignGroupToUser = async (context, user, userId, groupName) => {
const targetUser = await findById(context, user, userId);
if (!targetUser) {
throw FunctionalError('Cannot add the relation, User cannot be found.', { userId });
}
// No need for audit log here, only use for provider login
const generateToId = generateStandardId(ENTITY_TYPE_GROUP, { name: groupName });
const assignInput = {
fromId: userId,
toId: generateToId,
relationship_type: RELATION_MEMBER_OF,
};
const rel = await createRelation(context, user, assignInput);
await notify(BUS_TOPICS[ENTITY_TYPE_USER].EDIT_TOPIC, targetUser, user);
return rel;
};
export const checkPasswordInlinePolicy = (context, policy, password) => {
const {
password_policy_min_length,
password_policy_max_length,
password_policy_min_symbols,
password_policy_min_numbers,
password_policy_min_words,
password_policy_min_lowercase,
password_policy_min_uppercase,
} = policy;
const errors = [];
if (isEmptyField(password)) {
errors.push('required');
}
if (password_policy_min_length && password_policy_min_length > 0) {
if (password.length < password_policy_min_length) {
errors.push(`size must be >= ${password_policy_min_length}`);
}
}
if (password_policy_max_length && password_policy_max_length > 0) {
if (password.length > password_policy_max_length) {
errors.push(`size must be <= ${password_policy_max_length}`);
}
}
if (password_policy_min_symbols && password_policy_min_symbols > 0) {
if ((password.match(/[^a-zA-Z0-9]/g) ?? []).length < password_policy_min_symbols) {
errors.push(`number of symbols must be >= ${password_policy_min_symbols}`);
}
}
if (password_policy_min_numbers && password_policy_min_numbers > 0) {
if ((password.match(/[0-9]/g) ?? []).length < password_policy_min_numbers) {
errors.push(`number of digits must be >= ${password_policy_min_numbers}`);
}
}
if (password_policy_min_words && password_policy_min_words > 0) {
if (password.split(/[|, _-]/).length < password_policy_min_words) {
errors.push(`number of words must be >= ${password_policy_min_words}`);
}
}
if (password_policy_min_lowercase && password_policy_min_lowercase > 0) {
if ((password.match(/[a-z]/g) ?? []).length < password_policy_min_lowercase) {
errors.push(`number of lower chars must be >= ${password_policy_min_lowercase}`);
}
}
if (password_policy_min_uppercase && password_policy_min_uppercase > 0) {
if ((password.match(/[A-Z]/g) ?? []).length < password_policy_min_uppercase) {
errors.push(`number of upper chars must be >= ${password_policy_min_uppercase}`);
}
}
return errors;
};
export const checkPasswordFromPolicy = async (context, password) => {
const settings = await getEntityFromCache(context, SYSTEM_USER, ENTITY_TYPE_SETTINGS);
const errors = checkPasswordInlinePolicy(context, settings, password);
if (errors.length > 0) {
throw FunctionalError(`Invalid password: ${errors.join(', ')}`);
}
};
export const sendEmailToUser = async (context, user, input) => {
await checkEnterpriseEdition(context);
const settings = await getEntityFromCache(context, user, ENTITY_TYPE_SETTINGS);
const users = await getEntitiesListFromCache(context, user, ENTITY_TYPE_USER);
const targetUser = users.find((usr) => input.target_user_id === usr.id || input.target_user_id === usr.standard_id);
if (!targetUser) {
throw UnsupportedError('Target user not found', { id: input.target_user_id });
}
const organizationNames = (targetUser.organizations ?? []).map((org) => org.name);
const emailTemplate = await internalLoadById(context, user, input.email_template_id);
if (!emailTemplate || emailTemplate.entity_type !== ENTITY_TYPE_EMAIL_TEMPLATE) {
throw UnsupportedError('Invalid email template', { id: input.email_template_id });
}
const templateUser = {
...sanitizeUser(targetUser),
api_token: '', // empty token by default
account_lock_after_date: targetUser.account_lock_after_date
? DateTime.fromISO(targetUser.account_lock_after_date).toFormat('yyyy-MM-dd') : '',
};
// If the template asks for a user token, we need to generate a new one.
if (emailTemplate.template_body.includes('$user.api_token')) {
const inputToken = { name: 'Template generated token' };
const token = await addUserTokenByAdmin(context, user, input.target_user_id, inputToken);
templateUser.api_token = token.plaintext_token;
}
const preprocessedTemplate = emailTemplate.template_body
.replace(/\$user\.firstname/g, '<%= user.firstname %>')
.replace(/\$user\.lastname/g, '<%= user.lastname %>')
.replace(/\$user\.name/g, '<%= user.name %>')
.replace(/\$user\.user_email/g, '<%= user.user_email %>')
.replace(/\$user\.api_token/g, '<%= user.api_token %>')
.replace(/\$user\.account_status/g, '<%= user.account_status %>')
.replace(/\$user\.objectOrganization/g, '<%= organizationNames.join(", ") %>')
.replace(/\$user\.account_lock_after_date/g, '<%= user.account_lock_after_date %>')
.replace(/\$settings\.platform_url/g, '<%= platformUrl %>');
const renderedHtml = await safeRender(preprocessedTemplate, {
platformUrl: settings.platform_url,
user: templateUser,
organizationNames,
});
const sendMailArgs = {
from: await smtpComputeFrom(emailTemplate.sender_email),
to: targetUser.user_email,
subject: emailTemplate.email_object,
html: renderedHtml,
};
await sendMail(sendMailArgs, {
identifier: `user-${targetUser.id}`,
category: 'user-notification',
});
await addUserEmailSendCount();
await publishUserAction({
user,
event_type: 'command',
event_scope: 'send',
event_access: 'administration',
context_data: {
id: targetUser.id,
entity_type: ENTITY_TYPE_USER,
entity_name: targetUser.name,
input: {
...input,
to: targetUser.user_email,
},
},
});
return true;
};
export const addUser = async (context, user, newUser) => {
let userEmail;
const userServiceAccount = newUser.user_service_account;
if (newUser.user_email && !userServiceAccount) {
userEmail = newUser.user_email.toLowerCase();
const existingUser = await elLoadBy(context, SYSTEM_USER, 'user_email', userEmail, ENTITY_TYPE_USER);
if (existingUser) {
throw FunctionalError('User already exists', { user_id: existingUser.internal_id });
}
} else if (userServiceAccount) {
userEmail = newUser.user_email ? newUser.user_email : `automatic+${uuid()}@opencti.invalid`;
} else {
throw FunctionalError('User cannot be created without email');
}
if (isUserHasCapability(user, VIRTUAL_ORGANIZATION_ADMIN) && !isUserHasCapability(user, SETTINGS_SET_ACCESSES)) {
// user is Organization Admin
// Check organization
const myOrganizationIds = user.administrated_organizations.map((organization) => organization.id);
if (newUser.objectOrganization.length === 0 || !newUser.objectOrganization.every((orga) => myOrganizationIds.includes(orga))) {
throw ForbiddenAccess();
}
const myGroupIds = R.uniq(user.administrated_organizations.map((orga) => orga.grantable_groups).flat());
if (!newUser.groups.every((group) => myGroupIds.includes(group))) {
throw ForbiddenAccess();
}
}
// Create the user
let userPassword = newUser.password;
// If user is external and password is not specified, associate a random password
if ((newUser.external === true && isEmptyField(userPassword)) || userServiceAccount) {
userPassword = uuid();
} else { // If local user, check the password policy
await checkPasswordFromPolicy(context, userPassword);
}
let userToCreate = R.pipe(
R.assoc('user_email', userEmail),
R.assoc('password', bcrypt.hashSync(userPassword)),
R.assoc('theme', newUser.theme ? newUser.theme : 'default'),
R.assoc('language', newUser.language ? newUser.language : 'auto'),
R.assoc('external', newUser.external ? newUser.external : false),
R.assoc('account_status', newUser.account_status ? newUser.account_status : DEFAULT_ACCOUNT_STATUS),
R.assoc('account_lock_after_date', newUser.account_lock_after_date),
R.assoc('unit_system', newUser.unit_system),
R.assoc('user_confidence_level', newUser.user_confidence_level ?? null), // can be null
R.assoc('personal_notifiers', [STATIC_NOTIFIER_UI, STATIC_NOTIFIER_EMAIL]),
R.dissoc('roles'),
R.dissoc('groups'),
R.dissoc('prevent_default_groups'),
R.dissoc('email_template_id'),
)(newUser);
userToCreate = {
...userToCreate,
user_service_account: newUser.user_service_account || false,
};
if (userServiceAccount) {
userToCreate = {
...userToCreate,
password: undefined,
};
}
const { element, isCreation } = await createEntity(context, user, userToCreate, ENTITY_TYPE_USER, { complete: true });
// Link to organizations
const userOrganizations = newUser.objectOrganization ?? [];
const relationOrganizations = userOrganizations.map((organizationId) => ({
fromId: element.id,
toId: organizationId,
relationship_type: RELATION_PARTICIPATE_TO,
}));
await Promise.all(relationOrganizations.map((relation) => createRelation(context, user, relation)));
// Add the provided groups
let relationGroups = [];
if ((newUser.groups ?? []).length > 0) {
relationGroups = (newUser.groups ?? []).map((group) => ({
fromId: element.id,
toId: group,
relationship_type: RELATION_MEMBER_OF,
}));
}
// if prevent_default_groups is not true, assign the default groups to the user
if (newUser.prevent_default_groups !== true) {
const defaultAssignationFilter = {
mode: 'and',
filters: [{ key: 'default_assignation', values: [true] }],
filterGroups: [],
};
const defaultGroups = await findGroups(context, user, { filters: defaultAssignationFilter });
const relationDefaultGroups = defaultGroups.edges
.filter((e) => !(newUser.groups ?? []).includes(e.node.internal_id)) // remove groups already in new user group input
.map((e) => ({
fromId: element.id,
toId: e.node.internal_id,
relationship_type: RELATION_MEMBER_OF,
}));
relationGroups = [...relationGroups, ...relationDefaultGroups];
}
await Promise.all(relationGroups.map((relation) => createRelation(context, user, relation)));
// Audit log
if (isCreation) {
const actionEmail = ENABLED_DEMO_MODE ? REDACTED_USER.user_email : newUser.user_email;
await publishUserAction({
user,
event_type: 'mutation',
event_scope: 'create',
event_access: 'administration',
message: `creates user \`${actionEmail}\``,
context_data: { id: element.id, entity_type: ENTITY_TYPE_USER, input: newUser },
});
}
await notify(BUS_TOPICS[ENTITY_TYPE_USER].ADDED_TOPIC, element, user);
if (newUser.email_template_id) {
const input = {
target_user_id: element.id,
email_template_id: newUser.email_template_id,
};
try {
await sendEmailToUser(context, user, input);
} catch (_err) {
logApp.error('Error sending email on user creation', { createdUserID: user.id, emailTemplateId: newUser.email_template_id });
}
}
return element;
};
export const roleEditField = async (context, user, roleId, input) => {
const { element } = await updateAttribute(context, user, roleId, ENTITY_TYPE_ROLE, input);
await publishUserAction({
user,
event_type: 'mutation',
event_scope: 'update',
event_access: 'administration',
message: `updates \`${input.map((i) => i.key).join(', ')}\` for role \`${element.name}\``,
context_data: { id: roleId, entity_type: ENTITY_TYPE_ROLE, input },
});
await roleUsersCacheRefresh(context, user, roleId);
return notify(BUS_TOPICS[ENTITY_TYPE_ROLE].EDIT_TOPIC, element, user);
};
export const roleAddRelation = async (context, user, roleId, input) => {
const role = await storeLoadById(context, user, roleId, ENTITY_TYPE_ROLE);
if (!role) {
throw FunctionalError(`Cannot add the relation, ${ENTITY_TYPE_ROLE} cannot be found.`, { id: roleId });
}
if (!isInternalRelationship(input.relationship_type)) {
throw FunctionalError(`Only ${ABSTRACT_INTERNAL_RELATIONSHIP} can be added through this method, got ${input.relationship_type}.`);
}
const finalInput = R.assoc('fromId', roleId, input);
const relationData = await createRelation(context, user, finalInput);
await publishUserAction({
user,
event_type: 'mutation',
event_scope: 'update',
event_access: 'administration',
message: `adds ${relationData.to.entity_type} \`${extractEntityRepresentativeName(relationData.to)}\` for role \`${role.name}\``,
context_data: { id: roleId, entity_type: ENTITY_TYPE_ROLE, input: finalInput },
});
await roleUsersCacheRefresh(context, user, roleId);
if (input.relationship_type === RELATION_HAS_CAPABILITY_IN_DRAFT) {
await addCapabilitiesInDraftUpdatedCount();
}
return notify(BUS_TOPICS[ENTITY_TYPE_ROLE].EDIT_TOPIC, relationData, user);
};
export const roleDeleteRelation = async (context, user, roleId, toId, relationshipType) => {
const role = await storeLoadById(context, user, roleId, ENTITY_TYPE_ROLE);
if (!role) {
throw FunctionalError('Cannot delete the relation, Role cannot be found.', { id: roleId });
}
if (!isInternalRelationship(relationshipType)) {
throw FunctionalError(`Only ${ABSTRACT_INTERNAL_RELATIONSHIP} can be deleted through this method, got ${relationshipType}.`);
}
const deleted = await deleteRelationsByFromAndTo(context, user, roleId, toId, relationshipType, ABSTRACT_INTERNAL_RELATIONSHIP);
const input = { fromId: roleId, toId, relationship_type: relationshipType };
await publishUserAction({
user,
event_type: 'mutation',
event_scope: 'update',
event_access: 'administration',
message: `removes ${deleted.to.entity_type} \`${extractEntityRepresentativeName(deleted.to)}\` for role \`${role.name}\``,
context_data: { id: roleId, entity_type: ENTITY_TYPE_ROLE, input },
});
await roleUsersCacheRefresh(context, user, roleId);
if (input.relationship_type === RELATION_HAS_CAPABILITY_IN_DRAFT) {
await addCapabilitiesInDraftUpdatedCount();
}
return notify(BUS_TOPICS[ENTITY_TYPE_ROLE].EDIT_TOPIC, role, user);
};
// User related
export const userEditField = async (context, user, userId, rawInputs) => {
const inputs = [];
const userToUpdate = await loadUserToUpdateWithAccessCheck(context, user, userId);
let skipThisInput = false;
for (let index = 0; index < rawInputs.length; index += 1) {
const input = rawInputs[index];
if (userToUpdate.external && input.key === 'name') {
throw FunctionalError('Name cannot be updated for external user', { userId });
}
if (userToUpdate.external && input.key === 'user_email') {
throw FunctionalError('Email cannot be updated for external user', { userId });
}
if (input.key === 'password') {
const userServiceAccountInput = rawInputs.find((x) => x.key === 'user_service_account');
if (userServiceAccountInput && userToUpdate.user_service_account !== userServiceAccountInput.value[0]) {
skipThisInput = true;
}
if (!userToUpdate.user_service_account) {
const userPassword = R.head(input.value).toString();
await checkPasswordFromPolicy(context, userPassword);
input.value = [bcrypt.hashSync(userPassword)];
} else {
throw FunctionalError('Cannot update password for Service account', { userId });
}
}
if (input.key === 'account_status') {
// If account status is not active, kill all current user sessions
if (R.head(input.value) !== ACCOUNT_STATUS_ACTIVE) {
await killUserSessions(userId);
}
// If moving to unexpired status and expiration date is already in the past, reset the value
if (R.head(input.value) !== ACCOUNT_STATUS_EXPIRED && userToUpdate.account_lock_after_date
&& utcDate().isAfter(userToUpdate.account_lock_after_date)) {
inputs.push({ key: 'account_lock_after_date', value: [null] });
}
}
if (input.key === 'account_lock_after_date' && utcDate().isAfter(utcDate(R.head(input.value)))) {
inputs.push({ key: 'account_status', value: [ACCOUNT_STATUS_EXPIRED] });
await killUserSessions(userId);
}
if (input.key === 'draft_context') {
// draft context might have changed, we need to check draft context exists and refresh session info
const draftContext = R.head(input.value)?.toString();
if (draftContext?.length > 0) {
const draftWorkspaces = await getEntitiesMapFromCache(context, SYSTEM_USER, ENTITY_TYPE_DRAFT_WORKSPACE);
const draftWorkspace = draftWorkspaces.get(draftContext);
if (!draftWorkspace) throw DraftLockedError('Could not find draft workspace');
if (draftWorkspace.draft_status !== DRAFT_STATUS_OPEN) throw DraftLockedError('Can not move to a draft not in an open state');
}
}
if (input.key === 'unit_system') {
const unit = R.head(input.value).toString();
if (!Object.keys(UnitSystem).map((option) => option.toLowerCase()).includes(unit.toLowerCase())) {
throw UnsupportedError('Unsupported unit system', { unit });
}
}
// Check language is valid in case of language change
if (input.key === 'language') {
if (!(input.value.length === 1 && AVAILABLE_LANGUAGES.includes(input.value[0]))) {
throw FunctionalError('The language you have provided is not valid');
}
}
// Turn User into Service Account
if (input.key === 'user_service_account' && !userToUpdate.user_service_account && input.value[0] === true) {
inputs.push({ key: 'password', value: [null] });
await addUserIntoServiceAccountCount();
}
// Turn Service Account into User
if (input.key === 'user_service_account' && userToUpdate.user_service_account && input.value[0] === false) {
const userPassword = uuid();
await checkPasswordFromPolicy(context, userPassword);
inputs.push({ key: 'password', value: [bcrypt.hashSync(userPassword)] });
await addServiceAccountIntoUserCount();
}
if (!skipThisInput) {
inputs.push(input);
}
}
const { element } = await updateAttribute(context, user, userId, ENTITY_TYPE_USER, inputs);
const input = updatedInputsToData(element, inputs);
const personalUpdate = user.id === userId;
const actionEmail = ENABLED_DEMO_MODE ? REDACTED_USER.user_email : element.user_email;
await publishUserAction({
user,