Merge pull request #7183 from AlexSCorey/7104-UserTeamsDisassociate

Adds disassociate functionality and an empty state for Sys Admin

Reviewed-by: https://github.com/apps/softwarefactory-project-zuul
This commit is contained in:
softwarefactory-project-zuul[bot]
2020-06-03 14:04:44 +00:00
committed by GitHub
10 changed files with 768 additions and 293 deletions

View File

@@ -18,6 +18,7 @@ import Organizations from './models/Organizations';
import ProjectUpdates from './models/ProjectUpdates'; import ProjectUpdates from './models/ProjectUpdates';
import Projects from './models/Projects'; import Projects from './models/Projects';
import Root from './models/Root'; import Root from './models/Root';
import Roles from './models/Roles';
import Schedules from './models/Schedules'; import Schedules from './models/Schedules';
import SystemJobs from './models/SystemJobs'; import SystemJobs from './models/SystemJobs';
import Teams from './models/Teams'; import Teams from './models/Teams';
@@ -49,6 +50,7 @@ const OrganizationsAPI = new Organizations();
const ProjectUpdatesAPI = new ProjectUpdates(); const ProjectUpdatesAPI = new ProjectUpdates();
const ProjectsAPI = new Projects(); const ProjectsAPI = new Projects();
const RootAPI = new Root(); const RootAPI = new Root();
const RolesAPI = new Roles();
const SchedulesAPI = new Schedules(); const SchedulesAPI = new Schedules();
const SystemJobsAPI = new SystemJobs(); const SystemJobsAPI = new SystemJobs();
const TeamsAPI = new Teams(); const TeamsAPI = new Teams();
@@ -81,6 +83,7 @@ export {
ProjectUpdatesAPI, ProjectUpdatesAPI,
ProjectsAPI, ProjectsAPI,
RootAPI, RootAPI,
RolesAPI,
SchedulesAPI, SchedulesAPI,
SystemJobsAPI, SystemJobsAPI,
TeamsAPI, TeamsAPI,

View File

@@ -0,0 +1,23 @@
import Base from '../Base';
class Roles extends Base {
constructor(http) {
super(http);
this.baseUrl = '/api/v2/roles/';
}
disassociateUserRole(roleId, userId) {
return this.http.post(`${this.baseUrl}/${roleId}/users/`, {
disassociate: true,
id: userId,
});
}
disassociateTeamRole(roleId, teamId) {
return this.http.post(`${this.baseUrl}/${roleId}/teams/`, {
disassociate: true,
id: teamId,
});
}
}
export default Roles;

View File

@@ -4,17 +4,25 @@ import { useLocation, useParams } from 'react-router-dom';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
import { Button } from '@patternfly/react-core'; import {
import { TeamsAPI } from '../../../api'; Button,
EmptyState,
import useRequest from '../../../util/useRequest'; EmptyStateBody,
EmptyStateIcon,
Title,
} from '@patternfly/react-core';
import { CubesIcon } from '@patternfly/react-icons';
import { TeamsAPI, RolesAPI } from '../../../api';
import useRequest, { useDeleteItems } from '../../../util/useRequest';
import DataListToolbar from '../../../components/DataListToolbar'; import DataListToolbar from '../../../components/DataListToolbar';
import PaginatedDataList from '../../../components/PaginatedDataList'; import PaginatedDataList from '../../../components/PaginatedDataList';
import { getQSConfig, parseQueryString } from '../../../util/qs'; import { getQSConfig, parseQueryString } from '../../../util/qs';
import ErrorDetail from '../../../components/ErrorDetail';
import AlertModal from '../../../components/AlertModal';
import TeamAccessListItem from './TeamAccessListItem'; import TeamAccessListItem from './TeamAccessListItem';
import UserAndTeamAccessAdd from '../../../components/UserAndTeamAccessAdd/UserAndTeamAccessAdd'; import UserAndTeamAccessAdd from '../../../components/UserAndTeamAccessAdd/UserAndTeamAccessAdd';
const QS_CONFIG = getQSConfig('team', { const QS_CONFIG = getQSConfig('roles', {
page: 1, page: 1,
page_size: 20, page_size: 20,
order_by: 'id', order_by: 'id',
@@ -24,6 +32,7 @@ function TeamAccessList({ i18n }) {
const [isWizardOpen, setIsWizardOpen] = useState(false); const [isWizardOpen, setIsWizardOpen] = useState(false);
const { search } = useLocation(); const { search } = useLocation();
const { id } = useParams(); const { id } = useParams();
const [roleToDisassociate, setRoleToDisassociate] = useState(null);
const { const {
isLoading, isLoading,
@@ -60,6 +69,21 @@ function TeamAccessList({ i18n }) {
setIsWizardOpen(false); setIsWizardOpen(false);
fetchRoles(); fetchRoles();
}; };
const {
isLoading: isDisassociateLoading,
deleteItems: disassociateRole,
deletionError: disassociationError,
clearDeletionError: clearDisassociationError,
} = useDeleteItems(
useCallback(async () => {
setRoleToDisassociate(null);
await RolesAPI.disassociateTeamRole(
roleToDisassociate.id,
parseInt(id, 10)
);
}, [roleToDisassociate, id]),
{ qsConfig: QS_CONFIG, fetchItems: fetchRoles }
);
const canAdd = const canAdd =
options && Object.prototype.hasOwnProperty.call(options, 'POST'); options && Object.prototype.hasOwnProperty.call(options, 'POST');
@@ -80,11 +104,28 @@ function TeamAccessList({ i18n }) {
return `/${resource_type}s/${resource_id}/details`; return `/${resource_type}s/${resource_id}/details`;
}; };
const isSysAdmin = roles.some(role => role.name === 'System Administrator');
if (isSysAdmin) {
return (
<EmptyState variant="full">
<EmptyStateIcon icon={CubesIcon} />
<Title headingLevel="h5" size="lg">
{i18n._(t`System Administrator`)}
</Title>
<EmptyStateBody>
{i18n._(
t`System administrators have unrestricted access to all resources.`
)}
</EmptyStateBody>
</EmptyState>
);
}
return ( return (
<> <>
<PaginatedDataList <PaginatedDataList
contentError={contentError} contentError={contentError}
hasContentLoading={isLoading} hasContentLoading={isLoading || isDisassociateLoading}
items={roles} items={roles}
itemCount={roleCount} itemCount={roleCount}
pluralizedItemName={i18n._(t`Teams`)} pluralizedItemName={i18n._(t`Teams`)}
@@ -128,7 +169,9 @@ function TeamAccessList({ i18n }) {
key={role.id} key={role.id}
role={role} role={role}
detailUrl={detailUrl(role)} detailUrl={detailUrl(role)}
onSelect={() => {}} onSelect={item => {
setRoleToDisassociate(item);
}}
/> />
)} )}
/> />
@@ -141,6 +184,53 @@ function TeamAccessList({ i18n }) {
title={i18n._(t`Add team permissions`)} title={i18n._(t`Add team permissions`)}
/> />
)} )}
{roleToDisassociate && (
<AlertModal
aria-label={i18n._(t`Disassociate role`)}
isOpen={roleToDisassociate}
variant="error"
title={i18n._(t`Disassociate role!`)}
onClose={() => setRoleToDisassociate(null)}
actions={[
<Button
key="disassociate"
variant="danger"
aria-label={i18n._(t`confirm disassociate`)}
onClick={() => disassociateRole()}
>
{i18n._(t`Disassociate`)}
</Button>,
<Button
key="cancel"
variant="secondary"
aria-label={i18n._(t`Cancel`)}
onClick={() => setRoleToDisassociate(null)}
>
{i18n._(t`Cancel`)}
</Button>,
]}
>
<div>
{i18n._(
t`This action will disassociate the following role from ${roleToDisassociate.summary_fields.resource_name}:`
)}
<br />
<strong>{roleToDisassociate.name}</strong>
</div>
</AlertModal>
)}
{disassociationError && (
<AlertModal
isOpen={disassociationError}
variant="error"
title={i18n._(t`Error!`)}
onClose={clearDisassociationError}
>
{i18n._(t`Failed to delete role.`)}
<ErrorDetail error={disassociationError} />
</AlertModal>
)}
</> </>
); );
} }

