From 892bb80fa22c37e853b1f53182c4f1b7958b8a8f Mon Sep 17 00:00:00 2001 From: jacobo-dominguez-wgu Date: Mon, 23 Nov 2026 16:24:27 -0600 Subject: [PATCH 1/7] feat(authz): add the create custom role wizard for the name and resource step --- src/authz-module/authz-home/index.test.tsx | 42 +++ src/authz-module/authz-home/index.tsx | 19 +- src/authz-module/components/AddRoleButton.tsx | 6 +- src/authz-module/components/AuthZTitle.tsx | 6 +- src/authz-module/index.scss | 28 +- .../components/CreateCustomRole.test.tsx | 312 ++++++++++++++++++ .../components/CreateCustomRole.tsx | 197 +++++++++++ .../components/NameAndResourceStep.tsx | 281 ++++++++++++++++ .../roles-permissions/customRoleDraft.test.ts | 49 +++ .../roles-permissions/customRoleDraft.ts | 56 ++++ .../roles-permissions/messages.ts | 145 ++++++++ 11 files changed, 1128 insertions(+), 13 deletions(-) create mode 100644 src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx create mode 100644 src/authz-module/roles-permissions/components/CreateCustomRole.tsx create mode 100644 src/authz-module/roles-permissions/components/NameAndResourceStep.tsx create mode 100644 src/authz-module/roles-permissions/customRoleDraft.test.ts create mode 100644 src/authz-module/roles-permissions/customRoleDraft.ts diff --git a/src/authz-module/authz-home/index.test.tsx b/src/authz-module/authz-home/index.test.tsx index fdda1f2d..b25327d2 100644 --- a/src/authz-module/authz-home/index.test.tsx +++ b/src/authz-module/authz-home/index.test.tsx @@ -7,6 +7,9 @@ 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 { usePermissions } from '@openedx/frontend-base'; +import { SCOPE_TYPES } from '@src/authz-module/constants'; +import baseMessages from '@src/authz-module/messages'; import AuthzHome from './index'; import messages from './messages'; @@ -27,6 +30,12 @@ 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. + usePermissions: jest.fn(() => ({ 'course-v1': false, lib: false, isLoading: false })), +})); + jest.mock('@src/authz-module/data/hooks', () => ({ useTeamMembersAssignments: jest.fn(), useOrgs: jest.fn(), @@ -161,4 +170,37 @@ describe('AuthzHome', () => { expect(teamTab.getAllByText('Role').length).toBe(1); expect(teamTab.getByText('Actions')).toBeInTheDocument(); }); + + it('outlines the assign role button only while the roles and permissions tab is active', async () => { + (usePermissions as jest.Mock).mockReturnValue({ + [SCOPE_TYPES.COURSE]: false, [SCOPE_TYPES.LIBRARY]: true, isLoading: false, + }); + const user = userEvent.setup(); + renderAuthzHome(); + const assignRoleButton = () => screen.getByRole('button', { + name: baseMessages['authz.management.assign.role.title'].defaultMessage, + }); + + expect(assignRoleButton()).toHaveClass('btn-primary'); + + await user.click(screen.getByRole('tab', { name: messages['authz.tabs.permissionsRoles'].defaultMessage })); + expect(assignRoleButton()).toHaveClass('btn-outline-primary'); + + await user.click(screen.getByRole('tab', { name: messages['authz.tabs.team'].defaultMessage })); + expect(assignRoleButton()).toHaveClass('btn-primary'); + }); + + it('shows the create custom role button only on the roles and permissions tab', async () => { + const user = userEvent.setup(); + renderAuthzHome(); + const createCustomRoleButton = () => screen.queryByRole('button', { name: 'Create Custom Role' }); + + expect(createCustomRoleButton()).not.toBeInTheDocument(); + + await user.click(screen.getByRole('tab', { name: messages['authz.tabs.permissionsRoles'].defaultMessage })); + expect(createCustomRoleButton()).toBeInTheDocument(); + + await user.click(screen.getByRole('tab', { name: messages['authz.tabs.team'].defaultMessage })); + expect(createCustomRoleButton()).not.toBeInTheDocument(); + }); }); diff --git a/src/authz-module/authz-home/index.tsx b/src/authz-module/authz-home/index.tsx index 074b19e9..176ec600 100644 --- a/src/authz-module/authz-home/index.tsx +++ b/src/authz-module/authz-home/index.tsx @@ -1,5 +1,7 @@ +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'; @@ -8,13 +10,18 @@ import { CustomErrors } from '@src/constants'; import LoadingPage from '@src/components/LoadingPage'; import { RolesPermissionsTable } from '@src/authz-module/roles-permissions'; import AuthZLayout from '@src/authz-module/components/AuthZLayout'; +import CreateCustomRole from '@src/authz-module/roles-permissions/components/CreateCustomRole'; import messages from './messages'; +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 '+' @@ -47,15 +54,15 @@ const AuthzHome = () => { return ( ] - } + actions={[ + , + ...(activeTab === 'permissionsRoles' ? [] : []), + ]} > 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/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..62f2cac9 --- /dev/null +++ b/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx @@ -0,0 +1,312 @@ +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 CreateCustomRole from './CreateCustomRole'; + +jest.mock('@src/authz-module/catalog/data/hooks', () => ({ + useAuthzCatalog: 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 }); + }); + + 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('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('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('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..6f47c3f1 --- /dev/null +++ b/src/authz-module/roles-permissions/components/CreateCustomRole.tsx @@ -0,0 +1,197 @@ +import { useEffect, useId, useRef, useState } from 'react'; +import { useIntl } from '@openedx/frontend-base'; +import { Button, FullscreenModal, Stepper } from '@openedx/paragon'; +import { Add } 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 } from '../customRoleDraft'; +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', + 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 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; + let nextBlocker: typeof NEXT_BLOCKERS[keyof typeof NEXT_BLOCKERS] | null = null; + if (!draft.name.trim()) { + nextBlocker = NEXT_BLOCKERS.NAME; + } else if (!canProceed && draft.startFrom === START_FROM.CLONE) { + nextBlocker = NEXT_BLOCKERS.SOURCE_ROLE; + } + + 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) => setDraft((prev) => ({ ...prev, ...changes })); + + const handleNext = () => { + if (!canProceed) { + setHasTriedNext(true); + setFocusRequest((count) => count + 1); + return; + } + 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. */} + + {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..e7d4135d --- /dev/null +++ b/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx @@ -0,0 +1,281 @@ +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 { START_FROM } from '../customRoleDraft'; +import type { CustomRoleDraft, StartFrom } from '../customRoleDraft'; +import messages from '../messages'; + +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; +} + +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, +}: 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 moves focus to the first answer it needs, where the error is read out. + useEffect(() => { + if (focusRequest === 0) return; + document.getElementById(isNameMissing ? 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} + required + /> + {showNameError && ( + + {formatMessage(messages['authz.roles.create.wizard.name.error'])} + + )} + + {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..288f212f --- /dev/null +++ b/src/authz-module/roles-permissions/customRoleDraft.ts @@ -0,0 +1,56 @@ +import type { Role } from '@src/authz-module/catalog'; + +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] }; +}; diff --git a/src/authz-module/roles-permissions/messages.ts b/src/authz-module/roles-permissions/messages.ts index b3ee2230..e19a9cc3 100644 --- a/src/authz-module/roles-permissions/messages.ts +++ b/src/authz-module/roles-permissions/messages.ts @@ -111,6 +111,151 @@ 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.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.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.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.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 {}}', From bbd1df075d33968d7fc466a32f2991783ab8793c Mon Sep 17 00:00:00 2001 From: jacobo-dominguez-wgu Date: Fri, 27 Nov 2026 12:01:00 -0600 Subject: [PATCH 2/7] fix(authz): hide the create custom role button from non-staff users --- src/authz-module/authz-home/index.test.tsx | 11 ++++++++++- src/authz-module/authz-home/index.tsx | 12 ++++++++---- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/authz-module/authz-home/index.test.tsx b/src/authz-module/authz-home/index.test.tsx index b25327d2..8ebf7202 100644 --- a/src/authz-module/authz-home/index.test.tsx +++ b/src/authz-module/authz-home/index.test.tsx @@ -7,7 +7,7 @@ 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 { usePermissions } from '@openedx/frontend-base'; +import { getAuthenticatedUser, usePermissions } from '@openedx/frontend-base'; import { SCOPE_TYPES } from '@src/authz-module/constants'; import baseMessages from '@src/authz-module/messages'; import AuthzHome from './index'; @@ -33,6 +33,7 @@ jest.mock('@src/authz-module/hooks/useViewTeamPermissions', () => ({ 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 })), })); @@ -81,6 +82,7 @@ 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 }); (useTeamMembersAssignments as jest.Mock).mockReturnValue(emptyResponse); @@ -203,4 +205,11 @@ describe('AuthzHome', () => { await user.click(screen.getByRole('tab', { name: messages['authz.tabs.team'].defaultMessage })); expect(createCustomRoleButton()).not.toBeInTheDocument(); }); + it('hides the create custom role button from non-staff users', async () => { + const user = userEvent.setup(); + (getAuthenticatedUser as jest.Mock).mockReturnValue({ administrator: 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 176ec600..7828c2d0 100644 --- a/src/authz-module/authz-home/index.tsx +++ b/src/authz-module/authz-home/index.tsx @@ -1,5 +1,5 @@ -import { useState } from 'react'; -import { useIntl } from '@openedx/frontend-base'; +import { useMemo, useState } from 'react'; +import { getAuthenticatedUser, useIntl } from '@openedx/frontend-base'; import { Tab, Tabs } from '@openedx/paragon'; import { PersonAdd } from '@openedx/paragon/icons'; import { useLocation, useSearchParams } from 'react-router-dom'; @@ -28,6 +28,10 @@ const AuthzHome = () => { */ const presetScope = searchParams.get('scope')?.replace(/\s/g, '+') || undefined; + const showCreateCustomRole = useMemo(() => { + return getAuthenticatedUser()?.administrator ? activeTab === 'permissionsRoles' : false; + }, [activeTab]); + const pageTitle = intl.formatMessage(messages['authz.manage.page.title']); const { @@ -55,8 +59,8 @@ const AuthzHome = () => { , - ...(activeTab === 'permissionsRoles' ? [] : []), + , + ...(showCreateCustomRole ? [] : []), ]} > Date: Fri, 27 Nov 2026 12:01:00 -0600 Subject: [PATCH 3/7] fix(authz): explain why Next is blocked while the roles load or fail --- .../roles-permissions/components/CreateCustomRole.tsx | 7 +++++++ src/authz-module/roles-permissions/messages.ts | 10 ++++++++++ 2 files changed, 17 insertions(+) diff --git a/src/authz-module/roles-permissions/components/CreateCustomRole.tsx b/src/authz-module/roles-permissions/components/CreateCustomRole.tsx index 6f47c3f1..dcdccfab 100644 --- a/src/authz-module/roles-permissions/components/CreateCustomRole.tsx +++ b/src/authz-module/roles-permissions/components/CreateCustomRole.tsx @@ -19,6 +19,8 @@ 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', + CATALOG_LOADING: 'catalogLoading', + CATALOG_ERROR: 'catalogError', SOURCE_ROLE: 'sourceRole', } as const; @@ -66,6 +68,11 @@ export const CreateCustomRoleWizard = ({ onClose }: CreateCustomRoleWizardProps) let nextBlocker: typeof NEXT_BLOCKERS[keyof typeof NEXT_BLOCKERS] | null = null; if (!draft.name.trim()) { nextBlocker = NEXT_BLOCKERS.NAME; + } 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; } diff --git a/src/authz-module/roles-permissions/messages.ts b/src/authz-module/roles-permissions/messages.ts index e19a9cc3..539ddd54 100644 --- a/src/authz-module/roles-permissions/messages.ts +++ b/src/authz-module/roles-permissions/messages.ts @@ -161,6 +161,16 @@ const messages = defineMessages({ 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.', From 464eff6aae2abd5886319d503aff0ee35086ea50 Mon Sep 17 00:00:00 2001 From: jacobo-dominguez-wgu Date: Fri, 27 Nov 2026 12:01:00 -0600 Subject: [PATCH 4/7] fix(authz): limit the custom role name to 255 characters --- .../components/CreateCustomRole.test.tsx | 20 +++++++++++++++++++ .../components/NameAndResourceStep.tsx | 3 ++- .../roles-permissions/customRoleDraft.ts | 3 +++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx b/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx index 62f2cac9..0ed115af 100644 --- a/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx +++ b/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx @@ -50,6 +50,14 @@ describe('CreateCustomRole', () => { 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(); @@ -242,6 +250,18 @@ describe('CreateCustomRole', () => { 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 }); diff --git a/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx b/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx index e7d4135d..77be4578 100644 --- a/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx +++ b/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx @@ -6,7 +6,7 @@ import { import { isCustomRole } from '@src/authz-module/catalog'; import type { Role, ScopeCatalog } from '@src/authz-module/catalog'; import { RESOURCE_TYPE_DISPLAY } from '../constants'; -import { START_FROM } from '../customRoleDraft'; +import { MAX_ROLE_NAME_LENGTH, START_FROM } from '../customRoleDraft'; import type { CustomRoleDraft, StartFrom } from '../customRoleDraft'; import messages from '../messages'; @@ -98,6 +98,7 @@ const NameAndResourceStep = ({ onBlur={() => setIsNameTouched(true)} placeholder={formatMessage(messages['authz.roles.create.wizard.name.placeholder'])} isInvalid={showNameError} + maxLength={MAX_ROLE_NAME_LENGTH} required /> {showNameError && ( diff --git a/src/authz-module/roles-permissions/customRoleDraft.ts b/src/authz-module/roles-permissions/customRoleDraft.ts index 288f212f..a74268e0 100644 --- a/src/authz-module/roles-permissions/customRoleDraft.ts +++ b/src/authz-module/roles-permissions/customRoleDraft.ts @@ -1,5 +1,8 @@ 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', From a137e6b95960cc95b3f4b5a34662347a1cccd618 Mon Sep 17 00:00:00 2001 From: jacobo-dominguez-wgu Date: Fri, 27 Nov 2026 16:37:57 -0600 Subject: [PATCH 5/7] feat(authz): check the custom role name before leaving step one Next calls POST /api/authz/v1/roles/validate-name/ and only moves to the permissions step when the name is available. A taken or invalid name shows its error under the name field and disables Next until the name changes. --- src/authz-module/data/api.ts | 20 ++++++ src/authz-module/data/hooks.ts | 13 +++- .../components/CreateCustomRole.test.tsx | 65 +++++++++++++++++++ .../components/CreateCustomRole.tsx | 41 ++++++++++-- .../components/NameAndResourceStep.tsx | 11 +++- .../roles-permissions/customRoleDraft.ts | 3 + .../roles-permissions/messages.ts | 20 ++++++ 7 files changed, 166 insertions(+), 7 deletions(-) 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.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/roles-permissions/components/CreateCustomRole.test.tsx b/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx index 0ed115af..25b9007c 100644 --- a/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx +++ b/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx @@ -3,12 +3,19 @@ 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: [ @@ -38,6 +45,8 @@ 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 () => { @@ -190,6 +199,62 @@ describe('CreateCustomRole', () => { 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.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'); + 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' })).toBeInTheDocument(); + // 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(); diff --git a/src/authz-module/roles-permissions/components/CreateCustomRole.tsx b/src/authz-module/roles-permissions/components/CreateCustomRole.tsx index dcdccfab..931ba704 100644 --- a/src/authz-module/roles-permissions/components/CreateCustomRole.tsx +++ b/src/authz-module/roles-permissions/components/CreateCustomRole.tsx @@ -5,7 +5,8 @@ import { Add } 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 } from '../customRoleDraft'; +import type { CustomRoleDraft, NameCheckError } from '../customRoleDraft'; +import { useValidateRoleName } from '../../data/hooks'; import messages from '../messages'; import NameAndResourceStep from './NameAndResourceStep'; @@ -19,6 +20,7 @@ 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', @@ -48,6 +50,8 @@ export const CreateCustomRoleWizard = ({ onClose }: CreateCustomRoleWizardProps) 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); @@ -65,9 +69,13 @@ export const CreateCustomRoleWizard = ({ onClose }: CreateCustomRoleWizardProps) // 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) { @@ -77,6 +85,8 @@ export const CreateCustomRoleWizard = ({ onClose }: CreateCustomRoleWizardProps) 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']), @@ -88,14 +98,34 @@ export const CreateCustomRoleWizard = ({ onClose }: CreateCustomRoleWizardProps) title: stepTitles[step], }); - const handleDraftChange = (changes: Partial) => setDraft((prev) => ({ ...prev, ...changes })); + const handleDraftChange = (changes: Partial) => { + // A new name makes the previous check result stale. + if (changes.name !== undefined) setNameCheckError(null); + setDraft((prev) => ({ ...prev, ...changes })); + }; - const handleNext = () => { + /** + * 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); + if (!result.available) { + setNameCheckError(result.reason === 'invalid' ? 'invalid' : 'taken'); + return; + } + } catch { + setNameCheckError('failed'); + return; + } + setNameCheckError(null); setDraft(effectiveDraft); setActiveStep(STEPS.PERMISSIONS); }; @@ -120,8 +150,8 @@ export const CreateCustomRoleWizard = ({ onClose }: CreateCustomRoleWizardProps) {/* aria-disabled, not disabled, so Next stays focusable and can say what is missing. */}
diff --git a/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx b/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx index 77be4578..a68022d8 100644 --- a/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx +++ b/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx @@ -9,6 +9,7 @@ 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; @@ -21,6 +22,8 @@ interface NameAndResourceStepProps { 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]; @@ -35,6 +38,7 @@ const ARROW_KEY_OFFSETS: Record = { */ const NameAndResourceStep = ({ draft, onChange, scopeCatalogs, isLoading = false, isError = false, showErrors = false, focusRequest = 0, + nameCheckError = null, }: NameAndResourceStepProps) => { const { formatMessage } = useIntl(); const idPrefix = useId(); @@ -97,7 +101,7 @@ const NameAndResourceStep = ({ onChange={(e: React.ChangeEvent) => onChange({ name: e.target.value })} onBlur={() => setIsNameTouched(true)} placeholder={formatMessage(messages['authz.roles.create.wizard.name.placeholder'])} - isInvalid={showNameError} + isInvalid={showNameError || nameCheckError !== null} maxLength={MAX_ROLE_NAME_LENGTH} required /> @@ -106,6 +110,11 @@ const NameAndResourceStep = ({ {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'])} diff --git a/src/authz-module/roles-permissions/customRoleDraft.ts b/src/authz-module/roles-permissions/customRoleDraft.ts index a74268e0..3d7f7696 100644 --- a/src/authz-module/roles-permissions/customRoleDraft.ts +++ b/src/authz-module/roles-permissions/customRoleDraft.ts @@ -57,3 +57,6 @@ export const getCustomRoleSeed = ( 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/messages.ts b/src/authz-module/roles-permissions/messages.ts index 539ddd54..54cf8618 100644 --- a/src/authz-module/roles-permissions/messages.ts +++ b/src/authz-module/roles-permissions/messages.ts @@ -156,6 +156,11 @@ const messages = defineMessages({ 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.', @@ -176,6 +181,21 @@ const messages = defineMessages({ 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.', From a6385e882e8327711ad960f6fb1322edb5191af9 Mon Sep 17 00:00:00 2001 From: jacobo-dominguez-wgu Date: Fri, 27 Nov 2026 16:44:44 -0600 Subject: [PATCH 6/7] test(authz): cover the role name validation request and hook --- src/authz-module/authz-home/index.tsx | 5 ++- src/authz-module/data/api.test.tsx | 21 ++++++++++++ src/authz-module/data/hooks.test.tsx | 33 +++++++++++++++++++ .../components/CreateCustomRole.test.tsx | 3 +- .../components/CreateCustomRole.tsx | 2 ++ .../components/NameAndResourceStep.tsx | 13 ++++---- src/authz-module/roles-permissions/index.ts | 1 + 7 files changed, 67 insertions(+), 11 deletions(-) diff --git a/src/authz-module/authz-home/index.tsx b/src/authz-module/authz-home/index.tsx index 7828c2d0..bfa9656e 100644 --- a/src/authz-module/authz-home/index.tsx +++ b/src/authz-module/authz-home/index.tsx @@ -8,9 +8,8 @@ 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 CreateCustomRole from '@src/authz-module/roles-permissions/components/CreateCustomRole'; import messages from './messages'; @@ -29,7 +28,7 @@ const AuthzHome = () => { const presetScope = searchParams.get('scope')?.replace(/\s/g, '+') || undefined; const showCreateCustomRole = useMemo(() => { - return getAuthenticatedUser()?.administrator ? activeTab === 'permissionsRoles' : false; + return (getAuthenticatedUser()?.administrator || getAuthenticatedUser()?.superuser) ? activeTab === 'permissionsRoles' : false; }, [activeTab]); const pageTitle = intl.formatMessage(messages['authz.manage.page.title']); 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/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/roles-permissions/components/CreateCustomRole.test.tsx b/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx index 25b9007c..2028745a 100644 --- a/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx +++ b/src/authz-module/roles-permissions/components/CreateCustomRole.test.tsx @@ -221,6 +221,7 @@ describe('CreateCustomRole', () => { 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()); @@ -233,7 +234,7 @@ describe('CreateCustomRole', () => { 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' })).toBeInTheDocument(); + expect(screen.getByRole('textbox', { name: 'Role name' })).toHaveFocus(); // A failed check says nothing about the name, so Next stays available to retry. expectNextAllowed(); }); diff --git a/src/authz-module/roles-permissions/components/CreateCustomRole.tsx b/src/authz-module/roles-permissions/components/CreateCustomRole.tsx index 931ba704..19fa0e26 100644 --- a/src/authz-module/roles-permissions/components/CreateCustomRole.tsx +++ b/src/authz-module/roles-permissions/components/CreateCustomRole.tsx @@ -119,10 +119,12 @@ export const CreateCustomRoleWizard = ({ onClose }: CreateCustomRoleWizardProps) const result = await validateRoleName(effectiveDraft.name); if (!result.available) { setNameCheckError(result.reason === 'invalid' ? 'invalid' : 'taken'); + setFocusRequest((count) => count + 1); return; } } catch { setNameCheckError('failed'); + setFocusRequest((count) => count + 1); return; } setNameCheckError(null); diff --git a/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx b/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx index a68022d8..1689a569 100644 --- a/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx +++ b/src/authz-module/roles-permissions/components/NameAndResourceStep.tsx @@ -23,7 +23,7 @@ interface NameAndResourceStepProps { // 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; + nameCheckError: NameCheckError | null; } const START_FROM_OPTIONS = [START_FROM.SCRATCH, START_FROM.CLONE]; @@ -37,8 +37,7 @@ const ARROW_KEY_OFFSETS: Record = { * 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 = null, + draft, onChange, scopeCatalogs, isLoading = false, isError = false, showErrors = false, focusRequest = 0, nameCheckError, }: NameAndResourceStepProps) => { const { formatMessage } = useIntl(); const idPrefix = useId(); @@ -67,10 +66,10 @@ const NameAndResourceStep = ({ const showNameError = isNameMissing && (isNameTouched || showErrors); const showSourceRoleError = showErrors && draft.startFrom === START_FROM.CLONE && !selectedSourceRole; - // A blocked Next moves focus to the first answer it needs, where the error is read out. + // 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 ? nameInputId : sourceRoleToggleId)?.focus(); + 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]); @@ -106,12 +105,12 @@ const NameAndResourceStep = ({ required /> {showNameError && ( - + {formatMessage(messages['authz.roles.create.wizard.name.error'])} )} {!showNameError && nameCheckError && ( - + {formatMessage(messages[`authz.roles.create.wizard.name.alert.${nameCheckError}`])} )} 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'; From 64fe2f8d83345f51d21fe99e7564e96b4e6794e5 Mon Sep 17 00:00:00 2001 From: jacobo-dominguez-wgu Date: Wed, 2 Dec 2026 12:14:23 -0600 Subject: [PATCH 7/7] feat: redesign for the header butons and validations --- src/authz-module/authz-home/index.test.tsx | 30 ++++++++----------- src/authz-module/authz-home/index.tsx | 11 ++++--- .../components/CreateCustomRole.test.tsx | 6 ++++ .../components/CreateCustomRole.tsx | 22 +++++++++----- .../roles-permissions/messages.ts | 5 ++++ 5 files changed, 43 insertions(+), 31 deletions(-) diff --git a/src/authz-module/authz-home/index.test.tsx b/src/authz-module/authz-home/index.test.tsx index 8ebf7202..a7d9b911 100644 --- a/src/authz-module/authz-home/index.test.tsx +++ b/src/authz-module/authz-home/index.test.tsx @@ -10,9 +10,16 @@ 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(), @@ -85,6 +92,7 @@ describe('AuthzHome', () => { (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); @@ -173,41 +181,29 @@ describe('AuthzHome', () => { expect(teamTab.getByText('Actions')).toBeInTheDocument(); }); - it('outlines the assign role button only while the roles and permissions tab is active', async () => { + it('shows the assign role button', async () => { (usePermissions as jest.Mock).mockReturnValue({ [SCOPE_TYPES.COURSE]: false, [SCOPE_TYPES.LIBRARY]: true, isLoading: false, }); - const user = userEvent.setup(); renderAuthzHome(); const assignRoleButton = () => screen.getByRole('button', { name: baseMessages['authz.management.assign.role.title'].defaultMessage, }); expect(assignRoleButton()).toHaveClass('btn-primary'); - - await user.click(screen.getByRole('tab', { name: messages['authz.tabs.permissionsRoles'].defaultMessage })); - expect(assignRoleButton()).toHaveClass('btn-outline-primary'); - - await user.click(screen.getByRole('tab', { name: messages['authz.tabs.team'].defaultMessage })); - expect(assignRoleButton()).toHaveClass('btn-primary'); }); - it('shows the create custom role button only on the roles and permissions tab', async () => { - const user = userEvent.setup(); + 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()).not.toBeInTheDocument(); - - await user.click(screen.getByRole('tab', { name: messages['authz.tabs.permissionsRoles'].defaultMessage })); expect(createCustomRoleButton()).toBeInTheDocument(); - - await user.click(screen.getByRole('tab', { name: messages['authz.tabs.team'].defaultMessage })); - expect(createCustomRoleButton()).not.toBeInTheDocument(); }); + it('hides the create custom role button from non-staff users', async () => { const user = userEvent.setup(); - (getAuthenticatedUser as jest.Mock).mockReturnValue({ administrator: false }); + 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 bfa9656e..c4237efa 100644 --- a/src/authz-module/authz-home/index.tsx +++ b/src/authz-module/authz-home/index.tsx @@ -1,5 +1,5 @@ -import { useMemo, useState } from 'react'; -import { getAuthenticatedUser, useIntl } from '@openedx/frontend-base'; +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'; @@ -12,6 +12,7 @@ import { RolesPermissionsTable, CreateCustomRole } from '@src/authz-module/roles import AuthZLayout from '@src/authz-module/components/AuthZLayout'; import messages from './messages'; +import { useCanManageRoles } from '@src/authz-module/hooks/useCanManageRoles'; type AuthzHomeTab = 'team' | 'permissionsRoles'; @@ -27,9 +28,7 @@ const AuthzHome = () => { */ const presetScope = searchParams.get('scope')?.replace(/\s/g, '+') || undefined; - const showCreateCustomRole = useMemo(() => { - return (getAuthenticatedUser()?.administrator || getAuthenticatedUser()?.superuser) ? activeTab === 'permissionsRoles' : false; - }, [activeTab]); + const showCreateCustomRole = useCanManageRoles(); const pageTitle = intl.formatMessage(messages['authz.manage.page.title']); @@ -58,8 +57,8 @@ const AuthzHome = () => { , ...(showCreateCustomRole ? [] : []), + ]} > { 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.'], diff --git a/src/authz-module/roles-permissions/components/CreateCustomRole.tsx b/src/authz-module/roles-permissions/components/CreateCustomRole.tsx index 19fa0e26..9493cdac 100644 --- a/src/authz-module/roles-permissions/components/CreateCustomRole.tsx +++ b/src/authz-module/roles-permissions/components/CreateCustomRole.tsx @@ -1,7 +1,9 @@ import { useEffect, useId, useRef, useState } from 'react'; import { useIntl } from '@openedx/frontend-base'; -import { Button, FullscreenModal, Stepper } from '@openedx/paragon'; -import { Add } from '@openedx/paragon/icons'; +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'; @@ -116,7 +118,7 @@ export const CreateCustomRoleWizard = ({ onClose }: CreateCustomRoleWizardProps) return; } try { - const result = await validateRoleName(effectiveDraft.name); + const result = await validateRoleName(effectiveDraft.name?.trim()); if (!result.available) { setNameCheckError(result.reason === 'invalid' ? 'invalid' : 'taken'); setFocusRequest((count) => count + 1); @@ -150,14 +152,18 @@ export const CreateCustomRoleWizard = ({ onClose }: CreateCustomRoleWizardProps) {/* aria-disabled, not disabled, so Next stays focusable and can say what is missing. */} - + /> {nextBlocker && ( {formatMessage(messages[`authz.roles.create.wizard.button.next.hint.${nextBlocker}`])} @@ -226,7 +232,7 @@ const CreateCustomRole = () => { const [isWizardOpen, setIsWizardOpen] = useState(false); return ( <> - {isWizardOpen && setIsWizardOpen(false)} />} diff --git a/src/authz-module/roles-permissions/messages.ts b/src/authz-module/roles-permissions/messages.ts index 54cf8618..97b28334 100644 --- a/src/authz-module/roles-permissions/messages.ts +++ b/src/authz-module/roles-permissions/messages.ts @@ -146,6 +146,11 @@ const messages = defineMessages({ 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',