Fixed review comments for Grant Wizard.

refs #6687
This commit is contained in:
Nikhil Mohite
2021-09-23 14:40:38 +05:30
committed by Akshay Joshi
parent 19f0181756
commit 15a494c189
7 changed files with 16 additions and 17 deletions

View File

@@ -0,0 +1,383 @@
/////////////////////////////////////////////////////////////
//
// pgAdmin 4 - PostgreSQL Tools
//
// Copyright (C) 2013 - 2021, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
//////////////////////////////////////////////////////////////
import gettext from 'sources/gettext';
import _ from 'lodash';
import url_for from 'sources/url_for';
import React from 'react';
import { Box } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import Wizard from '../helpers/wizard/Wizard';
import WizardStep from '../helpers/wizard/WizardStep';
import PgTable from 'sources/components/PgTable';
import { getNodePrivilegeRoleSchema } from '../../../browser/server_groups/servers/static/js/privilege.ui.js';
import { InputSQL, InputText, FormFooterMessage, MESSAGE_TYPE } from './FormComponents';
import getApiInstance from '../api_instance';
import SchemaView from '../SchemaView';
import clsx from 'clsx';
import Loader from 'sources/components/Loader';
import Alertify from 'pgadmin.alertifyjs';
import PropTypes from 'prop-types';
import PrivilegeSchema from '../../../tools/grant_wizard/static/js/privilege_schema.ui';
const useStyles = makeStyles(() =>
({
grantWizardStep: {
height: '100%'
},
grantWizardTitle: {
top: '0 !important',
opacity: '1 !important',
borderRadius: '6px 6px 0px 0px !important',
margin: '0 !important',
width: '100%',
height: '6%'
},
grantWizardContent: {
height: '94% !important'
},
stepPanelCss: {
height: 500,
overflow: 'hidden'
},
objectSelection: {
display: 'flex',
flexDirection: 'column',
height: '100%',
overflow: 'hidden',
marginBottom: '1em'
},
searchBox: {
marginBottom: '1em',
display: 'flex',
},
table: {
},
searchPadding: {
flex: 2.5
},
searchInput: {
flex: 1,
marginTop: 2,
borderLeft: 'none',
paddingLeft: 5
},
grantWizardPanelContent: {
paddingTop: '0.9em !important',
overflow: 'hidden'
},
grantWizardSql: {
height: '90% !important',
width: '100%'
},
privilegeStep: {
height: '100%',
}
}),
);
export default function GrantWizard({ sid, did, nodeInfo, nodeData }) {
const classes = useStyles();
var columns = [
{
Header: 'Object Type',
accessor: 'object_type',
sortble: true,
resizable: false,
disableGlobalFilter: true
},
{
Header: 'Schema',
accessor: 'nspname',
sortble: true,
resizable: false,
disableGlobalFilter: true
},
{
Header: 'Name',
accessor: 'name',
sortble: true,
resizable: true,
disableGlobalFilter: false,
minWidth: 280
}
];
var steps = ['Object Selection', 'Privilege Selection', 'Review Selection'];
const [selectedObject, setSelectedObject] = React.useState([]);
const [selectedAcl, setSelectedAcl] = React.useState({});
const [msqlData, setSQL] = React.useState('');
const [stepType, setStepType] = React.useState('');
const [searchVal, setSearchVal] = React.useState('');
const [loaderText, setLoaderText] = React.useState('');
const [tablebData, setTableData] = React.useState([]);
const [privOptions, setPrivOptions] = React.useState({});
const [privileges, setPrivileges] = React.useState([]);
const [privSchemaInstance, setPrivSchemaInstance] = React.useState();
const [errMsg, setErrMsg] = React.useState('');
const api = getApiInstance();
const validatePrivilege = () => {
var isValid = true;
selectedAcl.privilege.forEach((priv) => {
if ((_.isUndefined(priv.grantee) || _.isUndefined(priv.privileges) || priv.privileges.length === 0) && isValid) {
isValid = false;
}
});
return !isValid;
};
React.useEffect(() => {
privSchemaInstance?.privilegeRoleSchema.updateSupportedPrivs(privileges);
}, [privileges]);
React.useEffect(() => {
const privSchema = new PrivilegeSchema((privileges) => getNodePrivilegeRoleSchema('', nodeInfo, nodeData, privileges));
setPrivSchemaInstance(privSchema);
setLoaderText('Loading...');
api.get(url_for(
'grant_wizard.acl', {
'sid': encodeURI(sid),
'did': encodeURI(did),
}
)).then(res => {
setPrivOptions(res.data);
});
var node_type = nodeData._type.replace('coll-', '').replace(
'materialized_', ''
);
var _url = url_for(
'grant_wizard.objects', {
'sid': encodeURI(sid),
'did': encodeURI(did),
'node_id': encodeURI(nodeData._id),
'node_type': encodeURI(node_type),
});
api.get(_url)
.then(res => {
var data = res.data.result;
data.forEach(element => {
if (element.icon)
element['icon'] = {
'object_type': element.icon
};
});
setTableData(data);
setLoaderText('');
})
.catch(() => {
Alertify.error(gettext('Error while fetching grant wizard data.'));
setLoaderText('');
});
}, [nodeData]);
const wizardStepChange = (data) => {
switch (data.currentStep) {
case 0:
setStepType('object_type');
break;
case 1:
setStepType('privileges');
break;
case 2:
setLoaderText('Loading SQL ...');
var msql_url = url_for(
'grant_wizard.modified_sql', {
'sid': encodeURI(sid),
'did': encodeURI(did),
});
var post_data = {
acl: selectedAcl.privilege,
objects: selectedObject
};
api.post(msql_url, post_data)
.then(res => {
setSQL(res.data.data);
setLoaderText('');
})
.catch(() => {
Alertify.error(gettext('Error while fetching SQL.'));
});
break;
default:
setStepType('');
}
};
const onSave = () => {
setLoaderText('Saving...');
var _url = url_for(
'grant_wizard.apply', {
'sid': encodeURI(sid),
'did': encodeURI(did),
});
const post_data = {
acl: selectedAcl.privilege,
objects: selectedObject
};
api.post(_url, post_data)
.then(() => {
setLoaderText('');
Alertify.wizardDialog().close();
})
.catch((error) => {
setLoaderText('');
Alertify.error(gettext(`Error while saving grant wizard data: ${error.response.data.errormsg}`));
});
};
const disableNextCheck = () => {
return selectedObject.length > 0 && stepType === 'object_type' ?
false : selectedAcl?.privilege?.length > 0 && stepType === 'privileges' ? validatePrivilege() : true;
};
const onDialogHelp= () => {
window.open(url_for('help.static', { 'filename': 'grant_wizard.html' }), 'pgadmin_help');
};
const getTableSelectedRows = (selRows) => {
var selObj = [];
var objectTypes = new Set();
if (selRows.length > 0) {
selRows.forEach((row) => {
var object_type = '';
switch (row.values.object_type) {
case 'Function':
object_type = 'function';
break;
case 'Trigger Function':
object_type = 'function';
break;
case 'Procedure':
object_type = 'procedure';
break;
case 'Table':
object_type = 'table';
break;
case 'Sequence':
object_type = 'sequence';
break;
case 'View':
object_type = 'table';
break;
case 'Materialized View':
object_type = 'table';
break;
case 'Foreign Table':
object_type = 'foreign_table';
break;
case 'Package':
object_type = 'package';
break;
default:
break;
}
objectTypes.add(object_type);
selObj.push(row.values);
});
}
var privileges = new Set();
objectTypes.forEach((objType) => {
privOptions[objType]?.acl.forEach((priv) => {
privileges.add(priv);
});
});
setPrivileges(Array.from(privileges));
setSelectedObject(selObj);
setErrMsg(selObj.length === 0 ? gettext('Please select any database object.') : '');
};
const onErrClose = React.useCallback(()=>{
setErrMsg('');
});
return (
<>
<Box className={clsx('wizard-header', classes.grantWizardTitle)}>{gettext('Grant Wizard')}</Box>
<Loader message={loaderText} />
<Wizard
stepList={steps}
rootClass={clsx(classes.grantWizardContent)}
stepPanelCss={classes.grantWizardPanelContent}
disableNextStep={disableNextCheck}
onStepChange={wizardStepChange}
onSave={onSave}
onHelp={onDialogHelp}
>
<WizardStep
stepId={0}
className={clsx(classes.objectSelection, classes.grantWizardStep, classes.stepPanelCss)} >
<Box className={classes.searchBox}>
<Box className={classes.searchPadding}></Box>
<InputText
placeholder={'Search'}
className={classes.searchInput}
value={searchVal}
onChange={(val) => {
setSearchVal(val);}
}>
</InputText>
</Box>
<PgTable
className={classes.table}
height={window.innerHeight - 450}
columns={columns}
data={tablebData}
isSelectRow={true}
searchText={searchVal}
getSelectedRows={getTableSelectedRows}>
</PgTable>
<FormFooterMessage type={MESSAGE_TYPE.ERROR} message={errMsg} onClose={onErrClose} />
</WizardStep>
<WizardStep
stepId={1}
className={clsx(classes.grantWizardStep, classes.privilegeStep)}>
{privSchemaInstance &&
<SchemaView
formType={'dialog'}
getInitData={() => { }}
viewHelperProps={{ mode: 'create' }}
schema={privSchemaInstance}
showFooter={false}
isTabView={false}
onDataChange={(isChanged, changedData) => {
setSelectedAcl(changedData);
}}
/>
}
</WizardStep>
<WizardStep
stepId={2}
className={classes.grantWizardStep}>
<Box>{gettext('The SQL below will be executed on the database server to grant the selected privileges. Please click on Finish to complete the process.')}</Box>
<InputSQL
onLable={true}
className={classes.grantWizardSql}
readonly={true}
value={msqlData.toString()} />
</WizardStep>
</Wizard>
</>
);
}
GrantWizard.propTypes = {
sid: PropTypes.string,
did: PropTypes.number,
nodeInfo: PropTypes.object,
nodeData: PropTypes.object,
};