View File

@@ -1,8 +1,6 @@
import React from 'react'; import React from 'react';
import { act } from 'react-dom/test-utils'; import { act } from 'react-dom/test-utils';
import { createMemoryHistory } from 'history'; import { TeamsAPI, RolesAPI } from '../../../api';
import { Route } from 'react-router-dom';
import { TeamsAPI } from '../../../api';
import { import {
mountWithContexts, mountWithContexts,
waitForElement, waitForElement,
@@ -10,119 +8,114 @@ import {
import TeamAccessList from './TeamAccessList'; import TeamAccessList from './TeamAccessList';
jest.mock('../../../api/models/Teams'); jest.mock('../../../api/models/Teams');
jest.mock('../../../api/models/Roles');
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: () => ({
id: 18,
}),
}));
const roles = {
data: {
results: [
{
id: 2,
name: 'Admin',
type: 'role',
url: '/api/v2/roles/257/',
summary_fields: {
resource_name: 'template delete project',
resource_id: 15,
resource_type: 'job_template',
resource_type_display_name: 'Job Template',
user_capabilities: { unattach: true },
},
},
{
id: 3,
name: 'Admin Read Only',
type: 'role',
url: '/api/v2/roles/257/',
summary_fields: {
resource_name: 'template delete project',
resource_id: 16,
resource_type: 'workflow_job_template',
resource_type_display_name: 'Job Template',
user_capabilities: { unattach: true },
},
},
{
id: 4,
name: 'Execute',
type: 'role',
url: '/api/v2/roles/258/',
summary_fields: {
resource_name: 'Credential Bar',
resource_id: 75,
resource_type: 'credential',
resource_type_display_name: 'Credential',
user_capabilities: { unattach: true },
},
},
{
id: 5,
name: 'Update',
type: 'role',
url: '/api/v2/roles/259/',
summary_fields: {
resource_name: 'Inventory Foo',
resource_id: 76,
resource_type: 'inventory',
resource_type_display_name: 'Inventory',
user_capabilities: { unattach: true },
},
},
{
id: 6,
name: 'Admin',
type: 'role',
url: '/api/v2/roles/260/',
summary_fields: {
resource_name: 'Smart Inventory Foo',
resource_id: 77,
resource_type: 'smart_inventory',
resource_type_display_name: 'Inventory',
user_capabilities: { unattach: true },
},
},
],
count: 5,
},
};
const options = {
data: { actions: { POST: { id: 1, disassociate: true } } },
};
describe('<TeamAccessList />', () => { describe('<TeamAccessList />', () => {
let wrapper; let wrapper;
let history;
beforeEach(async () => {
TeamsAPI.readRoles.mockResolvedValue({
data: {
results: [
{
id: 2,
name: 'Admin',
type: 'role',
url: '/api/v2/roles/257/',
summary_fields: {
resource_name: 'template delete project',
resource_id: 15,
resource_type: 'job_template',
resource_type_display_name: 'Job Template',
user_capabilities: { unattach: true },
},
},
{
id: 3,
name: 'Admin',
type: 'role',
url: '/api/v2/roles/257/',
summary_fields: {
resource_name: 'template delete project',
resource_id: 16,
resource_type: 'workflow_job_template',
resource_type_display_name: 'Job Template',
user_capabilities: { unattach: true },
},
},
{
id: 4,
name: 'Execute',
type: 'role',
url: '/api/v2/roles/258/',
summary_fields: {
resource_name: 'Credential Bar',
resource_id: 75,
resource_type: 'credential',
resource_type_display_name: 'Credential',
user_capabilities: { unattach: true },
},
},
{
id: 5,
name: 'Update',
type: 'role',
url: '/api/v2/roles/259/',
summary_fields: {
resource_name: 'Inventory Foo',
resource_id: 76,
resource_type: 'inventory',
resource_type_display_name: 'Inventory',
user_capabilities: { unattach: true },
},
},
{
id: 6,
name: 'Admin',
type: 'role',
url: '/api/v2/roles/260/',
summary_fields: {
resource_name: 'Smart Inventory Foo',
resource_id: 77,
resource_type: 'smart_inventory',
resource_type_display_name: 'Inventory',
user_capabilities: { unattach: true },
},
},
],
count: 4,
},
});
TeamsAPI.readRoleOptions.mockResolvedValue({
data: { actions: { POST: { id: 1, disassociate: true } } },
});
history = createMemoryHistory({
initialEntries: ['/teams/18/access'],
});
await act(async () => {
wrapper = mountWithContexts(
<Route path="/teams/:id/access">
<TeamAccessList />
</Route>,
{
context: {
router: {
history,
route: {
location: history.location,
match: { params: { id: 18 } },
},
},
},
}
);
});
});
afterEach(() => { afterEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
wrapper.unmount(); wrapper.unmount();
}); });
test('should render properly', async () => { test('should render properly', async () => {
TeamsAPI.readRoles.mockResolvedValue(roles);
TeamsAPI.readRoleOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<TeamAccessList />);
});
expect(wrapper.find('TeamAccessList').length).toBe(1); expect(wrapper.find('TeamAccessList').length).toBe(1);
}); });
test('should create proper detailUrl', async () => { test('should create proper detailUrl', async () => {
TeamsAPI.readRoles.mockResolvedValue(roles);
TeamsAPI.readRoleOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<TeamAccessList />);
});
waitForElement(wrapper, 'ContentEmpty', el => el.length === 0); waitForElement(wrapper, 'ContentEmpty', el => el.length === 0);
expect(wrapper.find(`Link#teamRole-2`).prop('to')).toBe( expect(wrapper.find(`Link#teamRole-2`).prop('to')).toBe(
@@ -168,22 +161,7 @@ describe('<TeamAccessList />', () => {
}, },
}); });
await act(async () => { await act(async () => {
wrapper = mountWithContexts( wrapper = mountWithContexts(<TeamAccessList />);
<Route path="/teams/:id/access">
<TeamAccessList />
</Route>,
{
context: {
router: {
history,
route: {
location: history.location,
match: { params: { id: 18 } },
},
},
},
}
);
}); });
waitForElement(wrapper, 'ContentEmpty', el => el.length === 0); waitForElement(wrapper, 'ContentEmpty', el => el.length === 0);
@@ -191,17 +169,129 @@ describe('<TeamAccessList />', () => {
0 0
); );
}); });
test('should open and close wizard', async () => {
test('should render disassociate modal', async () => {
TeamsAPI.readRoles.mockResolvedValue(roles);
TeamsAPI.readRoleOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<TeamAccessList />);
});
waitForElement(wrapper, 'ContentEmpty', el => el.length === 0); waitForElement(wrapper, 'ContentEmpty', el => el.length === 0);
await act(async () => await act(async () =>
wrapper.find('Button[aria-label="Add resource roles"]').prop('onClick')() wrapper.find('Chip[aria-label="Execute"]').prop('onClick')({
id: 4,
name: 'Execute',
type: 'role',
url: '/api/v2/roles/258/',
summary_fields: {
resource_name: 'Credential Bar',
resource_id: 75,
resource_type: 'credential',
resource_type_display_name: 'Credential',
user_capabilities: { unattach: true },
},
})
); );
wrapper.update(); wrapper.update();
expect(wrapper.find('PFWizard').length).toBe(1); expect(
wrapper.find('AlertModal[aria-label="Disassociate role"]').length
).toBe(1);
await act(async () => await act(async () =>
wrapper.find("Button[aria-label='Close']").prop('onClick')() wrapper
.find('button[aria-label="confirm disassociate"]')
.prop('onClick')()
);
expect(RolesAPI.disassociateTeamRole).toBeCalledWith(4, 18);
wrapper.update();
expect(
wrapper.find('AlertModal[aria-label="Disassociate role"]').length
).toBe(0);
});
test('should throw disassociation error', async () => {
TeamsAPI.readRoles.mockResolvedValue(roles);
RolesAPI.disassociateTeamRole.mockRejectedValue(
new Error({
response: {
config: {
method: 'post',
url: '/api/v2/roles/18/roles',
},
data: 'An error occurred',
status: 403,
},
})
);
TeamsAPI.readRoleOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<TeamAccessList />);
});
waitForElement(wrapper, 'ContentEmpty', el => el.length === 0);
await act(async () =>
wrapper.find('Chip[aria-label="Execute"]').prop('onClick')({
id: 4,
name: 'Execute',
type: 'role',
url: '/api/v2/roles/258/',
summary_fields: {
resource_name: 'Credential Bar',
resource_id: 75,
resource_type: 'credential',
resource_type_display_name: 'Credential',
user_capabilities: { unattach: true },
},
})
); );
wrapper.update(); wrapper.update();
expect(wrapper.find('PFWizard').length).toBe(0); expect(
wrapper.find('AlertModal[aria-label="Disassociate role"]').length
).toBe(1);
await act(async () =>
wrapper
.find('button[aria-label="confirm disassociate"]')
.prop('onClick')()
);
wrapper.update();
expect(wrapper.find('AlertModal[title="Error!"]').length).toBe(1);
});
test('user with sys admin privilege should show empty state', async () => {
TeamsAPI.readRoles.mockResolvedValue({
data: {
results: [
{
id: 2,
name: 'System Administrator',
type: 'role',
url: '/api/v2/roles/257/',
summary_fields: {
resource_name: 'template delete project',
resource_id: 15,
resource_type: 'job_template',
resource_type_display_name: 'Job Template',
user_capabilities: { unattach: true },
},
},
],
count: 1,
},
});
TeamsAPI.readRoleOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<TeamAccessList />);
});
waitForElement(
wrapper,
'EmptyState[title="System Administrator"]',
el => el.length === 1
);
}); });
}); });

