Debian Codegraph @

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