View File

@@ -0,0 +1,285 @@
/* eslint-disable react/display-name */
/* eslint-disable react/prop-types */
import React from 'react';
import { useTable, useBlockLayout, useRowSelect, useSortBy, useResizeColumns, useFlexLayout, useGlobalFilter } from 'react-table';
import { FixedSizeList } from 'react-window';
import { makeStyles } from '@material-ui/core/styles';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import AutoSizer from 'react-virtualized-auto-sizer';
import { Checkbox } from '@material-ui/core';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
flexDirection: 'column',
height: '100%',
...theme.mixins.panelBorder,
backgroundColor: theme.palette.background.default,
},
autoResizer: {
height: '100% !important',
width: '100% !important',
},
table: {
borderSpacing: 0,
width: '100%',
overflow: 'hidden',
height: '99.7%',
backgroundColor: theme.otherVars.tableBg,
...theme.mixins.panelBorder,
//backgroundColor: theme.palette.background.default,
},
tableCell: {
margin: 0,
padding: theme.spacing(0.5),
...theme.mixins.panelBorder.bottom,
...theme.mixins.panelBorder.right,
position: 'relative',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
selectCell: {
textAlign: 'center'
},
tableCellHeader: {
fontWeight: theme.typography.fontWeightBold,
padding: theme.spacing(1, 0.5),
textAlign: 'left',
overflowY: 'auto',
overflowX: 'hidden',
alignContent: 'center',
...theme.mixins.panelBorder.bottom,
...theme.mixins.panelBorder.right,
},
resizer: {
display: 'inline-block',
width: '5px',
height: '100%',
position: 'absolute',
right: 0,
top: 0,
transform: 'translateX(50%)',
zIndex: 1,
touchAction: 'none',
},
cellIcon: {
paddingLeft: '1.5em',
height: 35
}
}),
);
export default function PgTable({ columns, data, isSelectRow, ...props }) {
// Use the state and functions returned from useTable to build your UI
const classes = useStyles();
const defaultColumn = React.useMemo(
() => ({
minWidth: 150,
}),
[]
);
const scrollBarSize = React.useMemo(() => scrollbarWidth(), []);
const IndeterminateCheckbox = React.forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef();
const resolvedRef = ref || defaultRef;
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate;
}, [resolvedRef, indeterminate]);
return (
<>
<Checkbox
color="primary"
ref={resolvedRef} {...rest} />
</>
);
},
);
IndeterminateCheckbox.displayName = 'SelectCheckbox';
IndeterminateCheckbox.propTypes = {
indeterminate: PropTypes.bool,
rest: PropTypes.func,
getToggleAllRowsSelectedProps: PropTypes.func,
row: PropTypes.object,
};
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
totalColumnsWidth,
prepareRow,
selectedFlatRows,
state: { selectedRowIds },
setGlobalFilter
} = useTable(
{
columns,
data,
defaultColumn,
isSelectRow,
},
useBlockLayout,
useGlobalFilter,
useSortBy,
useRowSelect,
useResizeColumns,
useFlexLayout,
hooks => {
hooks.visibleColumns.push(CLOUMNS => {
if (isSelectRow) {
return [
// Let's make a column for selection
{
id: 'selection',
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div className={classes.selectCell}>
<IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div className={classes.selectCell}>
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
</div>
),
sortble: false,
width: 50,
minWidth: 0,
},
...CLOUMNS,
];
} else {
return [...CLOUMNS];
}
});
hooks.useInstanceBeforeDimensions.push(({ headerGroups }) => {
// fix the parent group of the selection button to not be resizable
const selectionGroupHeader = headerGroups[0].headers[0];
selectionGroupHeader.resizable = false;
});
}
);
React.useEffect(() => {
if (props.setSelectedRows) {
props.setSelectedRows(selectedFlatRows);
}
}, [selectedRowIds]);
React.useEffect(() => {
if (props.getSelectedRows) {
props.getSelectedRows(selectedFlatRows);
}
}, [selectedRowIds]);
React.useEffect(() => {
setGlobalFilter(props.searchText || undefined);
}, [props.searchText]);
const RenderRow = React.useCallback(
({ index, style }) => {
const row = rows[index];
prepareRow(row);
return (
<div
{...row.getRowProps({
style,
})}
className={classes.tr}
>
{row.cells.map((cell) => {
return (
<div key={cell.column.id} {...cell.getCellProps()} className={clsx(classes.tableCell, row.original.icon && row.original.icon[cell.column.id], row.original.icon[cell.column.id] && classes.cellIcon)} title={cell.value}>
{cell.render('Cell')}
</div>
);
})}
</div>
);
},
[prepareRow, rows, selectedRowIds]
);
// Render the UI for your table
return (
<AutoSizer className={classes.autoResizer}>
{({ height }) => (
<div {...getTableProps()} className={classes.table}>
<div>
{headerGroups.map(headerGroup => (
<div key={''} {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<div key={column.id} {...column.getHeaderProps()} className={clsx(classes.tableCellHeader, column.className)}>
<div {...(column.sortble ? column.getSortByToggleProps() : {})}>
{column.render('Header')}
<span>
{column.isSorted
? column.isSortedDesc
? ' 🔽'
: ' 🔼'
: ''}
</span>
{column.resizable &&
<div
{...column.getResizerProps()}
className={classes.resizer}
/>}
</div>
</div>
))}
</div>
))}
</div>
<div {...getTableBodyProps()}>
<FixedSizeList
height={height - 75}
itemCount={rows.length}
itemSize={35}
width={rows.length * 35 > 385 ? totalColumnsWidth + scrollBarSize : totalColumnsWidth}
sorted={props?.sortOptions}
>
{RenderRow}
</FixedSizeList>
</div>
</div>
)}
</AutoSizer>
);
}
const scrollbarWidth = () => {
// thanks too https://davidwalsh.name/detect-scrollbar-width
const scrollDiv = document.createElement('div');
scrollDiv.setAttribute('style', 'width: 100px; height: 100px; overflow: scroll; position:absolute; top:-9999px;');
document.body.appendChild(scrollDiv);
const scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
};
PgTable.propTypes = {
stepId: PropTypes.number,
height: PropTypes.number,
className: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),
getToggleAllRowsSelectedProps: PropTypes.func,
};