View File

@@ -5,11 +5,13 @@ import {
DataListItem, DataListItem,
DataListItemCells, DataListItemCells,
DataListItemRow, DataListItemRow,
Chip,
} from '@patternfly/react-core'; } from '@patternfly/react-core';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { DetailList, Detail } from '../../../components/DetailList';
import DataListCell from '../../../components/DataListCell'; import DataListCell from '../../../components/DataListCell';
function TeamAccessListItem({ role, i18n, detailUrl }) { function TeamAccessListItem({ role, i18n, detailUrl, onSelect }) {
const labelId = `teamRole-${role.id}`; const labelId = `teamRole-${role.id}`;
return ( return (
<DataListItem key={role.id} aria-labelledby={labelId} id={`${role.id}`}> <DataListItem key={role.id} aria-labelledby={labelId} id={`${role.id}`}>
@@ -23,18 +25,33 @@ function TeamAccessListItem({ role, i18n, detailUrl }) {
</DataListCell>, </DataListCell>,
<DataListCell key="type" aria-label={i18n._(t`resource type`)}> <DataListCell key="type" aria-label={i18n._(t`resource type`)}>
{role.summary_fields && ( {role.summary_fields && (
<> <DetailList stacked>
<b css="margin-right: 24px">{i18n._(t`Type`)}</b> <Detail
{role.summary_fields.resource_type_display_name} label={i18n._(t`Type`)}
</> value={role.summary_fields.resource_type_display_name}
/>
</DetailList>
)} )}
</DataListCell>, </DataListCell>,
<DataListCell key="role" aria-label={i18n._(t`resource role`)}> <DataListCell key="role" aria-label={i18n._(t`resource role`)}>
{role.name && ( {role.name && (
<> <DetailList stacked>
<b css="margin-right: 24px">{i18n._(t`Role`)}</b> <Detail
{role.name} label={i18n._(t`Role`)}
</> value={
<Chip
isReadOnly={
!role.summary_fields.user_capabilities.unattach
}
key={role.name}
aria-label={role.name}
onClick={() => onSelect(role)}
>
{role.name}
</Chip>
}
/>
</DetailList>
)} )}
</DataListCell>, </DataListCell>,
]} ]}

View File

@@ -18,20 +18,25 @@ describe('<TeamAccessListItem/>', () => {
}, },
}; };
beforeEach(() => { test('should mount properly', () => {
wrapper = mountWithContexts( wrapper = mountWithContexts(
<TeamAccessListItem <TeamAccessListItem
role={role} role={role}
detailUrl="/templates/job_template/15/details" detailUrl="/templates/job_template/15/details"
/> />
); );
});
test('should mount properly', () => {
expect(wrapper.length).toBe(1); expect(wrapper.length).toBe(1);
}); });
test('should render proper list item data', () => { test('should render proper list item data', () => {
wrapper = mountWithContexts(
<TeamAccessListItem
role={role}
detailUrl="/templates/job_template/15/details"
/>
);
expect( expect(
wrapper.find('PFDataListCell[aria-label="resource name"]').text() wrapper.find('PFDataListCell[aria-label="resource name"]').text()
).toBe('template delete project'); ).toBe('template delete project');
@@ -42,4 +47,23 @@ describe('<TeamAccessListItem/>', () => {
wrapper.find('PFDataListCell[aria-label="resource role"]').text() wrapper.find('PFDataListCell[aria-label="resource role"]').text()
).toContain('Admin'); ).toContain('Admin');
}); });
test('should render deletable chip', () => {
wrapper = mountWithContexts(
<TeamAccessListItem
role={role}
detailUrl="/templates/job_template/15/details"
/>
);
expect(wrapper.find('Chip').prop('isReadOnly')).toBe(false);
});
test('should render read only chip', () => {
role.summary_fields.user_capabilities.unattach = false;
wrapper = mountWithContexts(
<TeamAccessListItem
role={role}
detailUrl="/templates/job_template/15/details"
/>
);
expect(wrapper.find('Chip').prop('isReadOnly')).toBe(true);
});
}); });

