-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathResourceDetailsAccessPolicyTab.tsx
More file actions
842 lines (782 loc) · 25.1 KB
/
ResourceDetailsAccessPolicyTab.tsx
File metadata and controls
842 lines (782 loc) · 25.1 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
import React, { useState, useEffect } from "react";
import RenderMultiField from "../wizard/RenderMultiField";
import {
Acl,
Role,
fetchAclActions,
fetchAclDefaults,
fetchAclTemplates,
fetchRolesWithTarget,
} from "../../../slices/aclSlice";
import Notifications from "../Notifications";
import { Formik, FieldArray, FormikErrors, FormikProps } from "formik";
import { Field } from "../Field";
import { NOTIFICATION_CONTEXT } from "../../../configs/modalConfig";
import {
prepareAccessPolicyRulesForPost,
} from "../../../utils/resourceUtils";
import { getUserInformation } from "../../../selectors/userInfoSelectors";
import { hasAccess } from "../../../utils/utils";
import DropDown from "../DropDown";
import { getAclTemplateText, handleTemplateChange, policiesFiltered, rolesFiltered } from "../../../utils/aclUtils";
import { useAppDispatch, useAppSelector } from "../../../store";
import { removeNotificationWizardForm, addNotification } from "../../../slices/notificationSlice";
import { useTranslation } from "react-i18next";
import { TransformedAcl } from "../../../slices/aclDetailsSlice";
import { AsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { SaveEditFooter } from "../SaveEditFooter";
import { UserInfoState } from "../../../slices/userInfoSlice";
import { ParseKeys } from "i18next";
import ButtonLikeAnchor from "../ButtonLikeAnchor";
import { formatAclTemplatesForDropdown } from "../../../utils/dropDownUtils";
import ModalContentTable from "./ModalContentTable";
import { getAclDefaults } from "../../../selectors/aclSelectors";
import { LuCircleX } from "react-icons/lu";
/**
* This component manages the access policy tab of resource details modals
*/
type AclTemplate = {
id: string,
value: string
}
const ResourceDetailsAccessPolicyTab = ({
resourceId,
header,
policies,
policyTemplateId,
fetchHasActiveTransactions,
fetchAccessPolicies,
saveNewAccessPolicies,
descriptionText,
buttonText,
policyTableHeaderText,
policyTableRoleText,
policyTableNewText,
userPolicyTableHeaderText,
userPolicyTableRoleText,
userPolicyTableNewText,
editAccessRole,
viewUsersAccessRole,
viewNonUsersAccessRole,
policyChanged,
setPolicyChanged,
withOverrideButton,
}: {
resourceId: string,
header: ParseKeys,
policies: TransformedAcl[],
policyTemplateId: number,
fetchHasActiveTransactions?: AsyncThunk<{ active: boolean }, string, any>
fetchAccessPolicies: AsyncThunk<any, string, any>,
saveNewAccessPolicies: AsyncThunk<boolean, { id: string, policies: { acl: Acl }, override?: boolean }, any>
descriptionText: ParseKeys,
buttonText: ParseKeys,
policyTableHeaderText: ParseKeys,
policyTableRoleText: ParseKeys,
policyTableNewText: ParseKeys,
userPolicyTableHeaderText: ParseKeys,
userPolicyTableRoleText: ParseKeys,
userPolicyTableNewText: ParseKeys,
editAccessRole: string,
viewUsersAccessRole: string,
viewNonUsersAccessRole: string,
policyChanged: boolean,
setPolicyChanged: (value: boolean) => void,
withOverrideButton?: boolean
}) => {
const { t } = useTranslation();
const dispatch = useAppDispatch();
// list of policy templates
const [aclTemplates, setAclTemplates] = useState<AclTemplate[]>([]);
// list of possible additional actions
const [aclActions, setAclActions] = useState<{ id: string, value: string }[]>([]);
// shows, whether a resource has additional actions on top of normal read and write rights
const [hasActions, setHasActions] = useState(false);
// list of possible roles
const [roles, setRoles] = useState<Role[]>([]);
// this state is used, because the policies should be read-only, if a transaction is currently being performed on a resource
const [transactions, setTransactions] = useState({ readOnly: false });
// this state tracks, whether data is currently being fetched
const [loading, setLoading] = useState(false);
const user = useAppSelector(state => getUserInformation(state));
/* fetch initial values from backend */
useEffect(() => {
dispatch(removeNotificationWizardForm());
async function fetchData() {
setLoading(true);
const [responseTemplates, responseActions] = await Promise.all([
fetchAclTemplates(), fetchAclActions(), dispatch(fetchAccessPolicies(resourceId))]);
setAclTemplates(responseTemplates);
setAclActions(responseActions);
setHasActions(responseActions.length > 0);
fetchRolesWithTarget("ACL").then(roles => setRoles(roles));
if (fetchHasActiveTransactions) {
const fetchTransactionResult = await dispatch(fetchHasActiveTransactions(resourceId)).then(unwrapResult);
if (fetchTransactionResult.active !== undefined) {
setTransactions({ readOnly: fetchTransactionResult.active });
} else {
setTransactions({ readOnly: true });
}
if (
fetchTransactionResult.active === undefined ||
fetchTransactionResult.active
) {
dispatch(addNotification({
type: "warning",
key: "ACTIVE_TRANSACTION",
duration: -1,
context: NOTIFICATION_CONTEXT,
noDuplicates: true,
}));
}
}
setLoading(false);
}
fetchData().then(() => {});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
/* resets the formik form and hides the save and cancel buttons */
const resetPolicies = (resetFormik: () => void) => {
setPolicyChanged(false);
resetFormik();
};
/* transforms rules into proper format for saving and checks validity
* if the policies are valid, the new policies are saved in the backend */
const saveAccess = (values: { policies: TransformedAcl[] }, override: boolean) => {
dispatch(removeNotificationWizardForm());
const { roleWithFullRightsExists, allRulesValid } = validatePolicies(
values,
);
const access = prepareAccessPolicyRulesForPost(values.policies);
if (!allRulesValid) {
dispatch(addNotification({
type: "warning",
key: "INVALID_ACL_RULES",
duration: -1,
context: NOTIFICATION_CONTEXT,
}));
}
if (!roleWithFullRightsExists) {
dispatch(addNotification({
type: "warning",
key: "MISSING_ACL_RULES",
duration: -1,
context: NOTIFICATION_CONTEXT,
}));
}
if (allRulesValid && roleWithFullRightsExists) {
dispatch(saveNewAccessPolicies({ id: resourceId, policies: access, override: override })).then(success => {
// fetch new policies from the backend, if save successful
if (success) {
setPolicyChanged(false);
dispatch(fetchAccessPolicies(resourceId));
}
});
}
};
/* validates the policies in the formik form */
const validateFormik = (values: { policies: TransformedAcl[] }) => {
const errors: FormikErrors<{ emptyRole: string }> = {};
setPolicyChanged(isPolicyChanged(values.policies));
// each policy needs a role
if (values.policies.find(policy => !policy.role || policy.role === "")) {
errors.emptyRole = "Empty role!";
}
return errors;
};
/* checks validity of the policies
* each policy needs a role and at least one of: read-rights, write-rights, additional action
* if not admin, there needs to be at least one role, which has both read and write rights */
const validatePolicies = (values: { policies: TransformedAcl[] }) => {
let roleWithFullRightsExists = false;
let allRulesValid = true;
values.policies.forEach(policy => {
if ((policy.read && policy.write) || user.isAdmin) {
roleWithFullRightsExists = true;
}
if (
(!policy.read && !policy.write && policy.actions.length === 0) ||
!policy.role ||
policy.role === ""
) {
allRulesValid = false;
}
});
return { roleWithFullRightsExists, allRulesValid };
};
/* checks whether the current state of the policies from the formik is different form the
* initial policies or equal to them */
const isPolicyChanged = (newPolicies: TransformedAcl[]) => {
if (newPolicies.length !== policies.length) {
return true;
}
const sortSchema = (pol1: TransformedAcl, pol2: TransformedAcl) => {
return pol1.role > pol2.role ? 1 : -1;
};
const sortedNewPolicies = [...newPolicies].sort(sortSchema);
const sortedInitialPolicies = [...policies].sort(sortSchema);
for (let i = 0; i < sortedNewPolicies.length; i++) {
if (
sortedNewPolicies[i].role !== sortedInitialPolicies[i].role ||
sortedNewPolicies[i].read !== sortedInitialPolicies[i].read ||
sortedNewPolicies[i].write !== sortedInitialPolicies[i].write ||
sortedNewPolicies[i].actions.length !==
sortedInitialPolicies[i].actions.length
) {
return true;
}
if (
sortedNewPolicies[i].actions.length > 0 &&
sortedNewPolicies[i].actions.length ===
sortedInitialPolicies[i].actions.length
) {
for (let j = 0; j < sortedNewPolicies[i].actions.length; j++) {
if (
sortedNewPolicies[i].actions[j] !==
sortedInitialPolicies[i].actions[j]
) {
return true;
}
}
}
}
return false;
};
return (
<ModalContentTable>
{/* Notifications */}
<Notifications context="not_corner" />
{!loading && !!policies && (
<ul>
<li>
<Formik
initialValues={{
policies: policies.length > 0 ? [...policies] : [],
aclTemplate: policyTemplateId ? policyTemplateId.toString() : "",
}}
enableReinitialize
validate={values => validateFormik(values)}
onSubmit={values =>
saveAccess(values, false)
}
>
{formik => (
<div className="obj list-obj">
<header>{t(header) /* Access Policy */}</header>
{/* policy templates */}
<TemplateSelector
formik={formik}
editAccessRole={editAccessRole}
titleText={"EVENTS.EVENTS.DETAILS.ACCESS.TEMPLATES.TITLE"}
descriptionText={descriptionText}
buttonText={buttonText}
emptyText={"EVENTS.EVENTS.DETAILS.ACCESS.ACCESS_POLICY.EMPTY"}
transactions={transactions}
aclTemplates={aclTemplates}
defaultUser={user}
/>
{roles.length > 0 && !roles[0].isSanitize &&
<>
{hasAccess(viewUsersAccessRole, user) &&
<AccessPolicyTable
isUserTable={true}
policiesFiltered={policiesFiltered(formik.values.policies, true)}
rolesFilteredbyPolicies={rolesFiltered(roles, true)}
header={userPolicyTableHeaderText}
firstColumnHeader={userPolicyTableRoleText}
createLabel={userPolicyTableNewText}
formik={formik}
hasActions={hasActions}
transactions={transactions}
aclActions={aclActions}
roles={roles}
editAccessRole={editAccessRole}
/>
}
{hasAccess(viewNonUsersAccessRole, user) &&
<AccessPolicyTable
isUserTable={false}
policiesFiltered={policiesFiltered(formik.values.policies, false)}
rolesFilteredbyPolicies={rolesFiltered(roles, false)}
header={policyTableHeaderText}
firstColumnHeader={policyTableRoleText}
createLabel={policyTableNewText}
formik={formik}
hasActions={hasActions}
transactions={transactions}
aclActions={aclActions}
roles={roles}
editAccessRole={editAccessRole}
/>
}
</>
}
{roles.length > 0 && roles[0].isSanitize &&
<>
<AccessPolicyTable
isUserTable={false}
policiesFiltered={formik.values.policies}
rolesFilteredbyPolicies={roles}
header={policyTableHeaderText}
firstColumnHeader={policyTableRoleText}
createLabel={policyTableNewText}
formik={formik}
hasActions={hasActions}
transactions={transactions}
aclActions={aclActions}
roles={roles}
editAccessRole={editAccessRole}
/>
<div className="obj-container">
<span>
{t("EVENTS.EVENTS.DETAILS.ACCESS.ACCESS_POLICY.SANITIZATION_NOTE")}
</span>
</div>
</>
}
{/* Save and cancel buttons */}
{!transactions.readOnly && <SaveEditFooter
active={policyChanged && formik.dirty}
reset={() => resetPolicies(formik.resetForm)}
submit={() => saveAccess(formik.values, false)}
isValid={formik.isValid}
additionalButton={withOverrideButton ? {
label: "EVENTS.SERIES.DETAILS.ACCESS.ACCESS_POLICY.REPLACE_EVENT_ACLS",
hint: "EVENTS.SERIES.DETAILS.ACCESS.ACCESS_POLICY.REPLACE_EVENT_ACLS_HINT",
onClick: () => saveAccess(formik.values, true),
} : undefined}
customSaveButtonText={withOverrideButton ? "EVENTS.SERIES.DETAILS.ACCESS.ACCESS_POLICY.SAVE_SERIES_ACL_ONLY" : undefined}
/>}
</div>
)}
</Formik>
</li>
</ul>
)}
</ModalContentTable>
);
};
export default ResourceDetailsAccessPolicyTab;
type AccessPolicyTabFormikProps = {
policies: TransformedAcl[]
}
export const AccessPolicyTable = <T extends AccessPolicyTabFormikProps>({
isUserTable,
policiesFiltered,
rolesFilteredbyPolicies,
header,
firstColumnHeader,
createLabel,
formik,
hasActions,
transactions,
aclActions,
roles,
editAccessRole,
}: {
isUserTable: boolean
policiesFiltered: TransformedAcl[]
rolesFilteredbyPolicies: Role[]
header?: ParseKeys
firstColumnHeader: ParseKeys
createLabel: ParseKeys,
formik: FormikProps<T>,
hasActions: boolean
transactions: { readOnly: boolean }
aclActions: { id: string, value: string }[]
roles: Role[]
editAccessRole: string
}) => {
const { t } = useTranslation();
const dispatch = useAppDispatch();
const user = useAppSelector(state => getUserInformation(state));
const aclDefaults = useAppSelector(state => getAclDefaults(state));
useEffect(() => {
dispatch(fetchAclDefaults());
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const createPolicy = (role: string, withUser: boolean): TransformedAcl => {
const user = withUser ? { username: "", name: "", email: "" } : undefined;
const newRole: TransformedAcl = {
role: role,
read: true,
write: false,
actions: [],
user: user,
};
// If config exists, set defaults according to config
if (aclDefaults) {
if (aclDefaults["read_enabled"] && aclDefaults["read_enabled"] === "true") {
newRole.read = true;
} else if (aclDefaults["read_enabled"] && aclDefaults["read_enabled"] === "false") {
newRole.read = false;
}
if (aclDefaults["write_enabled"] && aclDefaults["write_enabled"] === "true") {
newRole.write = true;
} else if (aclDefaults["write_enabled"] && aclDefaults["write_enabled"] === "false") {
newRole.write = false;
}
if (aclDefaults["default_actions"]) {
newRole.actions = newRole.actions.concat(aclDefaults["default_actions"].split(","));
}
}
return newRole;
};
// Filter available options by custom prefixes from the config
if (aclDefaults) {
if (aclDefaults["display_role_filter_prefixes"]) {
const prefixes = aclDefaults["display_role_filter_prefixes"].split(",");
rolesFilteredbyPolicies = rolesFilteredbyPolicies.filter(role =>
!prefixes.some(prefix => role.name.startsWith(prefix)),
);
}
}
return (
<>
{/* list of policy details and interface for changing them */}
<div className="obj-container">
<div className="obj tbl-list">
<header>
{header ? t(header) : undefined}
</header>
<div className="obj-container">
<table className="main-tbl">
{/* column headers */}
<thead>
<tr>
<th>
{
t(
firstColumnHeader,
) /* <!-- Role --> */
}
</th>
<th>
{
t(
"EVENTS.EVENTS.DETAILS.ACCESS.ACCESS_POLICY.READ",
) /* <!-- Read --> */
}
</th>
<th>
{
t(
"EVENTS.EVENTS.DETAILS.ACCESS.ACCESS_POLICY.WRITE",
) /* <!-- Write --> */
}
</th>
{hasActions && (
<th>
{
t(
"EVENTS.SERIES.DETAILS.ACCESS.ACCESS_POLICY.ADDITIONAL_ACTIONS",
) /* <!-- Additional Actions --> */
}
</th>
)}
{hasAccess(editAccessRole, user) && (
<th>
{
t(
"EVENTS.EVENTS.DETAILS.ACCESS.ACCESS_POLICY.ACTION",
) /* <!-- Action --> */
}
</th>
)}
</tr>
</thead>
<tbody>
{/* list of policies */}
<FieldArray
name={"policies"}
render={arrayHelpers => (
<>
{formik.values.policies.length > 0 &&
policiesFiltered.map(
(policy, index) => (
<tr key={index}>
{/* dropdown for policy.role */}
<td className="editable">
{!transactions.readOnly ? (
<DropDown
value={policy.role}
text={createPolicyLabel(policy)}
options={
roles.length > 0
? formatAclRolesForDropdown(rolesFilteredbyPolicies)
: []
}
required={true}
creatable={true}
handleChange={element => {
if (element) {
const matchingRole = roles.find(role => role.name === element.value);
formik.setFieldValue(`policies.${index}.role`, element.value);
formik.setFieldValue(
`policies.${index}.user`,
matchingRole ? matchingRole.user : undefined,
);
}
}}
placeholder={
t("EVENTS.EVENTS.DETAILS.ACCESS.ROLES.LABEL")
}
disabled={
!hasAccess(
editAccessRole,
user,
)
}
skipTranslate
optionHeight={35}
customCSS={{ width: "100%", optionPaddingTop: 5 }}
/>
) : (
<p>{policy.role}</p>
)}
</td>
{/* Checkboxes for policy.read and policy.write */}
<td className="text-center">
<Field
type="checkbox"
name={`policies.${formik.values.policies.findIndex(p => p === policy)}.read`}
disabled={
transactions.readOnly ||
!hasAccess(
editAccessRole,
user,
) ||
(aclDefaults && aclDefaults["read_readonly"] !== "false")
}
className={`${
transactions.readOnly
? "disabled"
: "false"
}`}
onChange={(read: React.ChangeEvent<HTMLInputElement>) =>
formik.setFieldValue(`policies.${index}.read`, read.target.checked)
}
/>
</td>
<td className="text-center">
<Field
type="checkbox"
name={`policies.${formik.values.policies.findIndex(p => p === policy)}.write`}
disabled={
transactions.readOnly ||
!hasAccess(
editAccessRole,
user,
) ||
(aclDefaults
&& aclDefaults["write_readonly"]
&& aclDefaults["write_readonly"] === "true")
}
className={`${
transactions.readOnly
? "disabled"
: "false"
}`}
onChange={(write: React.ChangeEvent<HTMLInputElement>) =>
formik.setFieldValue(`policies.${index}.write`, write.target.checked)
}
/>
</td>
{/* Multi value field for policy.actions (additional actions) */}
{hasActions && (
<td className="editable">
{!transactions.readOnly &&
hasAccess(
editAccessRole,
user,
) && (
<div>
<Field
fieldInfo={{
id: `policies.${formik.values.policies.findIndex(p => p === policy)}.actions`,
type: "mixed_text",
collection: aclActions,
}}
onlyCollectionValues
name={`policies.${formik.values.policies.findIndex(p => p === policy)}.actions`}
component={
RenderMultiField
}
/>
</div>
)}
{(transactions.readOnly ||
!hasAccess(
editAccessRole,
user,
)) &&
policy.actions.map(
(
customAction,
actionKey,
) => (
<div key={actionKey}>
{customAction}
</div>
),
)}
</td>
)}
{/* Remove policy */}
{hasAccess(
editAccessRole,
user,
) && (
<td>
{!transactions.readOnly && (
<ButtonLikeAnchor
onClick={() =>
arrayHelpers.remove(formik.values.policies.findIndex(p => p === policy))
}
className="action-cell-button remove"
>
<LuCircleX />
</ButtonLikeAnchor>
)}
</td>
)}
</tr>
),
)}
{/* create additional policy */}
{!transactions.readOnly &&
hasAccess(editAccessRole, user) && (
<tr>
<td colSpan={5}>
<ButtonLikeAnchor
onClick={() =>
arrayHelpers.push(createPolicy("", isUserTable))
}
>
+{" "}
{t(createLabel)}
</ButtonLikeAnchor>
</td>
</tr>
)}
</>
)}
/>
</tbody>
</table>
</div>
</div>
</div>
</>
);
};
type TemplateSelectorProps = {
aclTemplate: string
policies: TransformedAcl[]
}
export const TemplateSelector = <T extends TemplateSelectorProps>({
formik,
editAccessRole,
titleText,
descriptionText,
buttonText,
emptyText,
transactions,
aclTemplates,
defaultUser,
}: {
formik: FormikProps<T>
editAccessRole: string
titleText: ParseKeys
descriptionText: ParseKeys
buttonText: ParseKeys
emptyText: ParseKeys
transactions: { readOnly: boolean }
aclTemplates: AclTemplate[]
defaultUser?: UserInfoState
}) => {
const { t } = useTranslation();
const dispatch = useAppDispatch();
const user = useAppSelector(state => getUserInformation(state));
const aclDefaults = useAppSelector(state => getAclDefaults(state));
if (!hasAccess(editAccessRole, user)) {
return <></>;
}
return (
<div className="obj-container">
<p>
{t(descriptionText) /* Description text for policies*/}
</p>
<div className="obj tbl-list">
<table className="main-tbl">
<thead>
<tr>
<th>
{t(titleText)}
</th>
</tr>
</thead>
<tbody>
<tr>
<td className="editable">
{!transactions.readOnly && aclTemplates.length > 0 && (
/* dropdown for selecting a policy template */
<DropDown
value={formik.values.aclTemplate}
text={getAclTemplateText(
aclTemplates,
formik.values.aclTemplate,
)}
options={aclTemplates ? formatAclTemplatesForDropdown(aclTemplates) : []}
required={true}
handleChange={element => {
if (element) {
handleTemplateChange(
element.value,
formik,
dispatch,
aclDefaults,
defaultUser,
);
}
}}
placeholder={t(buttonText)}
/>
)}
{!(aclTemplates.length > 0) &&
// Show if no option is available
<td>
<div className="obj-container padded">
{t(emptyText)}
</div>
</td>
}
</td>
</tr>
</tbody>
</table>
</div>
</div>
);
};
export const formatAclRolesForDropdown = (roles: Role[]) => {
return roles.map(role => ({ label: createPolicyLabel(role) ?? role.name, value: role.name }));
};
export const createPolicyLabel = (policy: Role | TransformedAcl) => {
if (policy.user) {
if (policy.user.email !== undefined && policy.user.email !== "" && policy.user.email !== null) {
return policy.user.name + " <" + policy.user.email + ">";
}
if (policy.user.name) {
return policy.user.name;
}
if (policy.user.username) {
return policy.user.username;
}
}
if ("name" in policy) {
return policy.name;
} else {
return policy.role;
}
};