View File

@@ -0,0 +1,196 @@
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import clsx from 'clsx';
import FastForwardIcon from '@material-ui/icons/FastForward';
import FastRewindIcon from '@material-ui/icons/FastRewind';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import HelpIcon from '@material-ui/icons/HelpRounded';
import CheckIcon from '@material-ui/icons/Check';
import { DefaultButton, PrimaryButton, PgIconButton } from '../../../../static/js/components/Buttons';
import PropTypes from 'prop-types';
import { Box } from '@material-ui/core';
import gettext from 'sources/gettext';
const useStyles = makeStyles((theme) =>
({
root: {
display: 'flex',
flexDirection: 'column',
height: '100%',
},
rightPanel: {
position: 'relative',
minHeight: 100,
display: 'flex',
paddingLeft: '1.5em',
paddingTop: '0em',
flex: 5,
overflow: 'auto',
height: '100%',
},
leftPanel: {
display: 'flex',
// padding: '2em',
flexDirection: 'column',
alignItems: 'flex-start',
borderRight: '1px solid',
...theme.mixins.panelBorder.right,
flex: 1.6
},
label: {
display: 'inline-block',
position: 'relative',
paddingLeft: '0.5em',
flex: 6
},
labelArrow: {
display: 'inline-block',
position: 'relative',
flex: 1
},
stepLabel: {
padding: '1em',
},
active: {
fontWeight: 600
},
activeIndex: {
backgroundColor: '#326690 !important',
color: '#fff'
},
stepIndex: {
padding: '0.5em 1em ',
height: '2.5em',
borderRadius: '2em',
backgroundColor: '#ddd',
display: 'inline-block',
flex: 0.5,
},
wizard: {
width: '100%',
height: '100%',
minHeight: 100,
display: 'flex',
flexWrap: 'wrap',
},
wizardFooter: {
borderTop: '1px solid #dde0e6 !important',
padding: '0.5rem',
display: 'flex',
flexDirection: 'row',
flex: 1
},
backButton: {
marginRight: theme.spacing(1),
},
instructions: {
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1),
},
actionBtn: {
alignItems: 'flex-start',
},
buttonMargin: {
marginLeft: '0.5em'
},
stepDefaultStyle: {
width: '100%',
height: '100%'
}
}),
);
function Wizard({ stepList, onStepChange, onSave, className, ...props }) {
const classes = useStyles();
const [activeStep, setActiveStep] = React.useState(0);
const steps = stepList && stepList.length > 0 ? stepList : [];
const [disableNext, setdisableNext] = React.useState(false);
const handleNext = () => {
setActiveStep((prevActiveStep) => prevActiveStep + 1);
};
const handleBack = () => {
setActiveStep((prevActiveStep) => prevActiveStep - 1 < 0 ? prevActiveStep : prevActiveStep - 1);
};
React.useEffect(() => {
if (onStepChange) {
onStepChange({ currentStep: activeStep });
}
}, [activeStep]);
React.useEffect(() => {
if (props.disableNextStep) {
setdisableNext(props.disableNextStep());
}
});
return (
<div className={clsx(classes.root, props?.rootClass)}>
<div className={clsx(classes.wizard, className)}>
<Box className={classes.leftPanel}>
{steps.map((label, index) => (
<Box key={label} className={clsx(classes.stepLabel, index === activeStep ? classes.active : '')}>
<Box className={clsx(classes.stepIndex, index === activeStep ? classes.activeIndex : '')}>{index + 1}</Box>
<Box className={classes.label}>{label} </Box>
<Box className={classes.labelArrow}>{index === activeStep ? <ChevronRightIcon /> : null}</Box>
</Box>
))}
</Box>
<div className={clsx(classes.rightPanel, props.stepPanelCss)}>
{
React.Children.map(props.children, (child) => {
return (
<div hidden={child.props.stepId !== activeStep} className={clsx(child.props.className, classes.stepDefaultStyle)}>
{child}
</div>
);
})
}
</div>
</div>
<div className={classes.wizardFooter}>
<Box >
<PgIconButton data-test="dialog-help" onClick={() => props.onHelp()} icon={<HelpIcon />} title="Help for this dialog."
disabled={props.disableDialogHelp} />
</Box>
<Box className={classes.actionBtn} marginLeft="auto">
<DefaultButton onClick={handleBack} disabled={activeStep === 0} className={classes.buttonMargin} startIcon={<FastRewindIcon />}>
{gettext('Back')}
</DefaultButton>
<DefaultButton onClick={() => handleNext()} className={classes.buttonMargin} startIcon={<FastForwardIcon />} disabled={activeStep == steps.length - 1 || disableNext}>
{gettext('Next')}
</DefaultButton>
<PrimaryButton className={classes.buttonMargin} startIcon={<CheckIcon />} disabled={activeStep == steps.length - 1 ? false : true} onClick={onSave}>
{gettext('Finish')}
</PrimaryButton>
</Box>
</div>
</div>
);
}
export default Wizard;
Wizard.propTypes = {
props: PropTypes.object,
stepList: PropTypes.array,
onSave: PropTypes.func,
onHelp: PropTypes.func,
onStepChange: PropTypes.func,
className: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
disableNextStep: PropTypes.func,
stepPanelCss: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
rootClass: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),
disableDialogHelp: PropTypes.bool
};

View File

@@ -0,0 +1,44 @@
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Box } from '@material-ui/core';
import clsx from 'clsx';
import PropTypes from 'prop-types';
const useStyles = makeStyles(() =>
({
stepPanel: {
height: '100%',
width: '100%',
// paddingLeft: '2em',
minHeight: '100px',
// paddingTop: '1em',
paddingBottom: '1em',
paddingRight: '1em',
overflow: 'auto',
}
}));
export default function WizardStep({stepId, className, ...props }) {
const classes = useStyles();
return (
<Box id={stepId} className={clsx(classes.stepPanel, className)} style={props?.height ? {height: props.height} : null}>
{
React.Children.map(props.children, (child) => {
return (
<>
{child}
</>
);
})
}
</Box>
);
}
WizardStep.propTypes = {
stepId: PropTypes.number,
height: PropTypes.number,
className: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),
};