View File

@@ -2,12 +2,21 @@ import React, { useCallback, useEffect, useState } from 'react';
import { useParams, useLocation } from 'react-router-dom'; import { useParams, useLocation } from 'react-router-dom';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
import { Button } from '@patternfly/react-core'; import {
Button,
EmptyState,
EmptyStateBody,
EmptyStateIcon,
Title,
} from '@patternfly/react-core';
import { CubesIcon } from '@patternfly/react-icons';
import { getQSConfig, parseQueryString } from '../../../util/qs'; import { getQSConfig, parseQueryString } from '../../../util/qs';
import { UsersAPI } from '../../../api'; import { UsersAPI, RolesAPI } from '../../../api';
import useRequest from '../../../util/useRequest'; import useRequest, { useDeleteItems } from '../../../util/useRequest';
import PaginatedDataList from '../../../components/PaginatedDataList'; import PaginatedDataList from '../../../components/PaginatedDataList';
import ErrorDetail from '../../../components/ErrorDetail';
import AlertModal from '../../../components/AlertModal';
import DatalistToolbar from '../../../components/DataListToolbar'; import DatalistToolbar from '../../../components/DataListToolbar';
import UserAccessListItem from './UserAccessListItem'; import UserAccessListItem from './UserAccessListItem';
import UserAndTeamAccessAdd from '../../../components/UserAndTeamAccessAdd/UserAndTeamAccessAdd'; import UserAndTeamAccessAdd from '../../../components/UserAndTeamAccessAdd/UserAndTeamAccessAdd';
@@ -25,6 +34,7 @@ function UserAccessList({ i18n }) {
const { search } = useLocation(); const { search } = useLocation();
const [isWizardOpen, setIsWizardOpen] = useState(false); const [isWizardOpen, setIsWizardOpen] = useState(false);
const [roleToDisassociate, setRoleToDisassociate] = useState(null);
const { const {
isLoading, isLoading,
request: fetchRoles, request: fetchRoles,
@@ -54,6 +64,23 @@ function UserAccessList({ i18n }) {
useEffect(() => { useEffect(() => {
fetchRoles(); fetchRoles();
}, [fetchRoles]); }, [fetchRoles]);
const {
isLoading: isDisassociateLoading,
deleteItems: disassociateRole,
deletionError: disassociationError,
clearDeletionError: clearDisassociationError,
} = useDeleteItems(
useCallback(async () => {
setRoleToDisassociate(null);
await RolesAPI.disassociateUserRole(
roleToDisassociate.id,
parseInt(id, 10)
);
}, [roleToDisassociate, id]),
{ qsConfig: QS_CONFIG, fetchItems: fetchRoles }
);
const canAdd = const canAdd =
options && Object.prototype.hasOwnProperty.call(options, 'POST'); options && Object.prototype.hasOwnProperty.call(options, 'POST');
@@ -77,12 +104,27 @@ function UserAccessList({ i18n }) {
} }
return `/${resource_type}s/${resource_id}/details`; return `/${resource_type}s/${resource_id}/details`;
}; };
const isSysAdmin = roles.some(role => role.name === 'System Administrator');
if (isSysAdmin) {
return (
<EmptyState variant="full">
<EmptyStateIcon icon={CubesIcon} />
<Title headingLevel="h5" size="lg">
{i18n._(t`System Administrator`)}
</Title>
<EmptyStateBody>
{i18n._(
t`System administrators have unrestricted access to all resources.`
)}
</EmptyStateBody>
</EmptyState>
);
}
return ( return (
<> <>
<PaginatedDataList <PaginatedDataList
contentError={error} contentError={error}
hasContentLoading={isLoading} hasContentLoading={isLoading || isDisassociateLoading}
items={roles} items={roles}
itemCount={roleCount} itemCount={roleCount}
pluralizedItemName={i18n._(t`User Roles`)} pluralizedItemName={i18n._(t`User Roles`)}
@@ -107,8 +149,10 @@ function UserAccessList({ i18n }) {
value={role.name} value={role.name}
role={role} role={role}
detailUrl={detailUrl(role)} detailUrl={detailUrl(role)}
onSelect={() => {}}
isSelected={false} isSelected={false}
onSelect={item => {
setRoleToDisassociate(item);
}}
/> />
); );
}} }}
@@ -143,6 +187,52 @@ function UserAccessList({ i18n }) {
title={i18n._(t`Add user permissions`)} title={i18n._(t`Add user permissions`)}
/> />
)} )}
{roleToDisassociate && (
<AlertModal
aria-label={i18n._(t`Disassociate role`)}
isOpen={roleToDisassociate}
variant="error"
title={i18n._(t`Disassociate role!`)}
onClose={() => setRoleToDisassociate(null)}
actions={[
<Button
key="disassociate"
variant="danger"
aria-label={i18n._(t`confirm disassociate`)}
onClick={() => disassociateRole()}
>
{i18n._(t`Disassociate`)}
</Button>,
<Button
key="cancel"
variant="secondary"
aria-label={i18n._(t`Cancel`)}
onClick={() => setRoleToDisassociate(null)}
>
{i18n._(t`Cancel`)}
</Button>,
]}
>
<div>
{i18n._(
t`This action will disassociate the following role from ${roleToDisassociate.summary_fields.resource_name}:`
)}
<br />
<strong>{roleToDisassociate.name}</strong>
</div>
</AlertModal>
)}
{disassociationError && (
<AlertModal
isOpen={disassociationError}
variant="error"
title={i18n._(t`Error!`)}
onClose={clearDisassociationError}
>
{i18n._(t`Failed to delete role.`)}
<ErrorDetail error={disassociationError} />
</AlertModal>
)}
</> </>
); );
} }

