Debian Codegraph @

install/freeipa-webui/src/pages/CertificateMapping/CertificateMapping.tsx

raw
1 import React from "react";
2 // PatternFly
3 import {
4 Flex,
5 FlexItem,
6 PageSection,
7 PaginationVariant,
8 ToolbarItemVariant,
9 } from "@patternfly/react-core";
10 import {
11 InnerScrollContainer,
12 OuterScrollContainer,
13 } from "@patternfly/react-table";
14 // Data types
15 import { CertificateMapping } from "src/utils/datatypes/globalDataTypes";
16 // Hooks
17 import { addAlert } from "src/store/Global/alerts-slice";
18 import useUpdateRoute from "src/hooks/useUpdateRoute";
19 import useListPageSearchParams from "src/hooks/useListPageSearchParams";
20 import useApiError from "src/hooks/useApiError";
21 // Redux
22 import { useAppDispatch, useAppSelector } from "src/store/hooks";
23 // RPC
24 import {
25 useGetCertMapRuleEntriesQuery,
26 useSearchCertMapRuleEntriesMutation,
27 } from "src/services/rpcCertMapping";
28 // Utils
29 import { isCertMapSelectable } from "src/utils/utils";
30 import { apiToCertificateMapping } from "src/utils/certMappingUtils";
31 // React router
32 import { useNavigate } from "react-router";
33 // Components
34 import { FetchBaseQueryError } from "@reduxjs/toolkit/query";
35 import { SerializedError } from "@reduxjs/toolkit";
36 import ToolbarLayout, {
37 ToolbarItem,
38 } from "src/components/layouts/ToolbarLayout";
39 import SearchInputLayout from "src/components/layouts/SearchInputLayout";
40 import SecondaryButton from "src/components/layouts/SecondaryButton";
41 import HelpTextWithIconLayout from "src/components/layouts/HelpTextWithIconLayout";
42 import PaginationLayout from "src/components/layouts/PaginationLayout";
43 import TitleLayout from "src/components/layouts/TitleLayout";
44 import GlobalErrors from "src/components/errors/GlobalErrors";
45 import MainTable from "src/components/tables/MainTable";
46 import BulkSelectorPrep from "src/components/BulkSelectorPrep";
47 import AddRuleModal from "src/components/modals/CertificateMapping/AddRuleModal";
48 import DeleteMultipleRulesModal from "src/components/modals/CertificateMapping/DeleteMultipleRulesModal";
49 import EnableDisableMultipleRulesModal from "src/components/modals/CertificateMapping/EnableDisableMultipleRules";
50
51 const CertificateMappingPage = () => {
52 const dispatch = useAppDispatch();
53 const navigate = useNavigate();
54
55 // Update current route data to Redux and highlight the current page in the Nav bar
56 const { browserTitle } = useUpdateRoute({
57 pathname: "cert-id-mapping-rules",
58 });
59
60 // Set the page title to be shown in the browser tab
61 React.useEffect(() => {
62 document.title = browserTitle;
63 }, [browserTitle]);
64
65 // Retrieve API version from environment data
66 const apiVersion = useAppSelector(
67 (state) => state.global.environment.api_version
68 ) as string;
69
70 // URL parameters: page number, page size, search value
71 const { page, setPage, perPage, setPerPage, searchValue, setSearchValue } =
72 useListPageSearchParams();
73
74 // Handle API calls errors
75 const globalErrors = useApiError([]);
76
77 // Page indexes
78 const firstUserIdx = (page - 1) * perPage;
79 const lastUserIdx = page * perPage;
80
81 // States
82 const [certMapRules, setCertMapRules] = React.useState<CertificateMapping[]>(
83 []
84 );
85 const [isSearchDisabled, setIsSearchDisabled] = React.useState(false);
86 const [totalCount, setTotalCount] = React.useState(0);
87
88 // API calls
89 const certMapsResponse = useGetCertMapRuleEntriesQuery({
90 searchValue,
91 apiVersion,
92 sizelimit: 100,
93 startIdx: firstUserIdx,
94 stopIdx: lastUserIdx,
95 });
96
97 const { data, isLoading, error } = certMapsResponse;
98
99 // Handle data when the API call is finished
100 React.useEffect(() => {
101 if (certMapsResponse.isFetching) {
102 setShowTableRows(false);
103 // Reset selected elements on refresh
104 setTotalCount(0);
105 globalErrors.clear();
106 return;
107 }
108
109 // API response: Success
110 if (
111 certMapsResponse.isSuccess &&
112 certMapsResponse.data &&
113 data !== undefined
114 ) {
115 const listResult = data.result.results;
116 const listSize = data.result.count;
117 const elementsList: CertificateMapping[] = [];
118
119 for (let i = 0; i < listSize; i++) {
120 elementsList.push(apiToCertificateMapping(listResult[i].result));
121 }
122
123 setTotalCount(certMapsResponse.data.result.totalCount);
124 // Update the list of elements
125 setCertMapRules(elementsList);
126 // Show table elements
127 setShowTableRows(true);
128 }
129
130 // API response: Error
131 if (
132 !certMapsResponse.isLoading &&
133 certMapsResponse.isError &&
134 certMapsResponse.error !== undefined
135 ) {
136 // This normally happens when the user is not authorized to view the data
137 // So instead of adding an error, refresh page
138 navigate("/login");
139 window.location.reload();
140 }
141 }, [certMapsResponse]);
142
143 // Selected elements
144 const [selectedElements, setSelectedElements] = React.useState<
145 CertificateMapping[]
146 >([]);
147 const [selectedPerPage, setSelectedPerPage] = React.useState<number>(0);
148
149 // Refresh button handling
150 const refreshData = () => {
151 // Hide table
152 setShowTableRows(false);
153
154 // Reset selected elements on refresh
155 setTotalCount(0);
156
157 certMapsResponse.refetch().then(() => {
158 setShowTableRows(true);
159 });
160 };
161
162 // 'Delete' button state
163 const [isDeleteButtonDisabled, setIsDeleteButtonDisabled] =
164 React.useState<boolean>(true);
165
166 const [isDeletion, setIsDeletion] = React.useState(false);
167
168 // 'Enable' button state
169 const [isEnableButtonDisabled, setIsEnableButtonDisabled] =
170 React.useState<boolean>(true);
171
172 // 'Disable' button state
173 const [isDisableButtonDisabled, setIsDisableButtonDisabled] =
174 React.useState<boolean>(true);
175
176 // Table-related shared functionality
177 // - Selectable checkboxes on table
178 const selectableCertMapRulesTable = certMapRules.filter(isCertMapSelectable); // elements per Table
179
180 const updateSelectedCertMapRules = (
181 certMapRule: CertificateMapping[],
182 isSelected: boolean
183 ) => {
184 let newSelectedCertMapRules: CertificateMapping[] = [];
185 if (isSelected) {
186 newSelectedCertMapRules = JSON.parse(JSON.stringify(selectedElements));
187 for (let i = 0; i < certMapRule.length; i++) {
188 if (
189 selectedElements.find(
190 (selectedCertMapRule) =>
191 selectedCertMapRule.cn === certMapRule[i].cn
192 )
193 ) {
194 // Already in the list
195 continue;
196 }
197 // Add element to list
198 newSelectedCertMapRules.push(certMapRule[i]);
199 }
200 } else {
201 // Remove element
202 for (let i = 0; i < selectedElements.length; i++) {
203 let found = false;
204 for (let ii = 0; ii < certMapRule.length; ii++) {
205 if (selectedElements[i].cn === certMapRule[ii].cn) {
206 found = true;
207 break;
208 }
209 }
210 if (!found) {
211 // Keep this valid selected entry
212 newSelectedCertMapRules.push(selectedElements[i]);
213 }
214 }
215 }
216 setSelectedElements(newSelectedCertMapRules);
217 setIsDeleteButtonDisabled(newSelectedCertMapRules.length === 0);
218 };
219
220 // - Helper method to set the selected entries from the table
221 const setCertMapRulesSelected = (
222 certMapRule: CertificateMapping,
223 isSelecting = true
224 ) => {
225 if (isCertMapSelectable(certMapRule)) {
226 updateSelectedCertMapRules([certMapRule], isSelecting);
227 }
228 };
229
230 // Always refetch data when the component is loaded.
231 // This ensures the data is always up-to-date.
232 React.useEffect(() => {
233 certMapsResponse.refetch();
234 }, []);
235
236 // Show table rows
237 const [showTableRows, setShowTableRows] = React.useState(!isLoading);
238
239 // Show table rows only when data is fully retrieved
240 React.useEffect(() => {
241 if (showTableRows !== !isLoading) {
242 setShowTableRows(!isLoading);
243 }
244 }, [isLoading]);
245
246 // Search API call
247 const [searchEntry] = useSearchCertMapRuleEntriesMutation();
248
249 const submitSearchValue = () => {
250 searchEntry({
251 searchValue: searchValue,
252 apiVersion,
253 sizelimit: 100,
254 startIdx: 0,
255 stopIdx: 200, // Search will consider a max. of elements
256 }).then((result) => {
257 if ("data" in result) {
258 const searchError = result.data?.error as
259 | FetchBaseQueryError
260 | SerializedError;
261
262 if (searchError) {
263 // Error
264 let error: string | undefined = "";
265 if ("error" in searchError) {
266 error = searchError.error;
267 } else if ("message" in searchError) {
268 error = searchError.message;
269 }
270 dispatch(
271 addAlert({
272 name: "submit-search-value-error",
273 title: error || "Error when searching for IdPs",
274 variant: "danger",
275 })
276 );
277 } else {
278 // Success
279 const listResult = result.data?.result.results || [];
280 const listSize = result.data?.result.count || 0;
281 const totalCount = result.data?.result.totalCount || 0;
282 const elementsList: CertificateMapping[] = [];
283
284 for (let i = 0; i < listSize; i++) {
285 elementsList.push(listResult[i].result);
286 }
287
288 setTotalCount(totalCount);
289 setCertMapRules(elementsList);
290 setShowTableRows(true);
291 }
292 setIsSearchDisabled(false);
293 }
294 });
295 };
296
297 // Data wrappers
298 // TODO: Better separation of concerts
299 // - 'PaginationLayout'
300 const paginationData = {
301 page,
302 perPage,
303 updatePage: setPage,
304 updatePerPage: setPerPage,
305 updateSelectedPerPage: setSelectedPerPage,
306 updateShownElementsList: setCertMapRules,
307 totalCount,
308 };
309
310 // SearchInputLayout
311 const searchValueData = {
312 searchValue,
313 updateSearchValue: setSearchValue,
314 submitSearchValue,
315 };
316
317 // - 'BulkSelectorrep'
318 const bulkSelectorData = {
319 selected: selectedElements,
320 updateSelected: updateSelectedCertMapRules,
321 selectableTable: selectableCertMapRulesTable,
322 nameAttr: "cn",
323 };
324
325 const selectedPerPageData = {
326 selectedPerPage,
327 updateSelectedPerPage: setSelectedPerPage,
328 };
329
330 // Modals functionality
331 const [showAddModal, setShowAddModal] = React.useState(false);
332 const [showDeleteModal, setShowDeleteModal] = React.useState(false);
333 const [showEnableDisableModal, setShowEnableDisableModal] =
334 React.useState(false);
335 const [operation, setOperation] = React.useState<"enable" | "disable">(
336 "disable"
337 );
338
339 // Open modal and set operation to 'disable' or "enable"
340 const onEnableOperation = () => {
341 setOperation("enable");
342 setShowEnableDisableModal(true);
343 };
344
345 const onDisableOperation = () => {
346 setOperation("disable");
347 setShowEnableDisableModal(true);
348 };
349
350 // List of Toolbar items
351 const toolbarItems: ToolbarItem[] = [
352 {
353 key: 0,
354 element: (
355 <BulkSelectorPrep
356 list={certMapRules}
357 shownElementsList={certMapRules}
358 elementData={bulkSelectorData}
359 buttonsData={{
360 updateIsDeleteButtonDisabled: setIsDeleteButtonDisabled,
361 }}
362 selectedPerPageData={selectedPerPageData}
363 />
364 ),
365 },
366 {
367 key: 1,
368 element: (
369 <SearchInputLayout
370 dataCy="search"
371 name="search"
372 ariaLabel="Search certificate mapping rules"
373 placeholder="Search"
374 searchValueData={searchValueData}
375 isDisabled={isSearchDisabled}
376 />
377 ),
378 toolbarItemVariant: ToolbarItemVariant.label,
379 toolbarItemGap: { default: "gapMd" },
380 },
381 {
382 key: 2,
383 toolbarItemVariant: ToolbarItemVariant.separator,
384 },
385 {
386 key: 3,
387 element: (
388 <SecondaryButton
389 dataCy="certificate-mapping-button-refresh"
390 onClickHandler={refreshData}
391 isDisabled={!showTableRows}
392 >
393 Refresh
394 </SecondaryButton>
395 ),
396 },
397 {
398 key: 4,
399 element: (
400 <SecondaryButton
401 dataCy="certificate-mapping-button-delete"
402 isDisabled={isDeleteButtonDisabled || !showTableRows}
403 onClickHandler={() => setShowDeleteModal(true)}
404 >
405 Delete
406 </SecondaryButton>
407 ),
408 },
409 {
410 key: 5,
411 element: (
412 <SecondaryButton
413 dataCy="certificate-mapping-button-add"
414 isDisabled={!showTableRows}
415 onClickHandler={() => setShowAddModal(true)}
416 >
417 Add
418 </SecondaryButton>
419 ),
420 },
421 {
422 key: 6,
423 element: (
424 <SecondaryButton
425 dataCy="certificate-mapping-button-disable"
426 isDisabled={isDisableButtonDisabled || !showTableRows}
427 onClickHandler={onDisableOperation}
428 >
429 Disable
430 </SecondaryButton>
431 ),
432 },
433 {
434 key: 7,
435 element: (
436 <SecondaryButton
437 dataCy="certificate-mapping-button-enable"
438 isDisabled={isEnableButtonDisabled || !showTableRows}
439 onClickHandler={onEnableOperation}
440 >
441 Enable
442 </SecondaryButton>
443 ),
444 },
445 {
446 key: 8,
447 toolbarItemVariant: ToolbarItemVariant.separator,
448 },
449 {
450 key: 9,
451 element: <HelpTextWithIconLayout textContent="Help" />,
452 },
453 {
454 key: 10,
455 element: (
456 <PaginationLayout
457 list={certMapRules}
458 paginationData={paginationData}
459 widgetId="pagination-options-menu-top"
460 isCompact={true}
461 />
462 ),
463 toolbarItemAlignment: { default: "alignEnd" },
464 },
465 ];
466
467 // Render component
468 return (
469 <div>
470 <PageSection hasBodyWrapper={false}>
471 <TitleLayout
472 id="Certificate Identity mapping rules page"
473 headingLevel="h1"
474 text="Certificate Identity mapping rules"
475 />
476 </PageSection>
477 <PageSection hasBodyWrapper={false} isFilled={false}>
478 <Flex direction={{ default: "column" }}>
479 <FlexItem>
480 <ToolbarLayout toolbarItems={toolbarItems} />
481 </FlexItem>
482 <FlexItem style={{ flex: "0 0 auto" }}>
483 <OuterScrollContainer>
484 <InnerScrollContainer
485 style={{ height: "55vh", overflow: "auto" }}
486 >
487 {error !== undefined && error ? (
488 <GlobalErrors errors={globalErrors.getAll()} />
489 ) : (
490 <MainTable
491 tableTitle="Certificate Identity mapping table"
492 shownElementsList={certMapRules}
493 pk="cn"
494 keyNames={["cn", "ipaenabledflag", "description"]}
495 columnNames={["Rule name", "Status", "Description"]}
496 hasCheckboxes={true}
497 pathname="cert-id-mapping-rules"
498 showTableRows={showTableRows}
499 showLink={true}
500 elementsData={{
501 isElementSelectable: isCertMapSelectable,
502 selectedElements,
503 selectableElementsTable: selectableCertMapRulesTable,
504 setElementsSelected: setCertMapRulesSelected,
505 clearSelectedElements: () => setSelectedElements([]),
506 }}
507 buttonsData={{
508 updateIsDeleteButtonDisabled: (value) =>
509 setIsDeleteButtonDisabled(value),
510 isDeletion,
511 updateIsDeletion: (value) => setIsDeletion(value),
512 updateIsEnableButtonDisabled: (value) =>
513 setIsEnableButtonDisabled(value),
514 updateIsDisableButtonDisabled: (value) =>
515 setIsDisableButtonDisabled(value),
516 isDisableEnableOp: true,
517 }}
518 paginationData={{
519 selectedPerPage,
520 updateSelectedPerPage: setSelectedPerPage,
521 }}
522 statusElementName="ipaenabledflag"
523 />
524 )}
525 </InnerScrollContainer>
526 </OuterScrollContainer>
527 </FlexItem>
528 <FlexItem style={{ flex: "0 0 auto", position: "sticky", bottom: 0 }}>
529 <PaginationLayout
530 list={certMapRules}
531 paginationData={paginationData}
532 variant={PaginationVariant.bottom}
533 widgetId="pagination-options-menu-bottom"
534 />
535 </FlexItem>
536 </Flex>
537 </PageSection>
538 <AddRuleModal
539 isOpen={showAddModal}
540 onClose={() => setShowAddModal(false)}
541 title={"Add certificate identity mapping rule"}
542 onRefresh={refreshData}
543 />
544 <DeleteMultipleRulesModal
545 isOpen={showDeleteModal}
546 onClose={() => setShowDeleteModal(false)}
547 elementsToDelete={selectedElements}
548 clearSelectedElements={() => setSelectedElements([])}
549 columnNames={["Rule name", "Description"]}
550 keyNames={["cn", "description"]}
551 onRefresh={refreshData}
552 updateIsDeleteButtonDisabled={setIsDeleteButtonDisabled}
553 updateIsDeletion={setIsDeletion}
554 />
555 <EnableDisableMultipleRulesModal
556 isOpen={showEnableDisableModal}
557 onClose={() => setShowEnableDisableModal(false)}
558 elementsList={selectedElements.map((rule) => rule.cn)}
559 setElementsList={(value) =>
560 setSelectedElements(value.map((cn) => ({ cn }) as CertificateMapping))
561 }
562 operation={operation}
563 setShowTableRows={setShowTableRows}
564 onRefresh={refreshData}
565 />
566 </div>
567 );
568 };
569
570 export default CertificateMappingPage;