Skip to content
47 changes: 47 additions & 0 deletions src/authz-module/authz-home/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,19 @@ import userEvent from '@testing-library/user-event';
import { ToastManagerProvider } from '@src/components/ToastManager/ToastManagerContext';
import { useViewTeamPermissions } from '@src/authz-module/hooks/useViewTeamPermissions';
import { CustomErrors } from '@src/constants';
import { getAuthenticatedUser, usePermissions } from '@openedx/frontend-base';
import { SCOPE_TYPES } from '@src/authz-module/constants';
import baseMessages from '@src/authz-module/messages';
import { useCanManageRoles } from '@src/authz-module/hooks/useCanManageRoles';
import AuthzHome from './index';
import messages from './messages';

jest.mock('@src/authz-module/hooks/useCanManageRoles', () => ({
useCanManageRoles: jest.fn(),
}));

const mockUseCanManageRoles = useCanManageRoles as jest.Mock;

jest.mock('@src/authz-module/catalog/data/hooks', () => ({
useAuthzCatalog: jest.fn(),
useCatalogRoles: jest.fn(),
Expand All @@ -27,6 +37,13 @@ jest.mock('@src/authz-module/hooks/useViewTeamPermissions', () => ({
useViewTeamPermissions: jest.fn(),
}));

jest.mock('@openedx/frontend-base', () => ({
...jest.requireActual('@openedx/frontend-base'),
// The manage-team answer: by default the user can manage no team.
getAuthenticatedUser: jest.fn(() => ({ administrator: true })),
usePermissions: jest.fn(() => ({ 'course-v1': false, lib: false, isLoading: false })),
}));

jest.mock('@src/authz-module/data/hooks', () => ({
useTeamMembersAssignments: jest.fn(),
useOrgs: jest.fn(),
Expand Down Expand Up @@ -72,8 +89,10 @@ describe('AuthzHome', () => {
beforeEach(() => {
// Call history is asserted on below, so it must not carry over between cases.
jest.clearAllMocks();
(getAuthenticatedUser as jest.Mock).mockReturnValue({ administrator: true });
mockAuthzCatalog();
mockViewTeamPermissions({ isCourseViewAllowed: true, isLibraryViewAllowed: true, isLoading: false });
mockUseCanManageRoles.mockReturnValue(true);
(useTeamMembersAssignments as jest.Mock).mockReturnValue(emptyResponse);
(useOrgs as jest.Mock).mockReturnValue(emptyResponse);
(useScopes as jest.Mock).mockReturnValue(emptyScopesResponse);
Expand Down Expand Up @@ -161,4 +180,32 @@ describe('AuthzHome', () => {
expect(teamTab.getAllByText('Role').length).toBe(1);
expect(teamTab.getByText('Actions')).toBeInTheDocument();
});

it('shows the assign role button', async () => {
(usePermissions as jest.Mock).mockReturnValue({
[SCOPE_TYPES.COURSE]: false, [SCOPE_TYPES.LIBRARY]: true, isLoading: false,
});
renderAuthzHome();
const assignRoleButton = () => screen.getByRole('button', {
name: baseMessages['authz.management.assign.role.title'].defaultMessage,
});

expect(assignRoleButton()).toHaveClass('btn-primary');
});

it('shows the create custom role button only to the users allowed', async () => {
mockUseCanManageRoles.mockReturnValue(true);
renderAuthzHome();
const createCustomRoleButton = () => screen.queryByRole('button', { name: 'Create Custom Role' });

expect(createCustomRoleButton()).toBeInTheDocument();
});

it('hides the create custom role button from non-staff users', async () => {
const user = userEvent.setup();
mockUseCanManageRoles.mockReturnValue(false);
renderAuthzHome();
await user.click(screen.getByRole('tab', { name: messages['authz.tabs.permissionsRoles'].defaultMessage }));
expect(screen.queryByRole('button', { name: 'Create Custom Role' })).not.toBeInTheDocument();
});
});
23 changes: 16 additions & 7 deletions src/authz-module/authz-home/index.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,35 @@
import { useState } from 'react';
import { useIntl } from '@openedx/frontend-base';
import { Tab, Tabs } from '@openedx/paragon';
import { PersonAdd } from '@openedx/paragon/icons';
import { useLocation, useSearchParams } from 'react-router-dom';
import { TeamMembersTable } from '@src/authz-module/team-members';
import AddRoleButton from '@src/authz-module/components/AddRoleButton';
import { useViewTeamPermissions } from '@src/authz-module/hooks/useViewTeamPermissions';
import { CustomErrors } from '@src/constants';
import LoadingPage from '@src/components/LoadingPage';
import { RolesPermissionsTable } from '@src/authz-module/roles-permissions';
import { RolesPermissionsTable, CreateCustomRole } from '@src/authz-module/roles-permissions';
import AuthZLayout from '@src/authz-module/components/AuthZLayout';

import messages from './messages';
import { useCanManageRoles } from '@src/authz-module/hooks/useCanManageRoles';

type AuthzHomeTab = 'team' | 'permissionsRoles';

const AuthzHome = () => {
const { hash } = useLocation();
const intl = useIntl();
const [searchParams] = useSearchParams();
// Controlled so the header actions can follow the active tab.
const [activeTab, setActiveTab] = useState<AuthzHomeTab>(hash ? 'permissionsRoles' : 'team');

/* In the authoring repository the scope is encoded but this is to Replace spaces with '+'
to match URL encoding format in case the 'scope' parameter is provided with spaces instead of '+'
*/
const presetScope = searchParams.get('scope')?.replace(/\s/g, '+') || undefined;

const showCreateCustomRole = useCanManageRoles();

const pageTitle = intl.formatMessage(messages['authz.manage.page.title']);

const {
Expand All @@ -47,15 +56,15 @@ const AuthzHome = () => {
return (
<AuthZLayout
pageTitle={pageTitle}
// TODO: add the "Create Custom Role" header button, tracked in
// https://github.com/openedx/openedx-authz/issues/571
actions={
[<AddRoleButton key="add-role-button" />]
}
actions={[
...(showCreateCustomRole ? [<CreateCustomRole key="create-custom-role" />] : []),
<AddRoleButton key="add-role-button" iconBefore={PersonAdd} variant="primary" />
]}
>
<Tabs
variant="tabs"
defaultActiveKey={hash ? 'permissionsRoles' : 'team'}
activeKey={activeTab}
onSelect={(key: string | null) => key && setActiveTab(key as AuthzHomeTab)}
className="page-band bg-light-100"
>
<Tab eventKey="team" title={intl.formatMessage(messages['authz.tabs.team'])} className="page-band py-3">
Expand Down
6 changes: 4 additions & 2 deletions src/authz-module/components/AddRoleButton.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, type ComponentType } from 'react';
import { useState, type ComponentProps, type ComponentType } from 'react';
import { useIntl } from '@openedx/frontend-base';
import { Button } from '@openedx/paragon';
import { Plus } from '@openedx/paragon/icons';
Expand All @@ -9,6 +9,7 @@ import { AssignRoleWizard, useAssignableRoleGroups } from '@src/authz-module/rol
interface AddRoleButtonProps {
presetUsername?: string;
iconBefore?: ComponentType;
variant?: ComponentProps<typeof Button>['variant'];
}

/**
Expand All @@ -19,7 +20,7 @@ interface AddRoleButtonProps {
* The wizard is mounted only while open, never hidden: each opening gets its own state
* and its own request state
*/
const AddRoleButton = ({ presetUsername, iconBefore = Plus }: AddRoleButtonProps) => {
const AddRoleButton = ({ presetUsername, iconBefore = Plus, variant = 'primary' }: AddRoleButtonProps) => {
const intl = useIntl();
const [isWizardOpen, setIsWizardOpen] = useState(false);

Expand All @@ -37,6 +38,7 @@ const AddRoleButton = ({ presetUsername, iconBefore = Plus }: AddRoleButtonProps
size="sm"
iconBefore={iconBefore}
onClick={() => setIsWizardOpen(true)}
variant={variant}
>
{intl.formatMessage(baseMessages['authz.management.assign.role.title'])}
</Button>
Expand Down
6 changes: 2 additions & 4 deletions src/authz-module/components/AuthZTitle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,9 @@ const AuthZTitle = ({
</div>
</Col>
<Col xs={12} md={5}>
<Stack className="justify-content-end" direction={isDesktop ? 'horizontal' : 'vertical'}>
<Stack className="justify-content-end" direction={isDesktop ? 'horizontal' : 'vertical'} gap={2}>
{
actions.map((action, index) => {
actions.map((action) => {
const content = isValidElement(action)
? action
: <ActionButton {...action as Action} />;
Expand All @@ -87,8 +87,6 @@ const AuthZTitle = ({
return (
<Fragment key={`authz-header-action-${key}`}>
{content}
{(index === actions.length - 1) ? null
: (<hr className="authz-action-divider mx-lg-5" />)}
</Fragment>
);
})
Expand Down
21 changes: 21 additions & 0 deletions src/authz-module/data/api.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
getScopes,
getCourseAuthoringFlagStates,
getRoleAssignments,
validateRoleName,
} from './api';
import { SCOPE_TYPES } from '../constants';

Expand Down Expand Up @@ -319,4 +320,24 @@ describe('API functions', () => {
});
});
});

describe('validateRoleName', () => {
it('posts the name as display_name and returns the result', async () => {
const post = jest.fn().mockResolvedValue({
data: {
displayName: 'Library Designer', available: false, reason: 'taken', message: 'taken',
},
});
mockHttpClient().mockReturnValue({ post });

const result = await validateRoleName('Library Designer');

expect(post).toHaveBeenCalledWith(
expect.stringContaining('/api/authz/v1/roles/validate-name/'),
{ display_name: 'Library Designer' },
);
expect(result.available).toBe(false);
expect(result.reason).toBe('taken');
});
});
});
20 changes: 20 additions & 0 deletions src/authz-module/data/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,14 @@ export interface ValidateUsersResponse {
};
}

export interface ValidateRoleNameResponse {
displayName: string;
available: boolean;
// `taken` when another role already uses the name, `invalid` when it breaks the name rules.
reason: 'taken' | 'invalid' | null;
message: string | null;
}

export interface GetScopesParams {
scopeType?: string;
search?: string;
Expand Down Expand Up @@ -134,6 +142,18 @@ export const validateUsers = async (
return camelCaseObject(res.data);
};

/**
* Checks whether a custom role name is free. It is not a reservation: creating the role can
* still conflict if someone else takes the name first.
*/
export const validateRoleName = async (displayName: string): Promise<ValidateRoleNameResponse> => {
const res = await getAuthenticatedHttpClient().post(
getApiUrl('/api/authz/v1/roles/validate-name/'),
{ display_name: displayName },
);
return camelCaseObject(res.data);
};

export const revokeUserRoles = async (
data: RevokeUserRolesRequest,
): Promise<DeleteRevokeUserRolesResponse> => {
Expand Down
33 changes: 33 additions & 0 deletions src/authz-module/data/hooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
useScopes,
useUserAssignedRoles,
useValidateUsers,
useValidateRoleName,
useCourseAuthoringFlagStates,
} from './hooks';

Expand Down Expand Up @@ -263,6 +264,38 @@ describe('useValidateUsers', () => {
});
});

describe('useValidateRoleName', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('returns whether the role name is available', async () => {
const mockResponse = { displayName: 'Designer', available: true, reason: null };
const post = jest.fn().mockResolvedValue({ data: mockResponse });
mockHttpClient().mockReturnValue({ post });

const { result } = renderHook(() => useValidateRoleName(), { wrapper: createWrapper() });
await act(async () => {
result.current.mutate('Designer');
});

await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(post).toHaveBeenCalledWith(expect.any(String), { display_name: 'Designer' });
expect(result.current.data).toEqual(mockResponse);
});

it('exposes the error when the request fails', async () => {
mockHttpClient().mockReturnValue({ post: jest.fn().mockRejectedValue(new Error('boom')) });

const { result } = renderHook(() => useValidateRoleName(), { wrapper: createWrapper() });
await act(async () => {
result.current.mutate('Designer');
});

await waitFor(() => expect(result.current.isError).toBe(true));
});
});

describe('useScopes', () => {
beforeEach(() => {
jest.clearAllMocks();
Expand Down
13 changes: 12 additions & 1 deletion src/authz-module/data/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
GetTeamMembersAssignmentsResponse, getOrgs, GetOrgsResponse,
getScopes, GetScopesResponse, QuerySettings, revokeUserRoles,
RevokeUserRolesRequest, getUserAssignedRoles, GetUserAssignmentsResponse,
validateUsers, ValidateUsersRequest, GetScopesParams,
validateUsers, ValidateUsersRequest, GetScopesParams, validateRoleName,
getCourseAuthoringFlagStates, CourseAuthoringFlagStates,
getRoleAssignments, GetRoleAssignmentsResponse,
} from './api';
Expand Down Expand Up @@ -65,6 +65,17 @@ export const useValidateUsers = () => useMutation({
}) => validateUsers(data),
});

/**
* React Query hook to check whether a custom role name is available.
*
* @example
* const { mutateAsync: validateRoleName } = useValidateRoleName();
* const { available, reason } = await validateRoleName('Library Designer');
*/
export const useValidateRoleName = () => useMutation({
mutationFn: (displayName: string) => validateRoleName(displayName),
});

/**
* React Query hook to remove roles for a specific team member within a scope.
*
Expand Down
28 changes: 27 additions & 1 deletion src/authz-module/index.scss
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,34 @@
}
}

// Create custom role wizard chrome, on top of the shared wizard chrome below.
.pgn__modal.create-custom-role-wizard {
.create-custom-role-wizard__step:focus {
outline: none;
}

.create-custom-role-wizard__start-from .pgn__selectable_box {
padding: var(--pgn-spacing-spacer-2-5) var(--pgn-spacing-spacer-3);
cursor: pointer;

&.pgn__selectable_box-active {
background-color: var(--pgn-color-info-100);

.create-custom-role-wizard__option-title {
color: var(--pgn-color-info-500);
}
}
}

.create-custom-role-wizard__source-role-menu {
max-height: 480px;
overflow-y: auto;
}
}

// Wizard modal chrome. `.pgn__modal` only to outrank Paragon's `-dark` header rule.
.pgn__modal.assign-role-wizard {
.pgn__modal.assign-role-wizard,
.pgn__modal.create-custom-role-wizard {
// Matches the Next button, via the button's own token so a theme keeps them in step.
.pgn__modal-header {
background-color: var(--pgn-color-btn-bg-primary);
Expand Down
Loading