diff --git a/src/authz-module/authz-home/index.test.tsx b/src/authz-module/authz-home/index.test.tsx index fdda1f2d..a7d9b911 100644 --- a/src/authz-module/authz-home/index.test.tsx +++ b/src/authz-module/authz-home/index.test.tsx @@ -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(), @@ -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(), @@ -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); @@ -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(); + }); }); diff --git a/src/authz-module/authz-home/index.tsx b/src/authz-module/authz-home/index.tsx index 074b19e9..c4237efa 100644 --- a/src/authz-module/authz-home/index.tsx +++ b/src/authz-module/authz-home/index.tsx @@ -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(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 { @@ -47,15 +56,15 @@ const AuthzHome = () => { return ( ] - } + actions={[ + ...(showCreateCustomRole ? [] : []), + + ]} > key && setActiveTab(key as AuthzHomeTab)} className="page-band bg-light-100" > diff --git a/src/authz-module/components/AddRoleButton.tsx b/src/authz-module/components/AddRoleButton.tsx index b0fddc66..9f169477 100644 --- a/src/authz-module/components/AddRoleButton.tsx +++ b/src/authz-module/components/AddRoleButton.tsx @@ -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'; @@ -9,6 +9,7 @@ import { AssignRoleWizard, useAssignableRoleGroups } from '@src/authz-module/rol interface AddRoleButtonProps { presetUsername?: string; iconBefore?: ComponentType; + variant?: ComponentProps['variant']; } /** @@ -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); @@ -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'])} diff --git a/src/authz-module/components/AuthZTitle.tsx b/src/authz-module/components/AuthZTitle.tsx index 6cf40a45..3326ea48 100644 --- a/src/authz-module/components/AuthZTitle.tsx +++ b/src/authz-module/components/AuthZTitle.tsx @@ -75,9 +75,9 @@ const AuthZTitle = ({ - + { - actions.map((action, index) => { + actions.map((action) => { const content = isValidElement(action) ? action : ; @@ -87,8 +87,6 @@ const AuthZTitle = ({ return ( {content} - {(index === actions.length - 1) ? null - : (
)}
); }) diff --git a/src/authz-module/data/api.test.tsx b/src/authz-module/data/api.test.tsx index 15edbbce..b14a0474 100644 --- a/src/authz-module/data/api.test.tsx +++ b/src/authz-module/data/api.test.tsx @@ -8,6 +8,7 @@ import { getScopes, getCourseAuthoringFlagStates, getRoleAssignments, + validateRoleName, } from './api'; import { SCOPE_TYPES } from '../constants'; @@ -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'); + }); + }); }); diff --git a/src/authz-module/data/api.ts b/src/authz-module/data/api.ts index 13362911..f431c71d 100644 --- a/src/authz-module/data/api.ts +++ b/src/authz-module/data/api.ts @@ -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; @@ -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 => { + 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 => { diff --git a/src/authz-module/data/hooks.test.tsx b/src/authz-module/data/hooks.test.tsx index 76d9b827..45d66db3 100644 --- a/src/authz-module/data/hooks.test.tsx +++ b/src/authz-module/data/hooks.test.tsx @@ -12,6 +12,7 @@ import { useScopes, useUserAssignedRoles, useValidateUsers, + useValidateRoleName, useCourseAuthoringFlagStates, } from './hooks'; @@ -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(); diff --git a/src/authz-module/data/hooks.ts b/src/authz-module/data/hooks.ts index cd1f4f78..a9bfb8d2 100644 --- a/src/authz-module/data/hooks.ts +++ b/src/authz-module/data/hooks.ts @@ -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'; @@ -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. * diff --git a/src/authz-module/index.scss b/src/authz-module/index.scss index 7090e534..ab09f71c 100644 --- a/src/authz-module/index.scss +++ b/src/authz-module/index.scss @@ -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); diff --git a/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx b/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx new file mode 100644 index 00000000..76f9630a --- /dev/null +++ b/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx @@ -0,0 +1,404 @@ +import { screen, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { renderWithAllProviders } from '@src/testUtils'; +import { authzCatalog, buildCatalogRole, mockAuthzCatalog } from '@src/authz-module/catalog/testUtils'; +import { SCOPE_TYPES } from '@src/authz-module/constants'; +import { useValidateRoleName } from '../../data/hooks'; +import CreateCustomRole from './CreateCustomRole'; + +jest.mock('@src/authz-module/catalog/data/hooks', () => ({ + useAuthzCatalog: jest.fn(), +})); + +jest.mock('../../data/hooks', () => ({ + useValidateRoleName: jest.fn(), +})); + +const mockValidateRoleName = jest.fn(); + +const catalogWithCustomRole = { + ...authzCatalog, + roles: [ + ...authzCatalog.roles, + buildCatalogRole('technique_auditor', { + displayName: 'Technique auditor', + definitionKind: 'user_defined', + permissions: ['courses.view_course'], + scopeTypes: [SCOPE_TYPES.COURSE], + }), + ], +}; + +const openWizard = async () => { + const user = userEvent.setup(); + renderWithAllProviders(); + await user.click(screen.getByRole('button', { name: 'Create Custom Role' })); + return user; +}; + +const getNextButton = () => screen.getByRole('button', { name: 'Next' }); +// Next stays focusable while a required answer is missing, so it reports it instead of being disabled. +const expectNextBlocked = () => expect(getNextButton()).toHaveAttribute('aria-disabled', 'true'); +const expectNextAllowed = () => expect(getNextButton()).toHaveAttribute('aria-disabled', 'false'); + +describe('CreateCustomRole', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockAuthzCatalog({ catalog: catalogWithCustomRole }); + mockValidateRoleName.mockResolvedValue({ available: true, reason: null }); + (useValidateRoleName as jest.Mock).mockReturnValue({ mutateAsync: mockValidateRoleName, isPending: false }); + }); + + it('opens the wizard on the name and resource step', async () => { + await openWizard(); + + expect(screen.getByRole('dialog', { name: 'Create a new role' })).toBeInTheDocument(); + expect(screen.getByText('Name & Resource')).toBeInTheDocument(); + expect(screen.getByText('Permissions')).toBeInTheDocument(); + expect(screen.getByRole('textbox', { name: 'Role name' })).toHaveValue(''); + expect(screen.getByText('Shown when administrators assign access.')).toBeInTheDocument(); + }); + + it('limits the role name to the 255 characters the backend accepts', async () => { + const user = await openWizard(); + const name = screen.getByRole('textbox', { name: 'Role name' }); + expect(name).toHaveAttribute('maxLength', '255'); + await user.click(name); + await user.paste('a'.repeat(300)); + expect(name).toHaveValue('a'.repeat(255)); + }); + it('starts from scratch on the first resource type', async () => { + await openWizard(); + + const startFrom = screen.getByRole('radiogroup', { name: 'Start from' }); + expect(within(startFrom).getByRole('radio', { name: /start from scratch/i })).toHaveAttribute('aria-checked', 'true'); + expect(within(startFrom).getByRole('radio', { name: /clone from role/i })).toHaveAttribute('aria-checked', 'false'); + const resourceType = screen.getByRole('combobox', { name: 'Resource type' }); + expect(resourceType).toHaveValue(SCOPE_TYPES.COURSE); + expect(within(resourceType).getAllByRole('option').map((option) => option.textContent)).toEqual(['Courses', 'Libraries']); + }); + + it('requires a role name before moving on', async () => { + const user = await openWizard(); + expectNextBlocked(); + + await user.type(screen.getByRole('textbox', { name: 'Role name' }), ' '); + expectNextBlocked(); + + await user.type(screen.getByRole('textbox', { name: 'Role name' }), 'Course designer'); + expectNextAllowed(); + }); + + it('moves on to the permissions step and back', async () => { + const user = await openWizard(); + await user.type(screen.getByRole('textbox', { name: 'Role name' }), 'Course designer'); + await user.selectOptions(screen.getByRole('combobox', { name: 'Resource type' }), 'Libraries'); + + await user.click(getNextButton()); + expect(screen.queryByRole('textbox', { name: 'Role name' })).not.toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Back' })); + expect(screen.getByRole('textbox', { name: 'Role name' })).toHaveValue('Course designer'); + expect(screen.getByRole('combobox', { name: 'Resource type' })).toHaveValue(SCOPE_TYPES.LIBRARY); + }); + + it('swaps the resource type for a grouped role picker when cloning', async () => { + const user = await openWizard(); + + await user.click(screen.getByRole('radio', { name: /clone from role/i })); + + expect(screen.queryByRole('combobox', { name: 'Resource type' })).not.toBeInTheDocument(); + const picker = screen.getByRole('button', { name: 'Role Select a role' }); + await user.click(picker); + const standard = screen.getByRole('group', { name: 'Standard Roles' }); + expect(within(within(standard).getByRole('group', { name: 'Courses' })).getAllByRole('menuitemradio').map((item) => item.textContent)) + .toEqual(['Course Admin', 'Course Staff']); + expect(within(within(standard).getByRole('group', { name: 'Libraries' })).getAllByRole('menuitemradio').map((item) => item.textContent)) + .toEqual(['Library Admin', 'Library Author', 'Library Contributor', 'Library User']); + expect(within(screen.getByRole('group', { name: 'Custom Roles' })).getAllByRole('menuitemradio').map((item) => item.textContent)) + .toEqual(['Technique auditor']); + }); + + it('requires a source role when cloning, standard or custom', async () => { + const user = await openWizard(); + await user.type(screen.getByRole('textbox', { name: 'Role name' }), 'Course designer'); + await user.click(screen.getByRole('radio', { name: /clone from role/i })); + expectNextBlocked(); + + await user.click(screen.getByRole('button', { name: 'Role Select a role' })); + await user.click(screen.getByText('Library Author')); + expect(screen.getByRole('button', { name: 'Role Library Author' })).toBeInTheDocument(); + expectNextAllowed(); + + await user.click(screen.getByRole('button', { name: 'Role Library Author' })); + await user.click(screen.getByText('Technique auditor')); + expect(screen.getByRole('button', { name: 'Role Technique auditor (Custom Role)' })).toBeInTheDocument(); + expectNextAllowed(); + }); + + it('hides the custom roles group when there are none', async () => { + mockAuthzCatalog(); + const user = await openWizard(); + await user.click(screen.getByRole('radio', { name: /clone from role/i })); + + await user.click(screen.getByRole('button', { name: 'Role Select a role' })); + + expect(screen.getByRole('group', { name: 'Standard Roles' })).toBeInTheDocument(); + expect(screen.queryByRole('group', { name: 'Custom Roles' })).not.toBeInTheDocument(); + }); + + it('closes on Cancel and starts over when opened again', async () => { + const user = await openWizard(); + await user.type(screen.getByRole('textbox', { name: 'Role name' }), 'Course designer'); + + await user.click(screen.getByRole('button', { name: 'Cancel' })); + expect(screen.queryByRole('dialog', { name: 'Create a new role' })).not.toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Create Custom Role' })); + expect(screen.getByRole('textbox', { name: 'Role name' })).toHaveValue(''); + }); + + it('shows a scope type it has no label for by its raw value, without an icon', async () => { + const unknownScopeType = 'org-v1'; + mockAuthzCatalog({ + catalog: { + ...authzCatalog, + scopeTypes: [...authzCatalog.scopeTypes, unknownScopeType], + roles: [...authzCatalog.roles, buildCatalogRole('org_admin', { displayName: 'Org Admin', scopeTypes: [unknownScopeType] })], + }, + }); + const user = await openWizard(); + + expect(within(screen.getByRole('combobox', { name: 'Resource type' })).getAllByRole('option').map((option) => option.textContent)) + .toEqual(['Courses', 'Libraries', unknownScopeType]); + + await user.click(screen.getByRole('radio', { name: /clone from role/i })); + await user.click(screen.getByRole('button', { name: 'Role Select a role' })); + expect(within(screen.getByRole('group', { name: unknownScopeType })).getAllByRole('menuitemradio').map((item) => item.textContent)) + .toEqual(['Org Admin']); + }); + + it('announces the roles loading, and offers neither field until they have', async () => { + mockAuthzCatalog({ isLoading: true }); + const user = await openWizard(); + + expect(screen.getByRole('status')).toHaveTextContent('Loading roles'); + expect(screen.queryByRole('combobox', { name: 'Resource type' })).not.toBeInTheDocument(); + + await user.click(screen.getByRole('radio', { name: /clone from role/i })); + expect(screen.getByRole('status')).toHaveTextContent('Loading roles'); + expect(screen.queryByRole('button', { name: /^Role / })).not.toBeInTheDocument(); + }); + + it('reports the roles failing to load', async () => { + mockAuthzCatalog({ isError: true }); + await openWizard(); + + expect(screen.getByText('The roles could not be loaded. Please try again later.')).toBeInTheDocument(); + expect(screen.queryByRole('combobox', { name: 'Resource type' })).not.toBeInTheDocument(); + expectNextBlocked(); + }); + + describe('role name check', () => { + const typeNameAndNext = async (user: ReturnType) => { + await user.type(screen.getByRole('textbox', { name: 'Role name' }), 'Course designer'); + await user.click(getNextButton()); + }; + + it('checks the name and moves on when it is available', async () => { + const user = await openWizard(); + await typeNameAndNext(user); + expect(mockValidateRoleName).toHaveBeenCalledWith('Course designer'); + expect(await screen.findByRole('group', { name: 'Step 2 of 2: Permissions' })).toBeInTheDocument(); + }); + + it('shows Next as pending while the name is being checked', async () => { + (useValidateRoleName as jest.Mock).mockReturnValue({ mutateAsync: mockValidateRoleName, isPending: true }); + await openWizard(); + expect(screen.getByRole('button', { name: /Validating/ })).toHaveAttribute('aria-disabled', 'true'); + }); + + it.each([ + ['taken', 'A role with this name already exists. Enter a different role name.'], + ['invalid', 'This role name is not valid. Enter a different role name.'], + ])('stays on the first step with an alert when the name is %s', async (reason, text) => { + mockValidateRoleName.mockResolvedValue({ available: false, reason }); + const user = await openWizard(); + await typeNameAndNext(user); + expect(await screen.findByRole('alert')).toHaveTextContent(text); + expect(screen.getByRole('textbox', { name: 'Role name' })).toHaveClass('is-invalid'); + expect(screen.getByRole('textbox', { name: 'Role name' })).toHaveFocus(); + expectNextBlocked(); + expect(getNextButton()).toHaveAccessibleDescription('Change the role name to continue.'); + await user.click(getNextButton()); + expect(mockValidateRoleName).toHaveBeenCalledTimes(1); + expect(screen.queryByRole('group', { name: 'Step 2 of 2: Permissions' })).not.toBeInTheDocument(); + }); + + it('stays on the first step with an alert when the check fails', async () => { + mockValidateRoleName.mockRejectedValue(new Error('network')); + const user = await openWizard(); + await typeNameAndNext(user); + expect(await screen.findByRole('alert')).toHaveTextContent('The role name could not be checked. Please try again.'); + expect(screen.getByRole('textbox', { name: 'Role name' })).toHaveFocus(); + // A failed check says nothing about the name, so Next stays available to retry. + expectNextAllowed(); + }); + + it('clears the alert when the name changes', async () => { + mockValidateRoleName.mockResolvedValue({ available: false, reason: 'taken' }); + const user = await openWizard(); + await typeNameAndNext(user); + expect(await screen.findByRole('alert')).toBeInTheDocument(); + await user.type(screen.getByRole('textbox', { name: 'Role name' }), '2'); + expect(screen.queryByRole('alert')).not.toBeInTheDocument(); + expectNextAllowed(); + }); + + it('does not check an empty name', async () => { + const user = await openWizard(); + await user.click(getNextButton()); + expect(mockValidateRoleName).not.toHaveBeenCalled(); + }); + }); + + describe('accessibility', () => { + it('names the content of each step by its position, and moves focus to it on Next and Back', async () => { + const user = await openWizard(); + expect(screen.getByRole('group', { name: 'Step 1 of 2: Name & Resource' })).toBeInTheDocument(); + + await user.type(screen.getByRole('textbox', { name: 'Role name' }), 'Course designer'); + await user.click(getNextButton()); + expect(screen.getByRole('group', { name: 'Step 2 of 2: Permissions' })).toHaveFocus(); + + await user.click(screen.getByRole('button', { name: 'Back' })); + expect(screen.getByRole('group', { name: 'Step 1 of 2: Name & Resource' })).toHaveFocus(); + }); + + it('describes the fields by their helper text', async () => { + await openWizard(); + + expect(screen.getByRole('textbox', { name: 'Role name' })) + .toHaveAccessibleDescription('Shown when administrators assign access.'); + expect(screen.getByRole('combobox', { name: 'Resource type' })) + .toHaveAccessibleDescription(/Custom roles currently apply to a single resource type\./); + }); + + it('tells a screen reader why Next does nothing, and where to fix it', async () => { + const user = await openWizard(); + expect(getNextButton()).toHaveAccessibleDescription('Enter a role name to continue.'); + + await user.click(getNextButton()); + + const name = screen.getByRole('textbox', { name: 'Role name' }); + expect(name).toHaveFocus(); + expect(name).toBeInvalid(); + expect(name).toHaveAccessibleDescription(/Enter a role name\./); + expect(screen.getByRole('group', { name: 'Step 1 of 2: Name & Resource' })).toBeInTheDocument(); + }); + + it('shows the name error once the field is left empty', async () => { + const user = await openWizard(); + const name = screen.getByRole('textbox', { name: 'Role name' }); + expect(screen.queryByText('Enter a role name.')).not.toBeInTheDocument(); + + await user.click(name); + await user.tab(); + + expect(screen.getByText('Enter a role name.')).toBeInTheDocument(); + expect(name).toBeInvalid(); + }); + + it('asks for the role to clone, and focuses its picker', async () => { + const user = await openWizard(); + await user.type(screen.getByRole('textbox', { name: 'Role name' }), 'Course designer'); + await user.click(screen.getByRole('radio', { name: /clone from role/i })); + expect(getNextButton()).toHaveAccessibleDescription('Select a role to clone to continue.'); + + await user.click(getNextButton()); + + const picker = screen.getByRole('button', { name: 'Role Select a role' }); + expect(picker).toHaveFocus(); + expect(picker).toHaveAccessibleDescription('Select a role to clone.'); + }); + + it.each([ + ['loading', { isLoading: true }, 'Roles are still loading. Wait to continue.'], + ['failed to load', { isError: true }, 'Roles could not be loaded, so you cannot continue.'], + ])('tells a screen reader why Next does nothing while the roles %s', async (_state, catalogState, hint) => { + const user = userEvent.setup(); + mockAuthzCatalog(catalogState); + renderWithAllProviders(); + await user.click(screen.getByRole('button', { name: 'Create Custom Role' })); + await user.type(screen.getByRole('textbox', { name: 'Role name' }), 'Course designer'); + expectNextBlocked(); + expect(getNextButton()).toHaveAccessibleDescription(hint); + }); + it('moves between the start from cards with the arrow keys, as a radio group', async () => { + const user = await openWizard(); + const scratch = screen.getByRole('radio', { name: /start from scratch/i }); + const clone = screen.getByRole('radio', { name: /clone from role/i }); + // One tab stop: the checked card. + expect(scratch).toHaveAttribute('tabindex', '0'); + expect(clone).toHaveAttribute('tabindex', '-1'); + + scratch.focus(); + await user.keyboard('{ArrowRight}'); + expect(clone).toHaveFocus(); + expect(clone).toHaveAttribute('aria-checked', 'true'); + expect(clone).toHaveAttribute('tabindex', '0'); + expect(scratch).toHaveAttribute('tabindex', '-1'); + + await user.keyboard('{ArrowLeft}'); + expect(scratch).toHaveFocus(); + expect(scratch).toHaveAttribute('aria-checked', 'true'); + }); + + it('leaves the start from choice alone on keys that are not arrows', async () => { + const user = await openWizard(); + const scratch = screen.getByRole('radio', { name: /start from scratch/i }); + + scratch.focus(); + await user.keyboard('{Home}{End}'); + + expect(scratch).toHaveFocus(); + expect(scratch).toHaveAttribute('aria-checked', 'true'); + expect(screen.getByRole('radio', { name: /clone from role/i })).toHaveAttribute('aria-checked', 'false'); + }); + + it('lists the roles to clone as a menu, announces the selected one, and opens on the first', async () => { + const user = await openWizard(); + await user.click(screen.getByRole('radio', { name: /clone from role/i })); + const picker = screen.getByRole('button', { name: 'Role Select a role' }); + + picker.focus(); + await user.keyboard('{Enter}'); + const items = screen.getAllByRole('menuitemradio'); + expect(screen.getByRole('menu')).toBeInTheDocument(); + expect(items[0]).toHaveFocus(); + expect(items.every((item) => item.getAttribute('aria-checked') === 'false')).toBe(true); + + await user.keyboard('{ArrowDown}{Enter}'); + expect(screen.getByRole('button', { name: 'Role Course Staff' })).toHaveFocus(); + + await user.click(screen.getByRole('button', { name: 'Role Course Staff' })); + expect(screen.getByRole('menuitemradio', { name: 'Course Staff' })).toHaveAttribute('aria-checked', 'true'); + expect(screen.getByRole('menuitemradio', { name: 'Course Admin' })).toHaveAttribute('aria-checked', 'false'); + }); + + // Paragon's modal returns focus itself; this keeps a change of modal from losing it. + it('hands focus back to the button that opened the wizard on Cancel and on Esc', async () => { + const user = await openWizard(); + const openButton = screen.getByRole('button', { name: 'Create Custom Role', hidden: true }); + + await user.click(screen.getByRole('button', { name: 'Cancel' })); + expect(openButton).toHaveFocus(); + + await user.click(openButton); + expect(screen.getByRole('dialog', { name: 'Create a new role' })).toBeInTheDocument(); + await user.keyboard('{Escape}'); + expect(screen.queryByRole('dialog', { name: 'Create a new role' })).not.toBeInTheDocument(); + expect(openButton).toHaveFocus(); + }); + }); +}); diff --git a/src/authz-module/roles-permissions/components/CreateCustomRole.tsx b/src/authz-module/roles-permissions/components/CreateCustomRole.tsx new file mode 100644 index 00000000..9493cdac --- /dev/null +++ b/src/authz-module/roles-permissions/components/CreateCustomRole.tsx @@ -0,0 +1,243 @@ +import { useEffect, useId, useRef, useState } from 'react'; +import { useIntl } from '@openedx/frontend-base'; +import { + Button, FullscreenModal, Icon, StatefulButton, Stepper, +} from '@openedx/paragon'; +import { Add, SpinnerSimple } from '@openedx/paragon/icons'; +import { useAuthzCatalog } from '@src/authz-module/catalog'; +import type { ScopeCatalog } from '@src/authz-module/catalog'; +import { EMPTY_CUSTOM_ROLE_DRAFT, START_FROM, getCustomRoleSeed } from '../customRoleDraft'; +import type { CustomRoleDraft, NameCheckError } from '../customRoleDraft'; +import { useValidateRoleName } from '../../data/hooks'; +import messages from '../messages'; +import NameAndResourceStep from './NameAndResourceStep'; + +const STEPS = { + NAME_AND_RESOURCE: 'name-and-resource', + PERMISSIONS: 'permissions', +} as const; + +type StepKey = typeof STEPS[keyof typeof STEPS]; + +// Why Next does nothing, so a screen reader can be told; `null` when there is nothing to fix. +const NEXT_BLOCKERS = { + NAME: 'name', + NAME_REJECTED: 'nameRejected', + CATALOG_LOADING: 'catalogLoading', + CATALOG_ERROR: 'catalogError', + SOURCE_ROLE: 'sourceRole', +} as const; + +interface CreateCustomRoleWizardProps { + /** Called on Cancel, header close and Esc. */ + onClose: () => void; +} + +/** + * Full-screen modal, like the assign role wizard, so creating a role never leaves the page. + * `Stepper` wraps it because its header, steps and action rows go into three modal slots that + * share one context. + * + * TODO: the permissions step is a placeholder, built in + * https://github.com/openedx/openedx-authz/issues/572 from `getCustomRoleSeed(draft, getRole)`. + */ +export const CreateCustomRoleWizard = ({ onClose }: CreateCustomRoleWizardProps) => { + const { formatMessage } = useIntl(); + const { + scopeTypes, getScopeCatalog, getRole, isLoading, isError, + } = useAuthzCatalog(); + const [activeStep, setActiveStep] = useState(STEPS.NAME_AND_RESOURCE); + const [draft, setDraft] = useState(EMPTY_CUSTOM_ROLE_DRAFT); + // Set once Next is pressed with a missing answer, so the step shows its errors from then on. + const [hasTriedNext, setHasTriedNext] = useState(false); + // Counts the presses of a blocked Next, so the step can move focus to the first missing answer. + const [focusRequest, setFocusRequest] = useState(0); + const [nameCheckError, setNameCheckError] = useState(null); + const { mutateAsync: validateRoleName, isPending: isCheckingName } = useValidateRoleName(); + const nextHintId = `${useId()}-next-hint`; + /** Focus target of the active step, so focus doesn't stay on the footer of the step that left. */ + const stepContentRef = useRef(null); + const focusedStep = useRef(activeStep); + + useEffect(() => { + if (focusedStep.current === activeStep) return; + focusedStep.current = activeStep; + stepContentRef.current?.focus(); + }, [activeStep]); + + const scopeCatalogs = scopeTypes + .map(getScopeCatalog) + .filter((scopeCatalog): scopeCatalog is ScopeCatalog => scopeCatalog !== undefined); + // The resource type field shows the first resource type until another is picked, so it counts as picked. + const effectiveDraft = draft.scopeType ? draft : { ...draft, scopeType: scopeTypes[0] ?? '' }; + const canProceed = getCustomRoleSeed(effectiveDraft, getRole) !== null; + // A rejected name stays rejected until it changes; a failed check can be retried as is. + const isNameRejected = nameCheckError === 'taken' || nameCheckError === 'invalid'; + let nextBlocker: typeof NEXT_BLOCKERS[keyof typeof NEXT_BLOCKERS] | null = null; + if (!draft.name.trim()) { + nextBlocker = NEXT_BLOCKERS.NAME; + } else if (isNameRejected) { + nextBlocker = NEXT_BLOCKERS.NAME_REJECTED; + } else if (isLoading) { + nextBlocker = NEXT_BLOCKERS.CATALOG_LOADING; + } else if (isError || !scopeTypes.length) { + // A catalog that loaded with no resource types leaves nothing to pick, so it reads as a failure too. + nextBlocker = NEXT_BLOCKERS.CATALOG_ERROR; + } else if (!canProceed && draft.startFrom === START_FROM.CLONE) { + nextBlocker = NEXT_BLOCKERS.SOURCE_ROLE; + } + + const isNextDisabled = !canProceed || isCheckingName || isNameRejected; + + const stepTitles = { + [STEPS.NAME_AND_RESOURCE]: formatMessage(messages['authz.roles.create.wizard.step.nameAndResource']), + [STEPS.PERMISSIONS]: formatMessage(messages['authz.roles.create.wizard.step.permissions']), + }; + // The Stepper header marks the active step with a class only, so each step names itself instead. + const getStepLabel = (step: StepKey) => formatMessage(messages['authz.roles.create.wizard.step.status'], { + current: Object.values(STEPS).indexOf(step) + 1, + total: Object.values(STEPS).length, + title: stepTitles[step], + }); + + const handleDraftChange = (changes: Partial) => { + // A new name makes the previous check result stale. + if (changes.name !== undefined) setNameCheckError(null); + setDraft((prev) => ({ ...prev, ...changes })); + }; + + /** + * The name is checked on Next, not while typing, because the check is not a reservation: + * the final create can still conflict, and a check per keystroke would only add requests. + */ + const handleNext = async () => { + if (isCheckingName || isNameRejected) return; + if (!canProceed) { + setHasTriedNext(true); + setFocusRequest((count) => count + 1); + return; + } + try { + const result = await validateRoleName(effectiveDraft.name?.trim()); + if (!result.available) { + setNameCheckError(result.reason === 'invalid' ? 'invalid' : 'taken'); + setFocusRequest((count) => count + 1); + return; + } + } catch { + setNameCheckError('failed'); + setFocusRequest((count) => count + 1); + return; + } + setNameCheckError(null); + setDraft(effectiveDraft); + setActiveStep(STEPS.PERMISSIONS); + }; + + return ( + + } + modalBodyClassName="bg-light-200 pt-0" + footerNode={( + <> + + + + {/* aria-disabled, not disabled, so Next stays focusable and can say what is missing. */} + }} + state={isCheckingName ? 'pending' : 'default'} + onClick={handleNext} + className={isNextDisabled ? 'disabled' : undefined} + aria-disabled={isNextDisabled} + aria-describedby={nextBlocker ? nextHintId : undefined} + /> + {nextBlocker && ( + + {formatMessage(messages[`authz.roles.create.wizard.button.next.hint.${nextBlocker}`])} + + )} + + + + + + + )} + > + +
+ +
+
+ +
+ + + + ); +}; + +/** + * Header button of the roles and permissions tab that opens the create custom role wizard. + * + * The wizard is mounted only while open, as `AddRoleButton` does, so each opening starts from + * an empty draft and Cancel needs no reset. + */ +const CreateCustomRole = () => { + const { formatMessage } = useIntl(); + const [isWizardOpen, setIsWizardOpen] = useState(false); + return ( + <> + + {isWizardOpen && setIsWizardOpen(false)} />} + + ); +}; + +export default CreateCustomRole; diff --git a/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx b/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx new file mode 100644 index 00000000..1689a569 --- /dev/null +++ b/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx @@ -0,0 +1,290 @@ +import { useEffect, useId, useRef, useState } from 'react'; +import { useIntl } from '@openedx/frontend-base'; +import { + Alert, Dropdown, Form, Icon, SelectableBox, Spinner, Stack, +} from '@openedx/paragon'; +import { isCustomRole } from '@src/authz-module/catalog'; +import type { Role, ScopeCatalog } from '@src/authz-module/catalog'; +import { RESOURCE_TYPE_DISPLAY } from '../constants'; +import { MAX_ROLE_NAME_LENGTH, START_FROM } from '../customRoleDraft'; +import type { CustomRoleDraft, StartFrom } from '../customRoleDraft'; +import messages from '../messages'; +import type { NameCheckError } from '../customRoleDraft'; + +interface NameAndResourceStepProps { + draft: CustomRoleDraft; + onChange: (changes: Partial) => void; + // The catalog of each resource type the user can view, in catalog order. + scopeCatalogs: ScopeCatalog[]; + isLoading?: boolean; + isError?: boolean; + // Shows the missing answers' errors, after Next was pressed without them. + showErrors?: boolean; + // Grows each time a blocked Next is pressed, to move focus to the first missing answer. + focusRequest?: number; + // Why the name check kept the wizard on this step, shown as an alert; `null` when there is nothing to fix. + nameCheckError: NameCheckError | null; +} + +const START_FROM_OPTIONS = [START_FROM.SCRATCH, START_FROM.CLONE]; +const ARROW_KEY_OFFSETS: Record = { + ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1, +}; + +/** + * First step of the create custom role wizard: the role name, and either the resource type of a + * role built from scratch or the role to clone. A clone copies the source role's resource type, + * so the resource type field is swapped for the role picker instead of shown beside it. + */ +const NameAndResourceStep = ({ + draft, onChange, scopeCatalogs, isLoading = false, isError = false, showErrors = false, focusRequest = 0, nameCheckError, +}: NameAndResourceStepProps) => { + const { formatMessage } = useIntl(); + const idPrefix = useId(); + const startFromLabelId = `${idPrefix}-start-from`; + const sourceRoleLabelId = `${idPrefix}-source-role`; + const sourceRoleToggleId = `${idPrefix}-source-role-toggle`; + const sourceRoleErrorId = `${idPrefix}-source-role-error`; + const nameInputId = `${idPrefix}-name`; + const startFromCards = useRef>({}); + const [isNameTouched, setIsNameTouched] = useState(false); + + const formatScopeType = (scopeType: string) => { + const display = RESOURCE_TYPE_DISPLAY[scopeType]; + return display ? formatMessage(display.label) : scopeType; + }; + + // Standard roles are listed under their resource type; custom roles go in a group of their own. + const standardGroups = scopeCatalogs + .map(({ scopeType, roles }) => ({ scopeType, roles: roles.filter((role) => !isCustomRole(role)) })) + .filter(({ roles }) => roles.length > 0); + const customRoles = scopeCatalogs.flatMap(({ roles }) => roles.filter(isCustomRole)); + const selectedSourceRole = [...standardGroups.flatMap(({ roles }) => roles), ...customRoles] + .find(({ role }) => role === draft.sourceRole); + + const isNameMissing = !draft.name.trim(); + const showNameError = isNameMissing && (isNameTouched || showErrors); + const showSourceRoleError = showErrors && draft.startFrom === START_FROM.CLONE && !selectedSourceRole; + + // A blocked Next, or a name the check rejected, moves focus to the first answer to fix, where the error is read out. + useEffect(() => { + if (focusRequest === 0) return; + document.getElementById(isNameMissing || nameCheckError ? nameInputId : sourceRoleToggleId)?.focus(); + // Only a new press should move focus, not later edits of the answers. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [focusRequest]); + + // Radio cards are a single tab stop; the arrow keys move between them, as in a native radio group. + const handleStartFromKeyDown = (e: React.KeyboardEvent) => { + const offset = ARROW_KEY_OFFSETS[e.key]; + if (!offset) return; + e.preventDefault(); + const index = START_FROM_OPTIONS.indexOf(draft.startFrom); + const next = START_FROM_OPTIONS[(index + offset + START_FROM_OPTIONS.length) % START_FROM_OPTIONS.length]; + onChange({ startFrom: next }); + startFromCards.current[next]?.focus(); + }; + + const formatRoleName = (role: Role) => (isCustomRole(role) + ? formatMessage(messages['authz.roles.create.wizard.sourceRole.custom'], { role: role.displayName }) + : role.displayName); + + return ( + + + + {formatMessage(messages['authz.roles.create.wizard.name.label'])} + + ) => onChange({ name: e.target.value })} + onBlur={() => setIsNameTouched(true)} + placeholder={formatMessage(messages['authz.roles.create.wizard.name.placeholder'])} + isInvalid={showNameError || nameCheckError !== null} + maxLength={MAX_ROLE_NAME_LENGTH} + required + /> + {showNameError && ( + + {formatMessage(messages['authz.roles.create.wizard.name.error'])} + + )} + {!showNameError && nameCheckError && ( + + {formatMessage(messages[`authz.roles.create.wizard.name.alert.${nameCheckError}`])} + + )} + + {formatMessage(messages['authz.roles.create.wizard.name.helper'])} + + + +
+

+ {formatMessage(messages['authz.roles.create.wizard.startFrom.label'])} +

+ ) => onChange({ startFrom: e.target.value as StartFrom })} + ariaLabelledby={startFromLabelId} + className="create-custom-role-wizard__start-from" + onKeyDown={handleStartFromKeyDown} + > + {START_FROM_OPTIONS.map((option) => ( + // SelectableBox renders a button over a hidden radio, so the radio state is restated on it. + { + startFromCards.current[option] = card; + }} + > +

+ {formatMessage(messages[`authz.roles.create.wizard.startFrom.${option}.title`])} +

+

+ {formatMessage(messages[`authz.roles.create.wizard.startFrom.${option}.description`])} +

+
+ ))} +
+
+ + {isLoading && ( +
+ +
+ )} + {isError && ( + + {formatMessage(messages['authz.roles.create.wizard.error'])} + + )} + + {!isLoading && !isError && draft.startFrom === START_FROM.SCRATCH && ( + + + {formatMessage(messages['authz.roles.create.wizard.resourceType.label'])} + + ) => onChange({ scopeType: e.target.value })} + required + > + {scopeCatalogs.map(({ scopeType }) => ( + + ))} + + + {formatMessage(messages['authz.roles.create.wizard.resourceType.helper'])} + + + )} + + {!isLoading && !isError && draft.startFrom === START_FROM.CLONE && ( +
+

+ {formatMessage(messages['authz.roles.create.wizard.sourceRole.label'])} +

+ {/* A native select can't nest groups or show icons, which the resource type headers need. */} + roleId && onChange({ sourceRole: roleId })} + > + + {selectedSourceRole + ? formatRoleName(selectedSourceRole) + : formatMessage(messages['authz.roles.create.wizard.sourceRole.placeholder'])} + + {/* role="menu" also makes the menu move focus to its first item when opened by keyboard. */} + + {standardGroups.length > 0 && ( +
+ {/* The group's aria-label already names it, and a heading may not sit in a menu. */} + + {standardGroups.map(({ scopeType, roles }) => { + const display = RESOURCE_TYPE_DISPLAY[scopeType]; + return ( +
+ + {roles.map((role) => ( + + {role.displayName} + + ))} +
+ ); + })} +
+ )} + {customRoles.length > 0 && ( +
+ {standardGroups.length > 0 && } + + {customRoles.map((role) => ( + + {role.displayName} + + ))} +
+ )} +
+
+ {showSourceRoleError && ( +

+ {formatMessage(messages['authz.roles.create.wizard.sourceRole.error'])} +

+ )} +
+ )} +
+ ); +}; + +export default NameAndResourceStep; diff --git a/src/authz-module/roles-permissions/customRoleDraft.test.ts b/src/authz-module/roles-permissions/customRoleDraft.test.ts new file mode 100644 index 00000000..6f9cd860 --- /dev/null +++ b/src/authz-module/roles-permissions/customRoleDraft.test.ts @@ -0,0 +1,49 @@ +import { authzCatalog, buildCatalogRole } from '@src/authz-module/catalog/testUtils'; +import { SCOPE_TYPES } from '@src/authz-module/constants'; +import { EMPTY_CUSTOM_ROLE_DRAFT, START_FROM, getCustomRoleSeed } from './customRoleDraft'; + +const roles = [ + ...authzCatalog.roles, + buildCatalogRole('technique_auditor', { + definitionKind: 'user_defined', permissions: ['courses.view_course'], scopeTypes: [SCOPE_TYPES.COURSE], + }), +]; +const getRole = (roleId: string) => roles.find(({ role }) => role === roleId); + +describe('getCustomRoleSeed', () => { + it('requires a name that is not only whitespace', () => { + expect(getCustomRoleSeed({ ...EMPTY_CUSTOM_ROLE_DRAFT, name: ' ', scopeType: SCOPE_TYPES.COURSE }, getRole)).toBeNull(); + }); + + it('starts a role from scratch with no permissions in the picked resource type', () => { + expect(getCustomRoleSeed({ ...EMPTY_CUSTOM_ROLE_DRAFT, name: 'Designer', scopeType: SCOPE_TYPES.LIBRARY }, getRole)) + .toEqual({ scopeType: SCOPE_TYPES.LIBRARY, permissions: [] }); + }); + + it('requires a resource type from scratch', () => { + expect(getCustomRoleSeed({ ...EMPTY_CUSTOM_ROLE_DRAFT, name: 'Designer' }, getRole)).toBeNull(); + }); + + it('requires a source role when cloning', () => { + expect(getCustomRoleSeed({ + ...EMPTY_CUSTOM_ROLE_DRAFT, name: 'Designer', startFrom: START_FROM.CLONE, scopeType: SCOPE_TYPES.COURSE, + }, getRole)).toBeNull(); + }); + + it.each([ + ['a standard role', 'library_author', SCOPE_TYPES.LIBRARY, ['content_libraries.edit_library_content', 'content_libraries.view_library']], + ['a custom role', 'technique_auditor', SCOPE_TYPES.COURSE, ['courses.view_course']], + ])('copies the resource type and permissions of %s when cloning', (_, sourceRole, scopeType, permissions) => { + // The scratch resource type is ignored: a clone keeps the source role's. + expect(getCustomRoleSeed({ + name: 'Designer', startFrom: START_FROM.CLONE, scopeType: SCOPE_TYPES.COURSE === scopeType ? SCOPE_TYPES.LIBRARY : SCOPE_TYPES.COURSE, sourceRole, + }, getRole)).toEqual({ scopeType, permissions }); + }); + + it('does not share the source role permissions array', () => { + const seed = getCustomRoleSeed({ + name: 'Designer', startFrom: START_FROM.CLONE, scopeType: '', sourceRole: 'course_admin', + }, getRole); + expect(seed?.permissions).not.toBe(getRole('course_admin')?.permissions); + }); +}); diff --git a/src/authz-module/roles-permissions/customRoleDraft.ts b/src/authz-module/roles-permissions/customRoleDraft.ts new file mode 100644 index 00000000..3d7f7696 --- /dev/null +++ b/src/authz-module/roles-permissions/customRoleDraft.ts @@ -0,0 +1,62 @@ +import type { Role } from '@src/authz-module/catalog'; + +/** Backend `display_name` is `max_length=255`; a longer name would be rejected on save. */ +export const MAX_ROLE_NAME_LENGTH = 255; + +export const START_FROM = { + SCRATCH: 'scratch', + CLONE: 'clone', +} as const; + +export type StartFrom = typeof START_FROM[keyof typeof START_FROM]; + +/** What the first step of the create custom role wizard collects. */ +export interface CustomRoleDraft { + name: string; + startFrom: StartFrom; + // The resource type picked in scratch mode. Clone mode takes it from the source role instead. + scopeType: string; + // The id of the role to clone, in clone mode. + sourceRole: string | null; +} + +/** What the permissions step starts from: the resource type and the permissions already granted. */ +export interface CustomRoleSeed { + scopeType: string; + permissions: string[]; +} + +export const EMPTY_CUSTOM_ROLE_DRAFT: CustomRoleDraft = { + name: '', + startFrom: START_FROM.SCRATCH, + scopeType: '', + sourceRole: null, +}; + +/** + * Turns the first step's answers into what the permissions step starts from, or `null` while + * a required answer is missing, which is also what keeps Next disabled. + * + * A clone takes its resource type and permissions from the source role, so the resource type + * can't differ from the role it copies. Roles hold a single resource type today, so the + * source role's first one is the resource type. + * + * @param draft - The first step's answers. + * @param getRole - Looks a role up by id in the catalog. + */ +export const getCustomRoleSeed = ( + draft: CustomRoleDraft, + getRole: (roleId: string) => Role | undefined, +): CustomRoleSeed | null => { + if (!draft.name.trim()) return null; + if (draft.startFrom === START_FROM.SCRATCH) { + return draft.scopeType ? { scopeType: draft.scopeType, permissions: [] } : null; + } + const sourceRole = draft.sourceRole ? getRole(draft.sourceRole) : undefined; + const scopeType = sourceRole?.scopeTypes[0]; + if (!sourceRole || !scopeType) return null; + return { scopeType, permissions: [...sourceRole.permissions] }; +}; + +/** Why the role name check kept the wizard on its first step. */ +export type NameCheckError = 'taken' | 'invalid' | 'failed'; diff --git a/src/authz-module/roles-permissions/index.ts b/src/authz-module/roles-permissions/index.ts index fe56a026..91bcd9fa 100644 --- a/src/authz-module/roles-permissions/index.ts +++ b/src/authz-module/roles-permissions/index.ts @@ -1,3 +1,4 @@ export { default as RolesPermissionsTable } from './RolesPermissionsTable'; +export { default as CreateCustomRole } from './components/CreateCustomRole'; export { buildPermissionMatrix } from './utils'; export type { MatrixCategory } from './utils'; diff --git a/src/authz-module/roles-permissions/messages.ts b/src/authz-module/roles-permissions/messages.ts index b3ee2230..97b28334 100644 --- a/src/authz-module/roles-permissions/messages.ts +++ b/src/authz-module/roles-permissions/messages.ts @@ -111,6 +111,186 @@ const messages = defineMessages({ defaultMessage: 'Remove {filter} filter', description: 'Accessible label of the button that removes an applied filter chip in the roles table', }, + 'authz.roles.create.button': { + id: 'authz.roles.create.button', + defaultMessage: 'Create Custom Role', + description: 'Header button that opens the create custom role wizard', + }, + 'authz.roles.create.wizard.title': { + id: 'authz.roles.create.wizard.title', + defaultMessage: 'Create a new role', + description: 'Title of the create custom role wizard', + }, + 'authz.roles.create.wizard.step.nameAndResource': { + id: 'authz.roles.create.wizard.step.nameAndResource', + defaultMessage: 'Name & Resource', + description: 'Title of the first step of the create custom role wizard', + }, + 'authz.roles.create.wizard.step.permissions': { + id: 'authz.roles.create.wizard.step.permissions', + defaultMessage: 'Permissions', + description: 'Title of the second step of the create custom role wizard', + }, + 'authz.roles.create.wizard.step.status': { + id: 'authz.roles.create.wizard.step.status', + defaultMessage: 'Step {current} of {total}: {title}', + description: 'Accessible name of the content of the active step of the create custom role wizard, which a screen reader reads when focus moves to the step', + }, + 'authz.roles.create.wizard.button.cancel': { + id: 'authz.roles.create.wizard.button.cancel', + defaultMessage: 'Cancel', + description: 'Button that closes the create custom role wizard', + }, + 'authz.roles.create.wizard.button.next': { + id: 'authz.roles.create.wizard.button.next', + defaultMessage: 'Next', + description: 'Button that moves the create custom role wizard to the permissions step', + }, + 'authz.roles.create.wizard.button.next.pending': { + id: 'authz.roles.create.wizard.button.next.pending', + defaultMessage: 'Validating...', + description: 'Next button label while the create custom role wizard checks the role name', + }, + 'authz.roles.create.wizard.button.back': { + id: 'authz.roles.create.wizard.button.back', + defaultMessage: 'Back', + description: 'Button that moves the create custom role wizard back to the name and resource step', + }, + 'authz.roles.create.wizard.button.next.hint.name': { + id: 'authz.roles.create.wizard.button.next.hint.name', + defaultMessage: 'Enter a role name to continue.', + description: 'Screen reader text that explains why the Next button of the create custom role wizard does nothing: the role name is missing', + }, + 'authz.roles.create.wizard.button.next.hint.nameRejected': { + id: 'authz.roles.create.wizard.button.next.hint.nameRejected', + defaultMessage: 'Change the role name to continue.', + description: 'Screen reader text that explains why the Next button of the create custom role wizard does nothing: the role name was rejected', + }, + 'authz.roles.create.wizard.button.next.hint.sourceRole': { + id: 'authz.roles.create.wizard.button.next.hint.sourceRole', + defaultMessage: 'Select a role to clone to continue.', + description: 'Screen reader text that explains why the Next button of the create custom role wizard does nothing: no role to clone is selected', + }, + 'authz.roles.create.wizard.button.next.hint.catalogLoading': { + id: 'authz.roles.create.wizard.button.next.hint.catalogLoading', + defaultMessage: 'Roles are still loading. Wait to continue.', + description: 'Screen reader text that explains why the Next button of the create custom role wizard does nothing: the roles are still loading', + }, + 'authz.roles.create.wizard.button.next.hint.catalogError': { + id: 'authz.roles.create.wizard.button.next.hint.catalogError', + defaultMessage: 'Roles could not be loaded, so you cannot continue.', + description: 'Screen reader text that explains why the Next button of the create custom role wizard does nothing: the roles failed to load or none are available', + }, + 'authz.roles.create.wizard.name.error': { + id: 'authz.roles.create.wizard.name.error', + defaultMessage: 'Enter a role name.', + description: 'Error shown under the custom role name field when it is empty', + }, + 'authz.roles.create.wizard.name.alert.taken': { + id: 'authz.roles.create.wizard.name.alert.taken', + defaultMessage: 'A role with this name already exists. Enter a different role name.', + description: 'Alert shown on the first step of the create custom role wizard when the role name is already used', + }, + 'authz.roles.create.wizard.name.alert.invalid': { + id: 'authz.roles.create.wizard.name.alert.invalid', + defaultMessage: 'This role name is not valid. Enter a different role name.', + description: 'Alert shown on the first step of the create custom role wizard when the role name breaks the naming rules', + }, + 'authz.roles.create.wizard.name.alert.failed': { + id: 'authz.roles.create.wizard.name.alert.failed', + defaultMessage: 'The role name could not be checked. Please try again.', + description: 'Alert shown on the first step of the create custom role wizard when the role name check request fails', + }, + 'authz.roles.create.wizard.sourceRole.error': { + id: 'authz.roles.create.wizard.sourceRole.error', + defaultMessage: 'Select a role to clone.', + description: 'Error shown under the picker of the role a custom role is cloned from when none is selected', + }, + 'authz.roles.create.wizard.name.label': { + id: 'authz.roles.create.wizard.name.label', + defaultMessage: 'Role name', + description: 'Label of the custom role name field', + }, + 'authz.roles.create.wizard.name.placeholder': { + id: 'authz.roles.create.wizard.name.placeholder', + defaultMessage: 'e.g. Course designer', + description: 'Placeholder of the custom role name field', + }, + 'authz.roles.create.wizard.name.helper': { + id: 'authz.roles.create.wizard.name.helper', + defaultMessage: 'Shown when administrators assign access.', + description: 'Helper text of the custom role name field', + }, + 'authz.roles.create.wizard.startFrom.label': { + id: 'authz.roles.create.wizard.startFrom.label', + defaultMessage: 'Start from', + description: 'Label of the choice between building a custom role from scratch or cloning a role', + }, + 'authz.roles.create.wizard.startFrom.scratch.title': { + id: 'authz.roles.create.wizard.startFrom.scratch.title', + defaultMessage: 'Start from scratch', + description: 'Title of the option that builds the custom role without permissions', + }, + 'authz.roles.create.wizard.startFrom.scratch.description': { + id: 'authz.roles.create.wizard.startFrom.scratch.description', + defaultMessage: 'Build the role from zero permissions.', + description: 'Description of the option that builds the custom role without permissions', + }, + 'authz.roles.create.wizard.startFrom.clone.title': { + id: 'authz.roles.create.wizard.startFrom.clone.title', + defaultMessage: 'Clone from role', + description: 'Title of the option that starts the custom role from an existing role', + }, + 'authz.roles.create.wizard.startFrom.clone.description': { + id: 'authz.roles.create.wizard.startFrom.clone.description', + defaultMessage: 'Start with pre-configured permissions from an existing role.', + description: 'Description of the option that starts the custom role from an existing role', + }, + 'authz.roles.create.wizard.resourceType.label': { + id: 'authz.roles.create.wizard.resourceType.label', + defaultMessage: 'Resource type', + description: 'Label of the custom role resource type field', + }, + 'authz.roles.create.wizard.resourceType.helper': { + id: 'authz.roles.create.wizard.resourceType.helper', + defaultMessage: 'Select the target resource. Custom roles currently apply to a single resource type.', + description: 'Helper text of the custom role resource type field', + }, + 'authz.roles.create.wizard.sourceRole.label': { + id: 'authz.roles.create.wizard.sourceRole.label', + defaultMessage: 'Role', + description: 'Label of the picker of the role a custom role is cloned from', + }, + 'authz.roles.create.wizard.sourceRole.placeholder': { + id: 'authz.roles.create.wizard.sourceRole.placeholder', + defaultMessage: 'Select a role', + description: 'Placeholder of the picker of the role a custom role is cloned from', + }, + 'authz.roles.create.wizard.sourceRole.group.standard': { + id: 'authz.roles.create.wizard.sourceRole.group.standard', + defaultMessage: 'Standard Roles', + description: 'Header of the built-in roles in the clone source role picker', + }, + 'authz.roles.create.wizard.sourceRole.group.custom': { + id: 'authz.roles.create.wizard.sourceRole.group.custom', + defaultMessage: 'Custom Roles', + description: 'Header of the custom roles in the clone source role picker', + }, + 'authz.roles.create.wizard.sourceRole.custom': { + id: 'authz.roles.create.wizard.sourceRole.custom', + defaultMessage: '{role} (Custom Role)', + description: 'A selected custom role in the clone source role picker', + }, + 'authz.roles.create.wizard.loading': { + id: 'authz.roles.create.wizard.loading', + defaultMessage: 'Loading roles', + description: 'Screen reader text while the create custom role wizard loads the roles', + }, + 'authz.roles.create.wizard.error': { + id: 'authz.roles.create.wizard.error', + defaultMessage: 'The roles could not be loaded. Please try again later.', + description: 'Message shown when the create custom role wizard fails to load the roles', + }, 'authz.team.remove.user.toast.success.description': { id: 'authz.team.remove.user.toast.success.description', defaultMessage: 'The {role} role has been successfully removed.{rolesCount, plural, =0 { The user no longer has access to this library and has been removed from the member list.} other {}}',