Debian Codegraph @

install/freeipa-webui/src/pages/SudoRules/AccessThisHost.tsx

raw
1 import React from "react";
2 // PatternFly
3 import {
4 Flex,
5 FlexItem,
6 Label,
7 Tab,
8 Tabs,
9 TabTitleText,
10 } from "@patternfly/react-core";
11 // Data types
12 import { Metadata, SudoRule } from "src/utils/datatypes/globalDataTypes";
13 // Components
14 import KeytabTableWithFilter, {
15 TableEntry,
16 } from "src/components/tables/KeytabTableWithFilter";
17 import IpaToggleGroup from "src/components/Form/IpaToggleGroup";
18 // RPC
19 import { ErrorResult } from "src/services/rpc";
20 import {
21 AddRemoveHostToSudoRulesResult,
22 AddRemoveToSudoRulesPayload,
23 useAddHostToSudoRuleMutation,
24 useRemoveHostFromSudoRuleMutation,
25 useSaveSudoRuleMutation,
26 } from "src/services/rpcSudoRules";
27 // Redux
28 import { useAppDispatch } from "src/store/hooks";
29 // Utils
30 import { containsAny } from "src/utils/utils";
31 // Hooks
32 import { addAlert } from "src/store/Global/alerts-slice";
33
34 interface PropsToAccessThisHost {
35 // eslint-disable-next-line @typescript-eslint/no-explicit-any
36 ipaObject: Record<string, any>;
37 rule: Partial<SudoRule>;
38 hostsList: TableEntry[]; // memberhost_host + externalhost
39 hostGroupsList: TableEntry[]; // memberhost_hostgroup
40 onRefresh: () => void;
41 // eslint-disable-next-line @typescript-eslint/no-explicit-any
42 recordOnChange: (ipaObject: Record<string, any>) => void;
43 metadata: Metadata;
44 // setIsAnyoneSelected: (value: boolean) => void;
45 onSave: () => void;
46 modifiedValues: () => Partial<SudoRule>;
47 }
48
49 const AccessThisHost = (props: PropsToAccessThisHost) => {
50 const dispatch = useAppDispatch();
51
52 const [activeTabKey, setActiveTabKey] = React.useState<string | number>(0);
53
54 const handleTabClick = (
55 event: React.MouseEvent | React.KeyboardEvent | MouseEvent,
56 tabIndex: string | number
57 ) => {
58 setActiveTabKey(tabIndex);
59 };
60
61 // API calls
62 const [onAdd] = useAddHostToSudoRuleMutation();
63 const [onDelete] = useRemoveHostFromSudoRuleMutation();
64 const [onSave] = useSaveSudoRuleMutation();
65
66 // States
67 const [modalSpinning, setModalSpinning] = React.useState(false);
68 const [hostsList, setHostsList] = React.useState<TableEntry[]>(
69 props.hostsList
70 );
71 const [hostGroupsList, setHostGroupsList] = React.useState<TableEntry[]>(
72 props.hostGroupsList
73 );
74
75 React.useEffect(() => {
76 setHostsList(props.hostsList);
77 }, [props.hostsList]);
78
79 React.useEffect(() => {
80 setHostGroupsList(props.hostGroupsList);
81 }, [props.hostGroupsList]);
82
83 // on Add new host
84 const onAddNewHost = (newHosts: string[]) => {
85 setModalSpinning(true);
86 const payload: AddRemoveToSudoRulesPayload = {
87 toId: props.rule.cn as string,
88 type: "host",
89 listOfMembers: newHosts,
90 };
91
92 onAdd(payload).then((response) => {
93 if ("data" in response) {
94 const data = response.data;
95 const results = data?.result
96 .results as unknown as AddRemoveHostToSudoRulesResult[];
97 results.forEach((result) => {
98 // Check if any errors
99 if (result.error !== null) {
100 dispatch(
101 addAlert({
102 name: "access-this-host-add-host-external-error",
103 title: "Error: " + result.error,
104 variant: "danger",
105 })
106 );
107 } else {
108 // Some values can be undefined after addition
109 const hostsFromResponse = result.result.memberhost_host || [];
110 const externalsFromResponse = result.result.externalhost || [];
111 if (
112 containsAny(hostsFromResponse, newHosts) ||
113 containsAny(externalsFromResponse, newHosts)
114 ) {
115 // Set alert: success
116 dispatch(
117 addAlert({
118 name: "access-this-host-add-host-external-success",
119 title: "Added new item(s) to '" + props.rule.cn + "'",
120 variant: "success",
121 })
122 );
123 // Refresh page
124 props.onRefresh();
125 }
126 }
127 });
128 } else {
129 // Assume error
130 dispatch(
131 addAlert({
132 name: "add-who-user-external-error",
133 title:
134 "Error: " + (response.error ? response.error : "Unknown error"),
135 variant: "danger",
136 })
137 );
138 }
139 setModalSpinning(false);
140 });
141 };
142
143 // on save and add hosts
144 // - If 'specify' option is selected (just modified) and new hosts should be added:
145 // save the rule first and then add the hosts
146 const onSaveAndAddHosts = (hostsToAdd: string[]) => {
147 const modifiedValues = props.modifiedValues();
148 if (modifiedValues.hostcategory === "") {
149 modifiedValues.cn = props.rule.cn;
150
151 onSave(modifiedValues).then((response) => {
152 if ("data" in response) {
153 if (response.data?.result) {
154 // Show toast notification: success
155 dispatch(
156 addAlert({
157 name: "save-success",
158 title: "Sudo rule modified",
159 variant: "success",
160 })
161 );
162 props.onRefresh();
163 // Add new hosts
164 onAddNewHost(hostsToAdd);
165 } else if (response.data?.error) {
166 // Show toast notification: error
167 const errorMessage = response.data.error as ErrorResult;
168 dispatch(
169 addAlert({
170 name: "save-error",
171 title: errorMessage.message,
172 variant: "danger",
173 })
174 );
175 }
176 }
177 });
178 } else {
179 onAddNewHost(hostsToAdd);
180 }
181 };
182
183 // on Delete host(s)
184 const onDeleteHosts = (hostsToDelete: string[]) => {
185 setModalSpinning(true);
186 const payload: AddRemoveToSudoRulesPayload = {
187 toId: props.rule.cn as string,
188 type: "host",
189 listOfMembers: hostsToDelete,
190 };
191
192 onDelete(payload).then((response) => {
193 if ("data" in response) {
194 const data = response.data;
195 const results =
196 data?.result as unknown as AddRemoveHostToSudoRulesResult;
197 if (results) {
198 // Some values can be undefined after deletion
199 const hostsFromResponse = results.result.memberhost_host || [];
200 const externalsFromResponse = results.result.externalhost || [];
201 if (
202 !containsAny(hostsFromResponse, hostsToDelete) ||
203 !containsAny(externalsFromResponse, hostsToDelete)
204 ) {
205 // Set alert: success
206 dispatch(
207 addAlert({
208 name: "access-this-host-remove-host-external-success",
209 title: "Removed item(s) from " + props.rule.cn,
210 variant: "success",
211 })
212 );
213 // Refresh page
214 props.onRefresh();
215 }
216 // Check if any errors
217 else if (results.error || results.failed.memberhost.host.length > 0) {
218 dispatch(
219 addAlert({
220 name: "access-this-host-remove-host-external-error",
221 title: "Error: " + results.error,
222 variant: "danger",
223 })
224 );
225 }
226 }
227 }
228 setModalSpinning(false);
229 });
230 };
231
232 // on Add new host group
233 const onAddNewHostGroup = (newHostGroups: string[]) => {
234 setModalSpinning(true);
235 const payload: AddRemoveToSudoRulesPayload = {
236 toId: props.rule.cn as string,
237 type: "hostgroup",
238 listOfMembers: newHostGroups,
239 };
240
241 onAdd(payload).then((response) => {
242 if ("data" in response) {
243 const data = response.data;
244 const results = data?.result
245 .results as unknown as AddRemoveHostToSudoRulesResult[];
246 results.forEach((result) => {
247 const hostGroupsFromResponse =
248 result.result.memberhost_hostgroup || [];
249 if (containsAny(hostGroupsFromResponse, newHostGroups)) {
250 // Set alert: success
251 dispatch(
252 addAlert({
253 name: "access-this-host-add-hostgroup-external-success",
254 title: "Added new item(s) to '" + props.rule.cn + "'",
255 variant: "success",
256 })
257 );
258 // Refresh page
259 props.onRefresh();
260 }
261 // Check if any errors
262 if (result.error !== null) {
263 dispatch(
264 addAlert({
265 name: "access-this-host-add-hostgroup-external-error",
266 title: "Error: " + result.error,
267 variant: "danger",
268 })
269 );
270 }
271 });
272 }
273 setModalSpinning(false);
274 });
275 };
276
277 // On save and add host groups
278 // - If 'specify' option is selected (just modified) and new host groups should be added:
279 // save the rule first and then add the host groups
280 const onSaveAndAddGroups = (hostGroupsToAdd: string[]) => {
281 const modifiedValues = props.modifiedValues();
282 if (modifiedValues.usercategory === "") {
283 modifiedValues.cn = props.rule.cn;
284
285 onSave(modifiedValues).then((response) => {
286 if ("data" in response) {
287 if (response.data?.result) {
288 // Show toast notification: success
289 dispatch(
290 addAlert({
291 name: "save-success",
292 title: "Sudo rule modified",
293 variant: "success",
294 })
295 );
296 props.onRefresh();
297 // Add new users
298 onAddNewHostGroup(hostGroupsToAdd);
299 } else if (response.data?.error) {
300 // Show toast notification: error
301 const errorMessage = response.data.error as ErrorResult;
302 dispatch(
303 addAlert({
304 name: "save-error",
305 title: errorMessage.message,
306 variant: "danger",
307 })
308 );
309 }
310 }
311 });
312 } else {
313 onAddNewHostGroup(hostGroupsToAdd);
314 }
315 };
316
317 // on Delete host group(s)
318 const onDeleteHostGroups = (hostGroupsToDelete: string[]) => {
319 setModalSpinning(true);
320 const payload: AddRemoveToSudoRulesPayload = {
321 toId: props.rule.cn as string,
322 type: "hostgroup",
323 listOfMembers: hostGroupsToDelete,
324 };
325
326 onDelete(payload).then((response) => {
327 if ("data" in response) {
328 const data = response.data;
329 const results =
330 data?.result as unknown as AddRemoveHostToSudoRulesResult;
331 if (results) {
332 const groupsFromResponse = results.result.memberhost_hostgroup || [];
333 if (!containsAny(groupsFromResponse, hostGroupsToDelete)) {
334 // Set alert: success
335 dispatch(
336 addAlert({
337 name: "access-this-host-remove-hostgroup-external-success",
338 title: "Removed item(s) from " + props.rule.cn,
339 variant: "success",
340 })
341 );
342 // Refresh page
343 props.onRefresh();
344 }
345 // Check if any errors
346 else if (
347 results.error ||
348 results.failed.memberhost.hostgroup.length > 0
349 ) {
350 dispatch(
351 addAlert({
352 name: "access-this-host-remove-hostgroup-external-error",
353 title: "Error: " + results.error,
354 variant: "danger",
355 })
356 );
357 }
358 }
359 }
360 setModalSpinning(false);
361 });
362 };
363
364 // Filter: toggle options
365 // - Default value: "first" (the first element)
366 // - Instead of using the name of the buttons, it will be referred
367 // as "first" as per the 'IpaToggleGroup' component
368 const [optionSelected, setOptionSelected] = React.useState<string>(
369 props.rule.usercategory && props.rule.usercategory === "all"
370 ? "Anyone"
371 : "Specified Users and Groups"
372 );
373
374 // - When 'hostcategory' is "all", disable checkboxes
375 const anyoneOptionSelected = optionSelected === "Anyone";
376
377 const options = [
378 { label: "Anyone", value: "all" },
379 { label: "Specified Users and Groups", value: "" },
380 ];
381
382 const filter = (
383 <Flex name="hostcategory">
384 <FlexItem>Host category the rule applies to: </FlexItem>
385 <FlexItem>
386 <IpaToggleGroup
387 dataCy="access-this-host-toggle-group-hostcategory"
388 ipaObject={props.ipaObject}
389 name="hostcategory"
390 options={options}
391 optionSelected={optionSelected}
392 setOptionSelected={setOptionSelected}
393 onChange={props.recordOnChange}
394 objectName="sudorule"
395 metadata={props.metadata}
396 isCompact
397 />
398 </FlexItem>
399 </Flex>
400 );
401
402 // Render component
403 return (
404 <>
405 {/* Filter: toggle group */}
406 {filter}
407 {/* Tabs */}
408 <Tabs
409 activeKey={activeTabKey}
410 onSelect={handleTabClick}
411 aria-label="Tabs for types of entries that can create keytabs"
412 >
413 <Tab
414 key={0}
415 eventKey={0}
416 title={
417 <TabTitleText>
418 Hosts <Label isCompact>{hostsList.length}</Label>
419 </TabTitleText>
420 }
421 aria-label="hosts in the who section of the sudo rule"
422 >
423 <KeytabTableWithFilter
424 className="pf-v6-u-ml-md pf-v6-u-mt-sm"
425 id={props.rule.cn as string}
426 from="sudo rule"
427 name="memberhost_host"
428 isSpinning={modalSpinning}
429 entityType="host"
430 // Table data
431 operationTitle={"Add host into sudo rule " + props.rule.cn}
432 tableEntryList={hostsList}
433 columnNames={["Host"]}
434 onRefresh={props.onRefresh}
435 onAdd={onSaveAndAddHosts}
436 onDelete={onDeleteHosts}
437 checkboxesDisabled={anyoneOptionSelected}
438 // Add external option on Add modal
439 externalOption={true}
440 />
441 </Tab>
442 <Tab
443 key={1}
444 eventKey={1}
445 title={
446 <TabTitleText>
447 Host groups <Label isCompact>{hostGroupsList.length}</Label>
448 </TabTitleText>
449 }
450 aria-label="user groups in the who section of the sudo rule"
451 >
452 <KeytabTableWithFilter
453 className="pf-v6-u-ml-md pf-v6-u-mt-sm"
454 id={props.rule.cn as string}
455 from="sudo rule"
456 name="memberuser_group"
457 isSpinning={modalSpinning}
458 entityType="hostgroup"
459 // Table data
460 operationTitle={"Add host group into sudo rule " + props.rule.cn}
461 tableEntryList={hostGroupsList}
462 columnNames={["Host group"]}
463 onRefresh={props.onRefresh}
464 onAdd={onSaveAndAddGroups}
465 onDelete={onDeleteHostGroups}
466 checkboxesDisabled={anyoneOptionSelected}
467 />
468 </Tab>
469 </Tabs>
470 </>
471 );
472 };
473
474 export default AccessThisHost;