View File

@@ -1,8 +1,6 @@
import React from 'react'; import React from 'react';
import { act } from 'react-dom/test-utils'; import { act } from 'react-dom/test-utils';
import { createMemoryHistory } from 'history'; import { UsersAPI, RolesAPI } from '../../../api';
import { Route } from 'react-router-dom';
import { UsersAPI } from '../../../api';
import { import {
mountWithContexts, mountWithContexts,
waitForElement, waitForElement,
@@ -10,124 +8,114 @@ import {
import UserAccessList from './UserAccessList'; import UserAccessList from './UserAccessList';
jest.mock('../../../api/models/Users'); jest.mock('../../../api/models/Users');
jest.mock('../../../api/models/Roles');
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: () => ({
id: 18,
}),
}));
const roles = {
data: {
results: [
{
id: 2,
name: 'Admin',
type: 'role',
url: '/api/v2/roles/257/',
summary_fields: {
resource_name: 'template delete project',
resource_id: 15,
resource_type: 'job_template',
resource_type_display_name: 'Job Template',
user_capabilities: { unattach: true },
},
},
{
id: 3,
name: 'Admin',
type: 'role',
url: '/api/v2/roles/257/',
summary_fields: {
resource_name: 'template delete project',
resource_id: 16,
resource_type: 'workflow_job_template',
resource_type_display_name: 'Job Template',
user_capabilities: { unattach: true },
},
},
{
id: 4,
name: 'Execute',
type: 'role',
url: '/api/v2/roles/258/',
summary_fields: {
resource_name: 'Credential Bar',
resource_id: 75,
resource_type: 'credential',
resource_type_display_name: 'Credential',
user_capabilities: { unattach: true },
},
},
{
id: 5,
name: 'Update',
type: 'role',
url: '/api/v2/roles/259/',
summary_fields: {
resource_name: 'Inventory Foo',
resource_id: 76,
resource_type: 'inventory',
resource_type_display_name: 'Inventory',
user_capabilities: { unattach: true },
},
},
{
id: 6,
name: 'Admin',
type: 'role',
url: '/api/v2/roles/260/',
summary_fields: {
resource_name: 'Smart Inventory Foo',
resource_id: 77,
resource_type: 'smart_inventory',
resource_type_display_name: 'Inventory',
user_capabilities: { unattach: true },
},
},
],
count: 5,
},
};
const options = {
data: { actions: { POST: { id: 1, disassociate: true } } },
};
describe('<UserAccessList />', () => { describe('<UserAccessList />', () => {
let wrapper; let wrapper;
let history;
beforeEach(async () => {
UsersAPI.readRoles.mockResolvedValue({
data: {
results: [
{
id: 2,
name: 'Admin',
type: 'role',
url: '/api/v2/roles/257/',
summary_fields: {
resource_name: 'template delete project',
resource_id: 15,
resource_type: 'job_template',
resource_type_display_name: 'Job Template',
user_capabilities: { unattach: true },
},
description: 'Can manage all aspects of the job template',
},
{
id: 3,
name: 'Admin',
type: 'role',
url: '/api/v2/roles/257/',
summary_fields: {
resource_name: 'template delete project',
resource_id: 16,
resource_type: 'workflow_job_template',
resource_type_display_name: 'Job Template',
user_capabilities: { unattach: true },
},
description: 'Can manage all aspects of the job template',
},
{
id: 4,
name: 'Execute',
type: 'role',
url: '/api/v2/roles/258/',
summary_fields: {
resource_name: 'Credential Bar',
resource_id: 75,
resource_type: 'credential',
resource_type_display_name: 'Credential',
user_capabilities: { unattach: true },
},
description: 'May run the job template',
},
{
id: 5,
name: 'Read',
type: 'role',
url: '/api/v2/roles/259/',
summary_fields: {
resource_name: 'Inventory Foo',
resource_id: 76,
resource_type: 'inventory',
resource_type_display_name: 'Inventory',
user_capabilities: { unattach: true },
},
description: 'May view settings for the job template',
},
{
id: 6,
name: 'Admin',
type: 'role',
url: '/api/v2/roles/260/',
summary_fields: {
resource_name: 'Project Foo',
resource_id: 77,
resource_type: 'project',
resource_type_display_name: 'Project',
user_capabilities: { unattach: true },
},
description: 'Can manage all aspects of the job template',
},
],
count: 5,
},
});
UsersAPI.readRoleOptions.mockResolvedValue({
data: { actions: { POST: { id: 1, disassociate: true } } },
});
history = createMemoryHistory({
initialEntries: ['/users/18/access'],
});
await act(async () => {
wrapper = mountWithContexts(
<Route path="/users/:id/access">
<UserAccessList />
</Route>,
{
context: {
router: {
history,
route: {
location: history.location,
match: { params: { id: 18 } },
},
},
},
}
);
});
});
afterEach(() => { afterEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
wrapper.unmount(); // wrapper.unmount();
}); });
test('should render properly', async () => { test('should render properly', async () => {
UsersAPI.readRoles.mockResolvedValue(roles);
UsersAPI.readRoleOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<UserAccessList />);
});
expect(wrapper.find('UserAccessList').length).toBe(1); expect(wrapper.find('UserAccessList').length).toBe(1);
}); });
test('should create proper detailUrl', async () => { test('should create proper detailUrl', async () => {
UsersAPI.readRoles.mockResolvedValue(roles);
UsersAPI.readRoleOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<UserAccessList />);
});
waitForElement(wrapper, 'ContentEmpty', el => el.length === 0); waitForElement(wrapper, 'ContentEmpty', el => el.length === 0);
expect(wrapper.find(`Link#userRole-2`).prop('to')).toBe( expect(wrapper.find(`Link#userRole-2`).prop('to')).toBe(
@@ -143,7 +131,7 @@ describe('<UserAccessList />', () => {
'/inventories/inventory/76/details' '/inventories/inventory/76/details'
); );
expect(wrapper.find('Link#userRole-6').prop('to')).toBe( expect(wrapper.find('Link#userRole-6').prop('to')).toBe(
'/projects/77/details' '/inventories/smart_inventory/77/details'
); );
}); });
test('should not render add button', async () => { test('should not render add button', async () => {
@@ -189,22 +177,7 @@ describe('<UserAccessList />', () => {
}, },
}); });
await act(async () => { await act(async () => {
wrapper = mountWithContexts( wrapper = mountWithContexts(<UserAccessList />);
<Route path="/users/:id/access">
<UserAccessList />
</Route>,
{
context: {
router: {
history,
route: {
location: history.location,
match: { params: { id: 18 } },
},
},
},
}
);
}); });
waitForElement(wrapper, 'ContentEmpty', el => el.length === 0); waitForElement(wrapper, 'ContentEmpty', el => el.length === 0);
@@ -213,6 +186,11 @@ describe('<UserAccessList />', () => {
); );
}); });
test('should open and close wizard', async () => { test('should open and close wizard', async () => {
UsersAPI.readRoles.mockResolvedValue(roles);
UsersAPI.readRoleOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<UserAccessList />);
});
waitForElement(wrapper, 'ContentEmpty', el => el.length === 0); waitForElement(wrapper, 'ContentEmpty', el => el.length === 0);
await act(async () => await act(async () =>
wrapper.find('Button[aria-label="Add resource roles"]').prop('onClick')() wrapper.find('Button[aria-label="Add resource roles"]').prop('onClick')()
@@ -225,4 +203,126 @@ describe('<UserAccessList />', () => {
wrapper.update(); wrapper.update();
expect(wrapper.find('PFWizard').length).toBe(0); expect(wrapper.find('PFWizard').length).toBe(0);
}); });
test('should render disassociate modal', async () => {
UsersAPI.readRoles.mockResolvedValue(roles);
UsersAPI.readRoleOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<UserAccessList />);
});
waitForElement(wrapper, 'ContentEmpty', el => el.length === 0);
await act(async () =>
wrapper.find('Chip[aria-label="Execute"]').prop('onClick')({
id: 4,
name: 'Execute',
type: 'role',
url: '/api/v2/roles/258/',
summary_fields: {
resource_name: 'Credential Bar',
resource_id: 75,
resource_type: 'credential',
resource_type_display_name: 'Credential',
user_capabilities: { unattach: true },
},
})
);
wrapper.update();
expect(
wrapper.find('AlertModal[aria-label="Disassociate role"]').length
).toBe(1);
await act(async () =>
wrapper
.find('button[aria-label="confirm disassociate"]')
.prop('onClick')()
);
expect(RolesAPI.disassociateUserRole).toBeCalledWith(4, 18);
wrapper.update();
expect(
wrapper.find('AlertModal[aria-label="Disassociate role"]').length
).toBe(0);
});
test('should throw disassociation error', async () => {
UsersAPI.readRoles.mockResolvedValue(roles);
RolesAPI.disassociateUserRole.mockRejectedValue(
new Error({
response: {
config: {
method: 'post',
url: '/api/v2/roles/18/roles',
},
data: 'An error occurred',
status: 403,
},
})
);
UsersAPI.readRoleOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<UserAccessList />);
});
waitForElement(wrapper, 'ContentEmpty', el => el.length === 0);
await act(async () =>
wrapper.find('Chip[aria-label="Execute"]').prop('onClick')({
id: 4,
name: 'Execute',
type: 'role',
url: '/api/v2/roles/258/',
summary_fields: {
resource_name: 'Credential Bar',
resource_id: 75,
resource_type: 'credential',
resource_type_display_name: 'Credential',
user_capabilities: { unattach: true },
},
})
);
wrapper.update();
expect(
wrapper.find('AlertModal[aria-label="Disassociate role"]').length
).toBe(1);
await act(async () =>
wrapper
.find('button[aria-label="confirm disassociate"]')
.prop('onClick')()
);
wrapper.update();
expect(wrapper.find('AlertModal[title="Error!"]').length).toBe(1);
});
test('user with sys admin privilege should show empty state', async () => {
UsersAPI.readRoles.mockResolvedValue({
data: {
results: [
{
id: 2,
name: 'System Administrator',
type: 'role',
url: '/api/v2/roles/257/',
summary_fields: {
resource_name: 'template delete project',
resource_id: 15,
resource_type: 'job_template',
resource_type_display_name: 'Job Template',
user_capabilities: { unattach: true },
},
},
],
count: 1,
},
});
UsersAPI.readRoleOptions.mockResolvedValue(options);
await act(async () => {
wrapper = mountWithContexts(<UserAccessList />);
});
waitForElement(
wrapper,
'EmptyState[title="System Administrator"]',
el => el.length === 1
);
});
}); });

View File

@@ -5,11 +5,13 @@ import {
DataListItem, DataListItem,
DataListItemCells, DataListItemCells,
DataListItemRow, DataListItemRow,
Chip,
} from '@patternfly/react-core'; } from '@patternfly/react-core';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { DetailList, Detail } from '../../../components/DetailList';
import DataListCell from '../../../components/DataListCell'; import DataListCell from '../../../components/DataListCell';
function UserAccessListItem({ role, i18n, detailUrl }) { function UserAccessListItem({ role, i18n, detailUrl, onSelect }) {
const labelId = `userRole-${role.id}`; const labelId = `userRole-${role.id}`;
return ( return (
<DataListItem key={role.id} aria-labelledby={labelId} id={`${role.id}`}> <DataListItem key={role.id} aria-labelledby={labelId} id={`${role.id}`}>
@@ -23,18 +25,33 @@ function UserAccessListItem({ role, i18n, detailUrl }) {
</DataListCell>, </DataListCell>,
<DataListCell key="type" aria-label={i18n._(t`resource type`)}> <DataListCell key="type" aria-label={i18n._(t`resource type`)}>
{role.summary_fields && ( {role.summary_fields && (
<> <DetailList stacked>
<b css="margin-right: 24px">{i18n._(t`Type`)}</b> <Detail
{role.summary_fields.resource_type_display_name} label={i18n._(t`Type`)}
</> value={role.summary_fields.resource_type_display_name}
/>
</DetailList>
)} )}
</DataListCell>, </DataListCell>,
<DataListCell key="role" aria-label={i18n._(t`resource role`)}> <DataListCell key="role" aria-label={i18n._(t`resource role`)}>
{role.name && ( {role.name && (
<> <DetailList stacked>
<b css="margin-right: 24px">{i18n._(t`Role`)}</b> <Detail
{role.name} label={i18n._(t`Role`)}
</> value={
<Chip
isReadOnly={
!role.summary_fields.user_capabilities.unattach
}
key={role.name}
aria-label={role.name}
onClick={() => onSelect(role)}
>
{role.name}
</Chip>
}
/>
</DetailList>
)} )}
</DataListCell>, </DataListCell>,
]} ]}

View File

@@ -17,21 +17,23 @@ describe('<UserAccessListItem/>', () => {
user_capabilities: { unattach: true }, user_capabilities: { unattach: true },
}, },
}; };
test('should mount properly', () => {
beforeEach(() => {
wrapper = mountWithContexts( wrapper = mountWithContexts(
<UserAccessListItem <UserAccessListItem
role={role} role={role}
detailUrl="/templates/job_template/15/details" detailUrl="/templates/job_template/15/details"
/> />
); );
});
test('should mount properly', () => {
expect(wrapper.length).toBe(1); expect(wrapper.length).toBe(1);
}); });
test('should render proper list item data', () => { test('should render proper list item data', () => {
wrapper = mountWithContexts(
<UserAccessListItem
role={role}
detailUrl="/templates/job_template/15/details"
/>
);
expect( expect(
wrapper.find('PFDataListCell[aria-label="resource name"]').text() wrapper.find('PFDataListCell[aria-label="resource name"]').text()
).toBe('template delete project'); ).toBe('template delete project');
@@ -42,4 +44,23 @@ describe('<UserAccessListItem/>', () => {
wrapper.find('PFDataListCell[aria-label="resource role"]').text() wrapper.find('PFDataListCell[aria-label="resource role"]').text()
).toContain('Admin'); ).toContain('Admin');
}); });
test('should render deletable chip', () => {
wrapper = mountWithContexts(
<UserAccessListItem
role={role}
detailUrl="/templates/job_template/15/details"
/>
);
expect(wrapper.find('Chip').prop('isReadOnly')).toBe(false);
});
test('should render read only chip', () => {
role.summary_fields.user_capabilities.unattach = false;
wrapper = mountWithContexts(
<UserAccessListItem
role={role}
detailUrl="/templates/job_template/15/details"
/>
);
expect(wrapper.find('Chip').prop('isReadOnly')).toBe(true);
});
}); });