snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
import { useTranslation } from 'react-i18next';
import GenericUpsellModal from '../../../components/GenericUpsellModal';
import { useUpsellActions } from '../../../components/GenericUpsellModal/hooks';
const CustomRoleUpsellModal = ({ onClose }: { onClose: () => void }) => {
const { t } = useTranslation();
const { handleManageSubscription } = useUpsellActions();
return (
<GenericUpsellModal
aria-label={t('Custom_roles')}
img='images/custom-role-upsell-modal.png'
title={t('Custom_roles')}
subtitle={t('Custom_roles_upsell_add_custom_roles_workspace')}
description={t('Custom_roles_upsell_add_custom_roles_workspace_description')}
onClose={onClose}
onConfirm={handleManageSubscription}
onCancel={onClose}
/>
);
};
export default CustomRoleUpsellModal;

View File

@@ -0,0 +1,128 @@
import type { IRole } from '@rocket.chat/core-typings';
import { Box, ButtonGroup, Button, Margins } from '@rocket.chat/fuselage';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { GenericModal, ContextualbarFooter, ContextualbarScrollableContent } from '@rocket.chat/ui-client';
import { useSetModal, useToastMessageDispatch, useRoute, useEndpoint } from '@rocket.chat/ui-contexts';
import { FormProvider, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import RoleForm from './RoleForm';
export type EditRolePageFormData = {
roleId: string;
name: string;
description: string;
scope: 'Users' | 'Subscriptions';
mandatory2fa: boolean;
};
export type EditRolePageProps = { role?: IRole; isEnterprise: boolean };
const EditRolePage = ({ role, isEnterprise }: EditRolePageProps) => {
const { t } = useTranslation();
const dispatchToastMessage = useToastMessageDispatch();
const setModal = useSetModal();
const usersInRoleRouter = useRoute('admin-permissions');
const router = useRoute('admin-permissions');
const createRole = useEndpoint('POST', '/v1/roles.create');
const updateRole = useEndpoint('POST', '/v1/roles.update');
const deleteRole = useEndpoint('POST', '/v1/roles.delete');
const methods = useForm<EditRolePageFormData>({
defaultValues: {
roleId: role?._id,
name: role?.name,
description: role?.description,
scope: role?.scope || 'Users',
mandatory2fa: !!role?.mandatory2fa,
},
});
const handleManageUsers = useStableCallback(() => {
if (role?._id) {
usersInRoleRouter.push({
context: 'users-in-role',
_id: role._id,
});
}
});
const handleSave = useStableCallback(async (data: EditRolePageFormData) => {
try {
if (data.roleId) {
await updateRole(data);
dispatchToastMessage({ type: 'success', message: t('Saved') });
return router.push({});
}
await createRole(data);
dispatchToastMessage({ type: 'success', message: t('Saved') });
router.push({});
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
});
const handleDelete = useStableCallback(async () => {
if (!role?._id) {
return;
}
const deleteRoleAction = async (): Promise<void> => {
try {
await deleteRole({ roleId: role._id });
dispatchToastMessage({ type: 'success', message: t('Role_removed') });
setModal();
router.push({});
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
setModal();
}
};
const deleteRoleMessage = isEnterprise ? t('Delete_Role_Warning') : t('Delete_Role_Warning_Not_Enterprise');
setModal(
<GenericModal
variant='danger'
onConfirm={deleteRoleAction}
onClose={(): void => setModal()}
onCancel={(): void => setModal()}
confirmText={t('Delete')}
>
{deleteRoleMessage}
</GenericModal>,
);
});
return (
<>
<ContextualbarScrollableContent>
<Box width='full' alignSelf='center' marginBlock='neg-x8'>
<Margins block={8}>
<FormProvider {...methods}>
<RoleForm editing={Boolean(role?._id)} isProtected={role?.protected} isDisabled={!isEnterprise} />
</FormProvider>
</Margins>
</Box>
</ContextualbarScrollableContent>
<ContextualbarFooter>
<ButtonGroup vertical stretch>
<Button primary disabled={!methods.formState.isDirty || !isEnterprise} onClick={methods.handleSubmit(handleSave)}>
{t('Save')}
</Button>
{!role?.protected && role?._id && (
<Button secondary danger onClick={handleDelete}>
{t('Delete')}
</Button>
)}
{role?._id && <Button onClick={handleManageUsers}>{t('Users_in_role')}</Button>}
</ButtonGroup>
</ContextualbarFooter>
</>
);
};
export default EditRolePage;

View File

@@ -0,0 +1,35 @@
import type { IRole } from '@rocket.chat/core-typings';
import { Callout } from '@rocket.chat/fuselage';
import { useRouteParameter } from '@rocket.chat/ui-contexts';
import { useTranslation } from 'react-i18next';
import EditRolePage from './EditRolePage';
import { useRole } from './hooks/useRole';
import GenericError from '../../../components/GenericError';
import PageSkeleton from '../../../components/PageSkeleton';
import { useHasLicenseModule } from '../../../hooks/useHasLicenseModule';
export type EditRolePageWithDataProps = { roleId?: IRole['_id'] };
const EditRolePageWithData = ({ roleId }: EditRolePageWithDataProps) => {
const { t } = useTranslation();
const role = useRole(roleId);
const context = useRouteParameter('context');
const { isPending, isError, data: hasLicense } = useHasLicenseModule('custom-roles');
if (!role && context === 'edit') {
return <Callout type='danger'>{t('error-invalid-role')}</Callout>;
}
if (isPending) {
return <PageSkeleton />;
}
if (isError) {
return <GenericError />;
}
return <EditRolePage key={roleId} role={role} isEnterprise={hasLicense} />;
};
export default EditRolePageWithData;

View File

@@ -0,0 +1,49 @@
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { ContextualbarHeader, ContextualbarTitle, ContextualbarClose, ContextualbarDialog } from '@rocket.chat/ui-client';
import { useRouteParameter, useRoute, useTranslation, useSetModal } from '@rocket.chat/ui-contexts';
import { useEffect } from 'react';
import CustomRoleUpsellModal from './CustomRoleUpsellModal';
import EditRolePageWithData from './EditRolePageWithData';
import { useHasLicenseModule } from '../../../hooks/useHasLicenseModule';
const PermissionsContextBar = () => {
const t = useTranslation();
const _id = useRouteParameter('_id');
const context = useRouteParameter('context');
const router = useRoute('admin-permissions');
const setModal = useSetModal();
const { isPending, data: hasCustomRolesModule = false } = useHasLicenseModule('custom-roles');
const handleCloseContextualbar = useStableCallback(() => {
router.push({});
});
useEffect(() => {
if (isPending) {
return;
}
if (context !== 'new' || hasCustomRolesModule) {
return;
}
setModal(<CustomRoleUpsellModal onClose={() => setModal(null)} />);
handleCloseContextualbar();
}, [isPending, context, hasCustomRolesModule, handleCloseContextualbar, setModal]);
return (
(context && (
<ContextualbarDialog onClose={handleCloseContextualbar}>
<ContextualbarHeader>
<ContextualbarTitle>{context === 'edit' ? t('Role_Editing') : t('New_role')}</ContextualbarTitle>
<ContextualbarClose onClick={handleCloseContextualbar} />
</ContextualbarHeader>
<EditRolePageWithData roleId={_id} />
</ContextualbarDialog>
)) ||
null
);
};
export default PermissionsContextBar;

View File

@@ -0,0 +1,91 @@
import { Margins, Tabs, TabsItem, Button } from '@rocket.chat/fuselage';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { usePagination, Page, PageHeader, PageContent } from '@rocket.chat/ui-client';
import { useRoute, usePermission, useSetModal } from '@rocket.chat/ui-contexts';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import CustomRoleUpsellModal from './CustomRoleUpsellModal';
import PermissionsContextBar from './PermissionsContextBar';
import PermissionsTable from './PermissionsTable';
import { usePermissionsAndRoles } from './hooks/usePermissionsAndRoles';
export type PermissionsPageProps = { isEnterprise: boolean };
const PermissionsPage = ({ isEnterprise }: PermissionsPageProps) => {
const { t } = useTranslation();
const [filter, setFilter] = useState('');
const canViewPermission = usePermission('access-permissions');
const canViewSettingPermission = usePermission('access-setting-permissions');
const defaultType = canViewPermission ? 'permissions' : 'settings';
const [type, setType] = useState(defaultType);
const router = useRoute('admin-permissions');
const setModal = useSetModal();
const paginationData = usePagination();
const { permissions, total, roleList } = usePermissionsAndRoles(type, filter, paginationData.itemsPerPage, paginationData.current);
const handlePermissionsTab = useStableCallback(() => {
if (type === 'permissions') {
return;
}
setType('permissions');
});
const handleSettingsTab = useStableCallback(() => {
if (type === 'settings') {
return;
}
setType('settings');
});
const handleAdd = useStableCallback(() => {
if (!isEnterprise) {
setModal(<CustomRoleUpsellModal onClose={() => setModal(null)} />);
return;
}
router.push({
context: 'new',
});
});
return (
<Page flexDirection='row'>
<Page>
<PageHeader title={t('Permissions')}>
<Button primary onClick={handleAdd} aria-label={t('New')} name={t('New_role')}>
{t('New_role')}
</Button>
</PageHeader>
<Margins blockEnd={16}>
<Tabs>
<TabsItem
selected={type === 'permissions'}
onClick={canViewPermission ? handlePermissionsTab : undefined}
disabled={!canViewPermission}
>
{t('Permissions')}
</TabsItem>
<TabsItem selected={type === 'settings'} onClick={handleSettingsTab} disabled={!canViewSettingPermission}>
{t('Settings')}
</TabsItem>
</Tabs>
</Margins>
<PageContent marginBlock='neg-x8'>
<Margins block={8}>
<PermissionsTable
roleList={roleList}
permissions={permissions}
total={total}
setFilter={setFilter}
paginationData={paginationData}
/>
</Margins>
</PageContent>
</Page>
<PermissionsContextBar />
</Page>
);
};
export default PermissionsPage;

View File

@@ -0,0 +1,30 @@
import { useRouteParameter, usePermission } from '@rocket.chat/ui-contexts';
import PermissionsPage from './PermissionsPage';
import UsersInRole from './UsersInRole';
import PageSkeleton from '../../../components/PageSkeleton';
import { useIsEnterprise } from '../../../hooks/useIsEnterprise';
import NotAuthorizedPage from '../../notAuthorized/NotAuthorizedPage';
const PermissionsRouter = () => {
const canViewPermission = usePermission('access-permissions');
const canViewSettingPermission = usePermission('access-setting-permissions');
const context = useRouteParameter('context');
const { data, isLoading } = useIsEnterprise();
if (isLoading) {
<PageSkeleton />;
}
if (!canViewPermission && !canViewSettingPermission) {
return <NotAuthorizedPage />;
}
if (context === 'users-in-role') {
return <UsersInRole />;
}
return <PermissionsPage isEnterprise={!!data?.isEnterprise} />;
};
export default PermissionsRouter;

View File

@@ -0,0 +1,61 @@
import type { IRole, IPermission } from '@rocket.chat/core-typings';
import { GenericTableRow, GenericTableCell } from '@rocket.chat/ui-client';
import type { TranslationKey } from '@rocket.chat/ui-contexts';
import type { TFunction } from 'i18next';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import RoleCell from './RoleCell';
import { CONSTANTS } from '../../../../../app/authorization/lib';
import { useChangeRole } from '../hooks/useChangeRole';
const getName = (t: TFunction, permission: IPermission): string => {
if (permission.level === CONSTANTS.SETTINGS_LEVEL) {
let path = '';
if (permission.group) {
path = `${t(permission.group as TranslationKey)} > `;
}
if (permission.section) {
path = `${path}${t(permission.section as TranslationKey)} > `;
}
return `${path}${t(permission.settingId as TranslationKey)}`;
}
return t(permission._id as TranslationKey);
};
export type PermissionRowProps = {
permission: IPermission;
roleList: IRole[];
onGrant: (permissionId: IPermission['_id'], roleId: IRole['_id']) => Promise<void>;
onRemove: (permissionId: IPermission['_id'], roleId: IRole['_id']) => Promise<void>;
};
const PermissionRow = ({ permission, roleList, onGrant, onRemove }: PermissionRowProps) => {
const { t } = useTranslation();
const { _id: permissionId, roles } = permission;
const changeRole = useChangeRole({ onGrant, onRemove, permissionId });
const permissionName = getName(t, permission);
return (
<GenericTableRow key={permissionId} role='link' action tabIndex={0}>
<GenericTableCell maxWidth='x300' withTruncatedText title={t(`${permissionId}_description` as TranslationKey)}>
{permissionName}
</GenericTableCell>
{roleList.map(({ _id: roleId, name, description }) => (
<RoleCell
key={roleId}
_id={roleId}
name={name}
description={description}
grantedRoles={roles}
onChange={changeRole}
permissionId={permissionId}
permissionName={permissionName}
/>
))}
</GenericTableRow>
);
};
export default memo(PermissionRow);

View File

@@ -0,0 +1,99 @@
import type { IPermission, IRole } from '@rocket.chat/core-typings';
import { mockAppRoot } from '@rocket.chat/mock-providers';
import { composeStories } from '@storybook/react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { axe } from 'jest-axe';
import PermissionsTable from './PermissionsTable';
import * as stories from './PermissionsTable.stories';
import { createMockedPagination } from '../../../../../tests/mocks/data';
const testCases = Object.values(composeStories(stories)).map((Story) => [Story.storyName || 'Story', Story]);
test.each(testCases)(`renders %s without crashing`, async (_storyname, Story) => {
const { baseElement } = render(<Story />, { wrapper: mockAppRoot().build() });
expect(baseElement).toMatchSnapshot();
});
test.each(testCases)('%s should have no a11y violations', async (_storyname, Story) => {
const { container } = render(<Story />, { wrapper: mockAppRoot().build() });
// TODO: Needed to skip `label` because fuselage‘s `CheckBox` has a a11y empty label issue
// TODO: Needed to skip `button-name` because fuselage‘s `Pagination` buttons are missing names
const results = await axe(container, { rules: { 'label': { enabled: false }, 'button-name': { enabled: false } } });
expect(results).toHaveNoViolations();
});
const paginationData = createMockedPagination();
const defaultPermissions: IPermission[] = [
{
_id: 'access-permissions',
_updatedAt: new Date('2023-01-01'),
roles: ['admin'],
},
];
const roles: IRole[] = [
{
description: 'Owner of the workspace',
name: 'owner',
protected: true,
scope: 'Users',
_id: 'owner',
_updatedAt: new Date(),
},
{
description: 'Administrator',
name: 'admin',
protected: true,
scope: 'Users',
_id: 'admin',
_updatedAt: new Date(),
},
];
test('should display modal if the permission is access-permissions and has only one granted role', async () => {
render(
<PermissionsTable
permissions={defaultPermissions}
total={defaultPermissions.length}
setFilter={() => undefined}
roleList={roles}
paginationData={paginationData}
/>,
{
wrapper: mockAppRoot().build(),
},
);
await userEvent.click(screen.getByRole('checkbox', { name: 'access-permissions - Administrator' }));
expect(screen.getByRole('dialog')).toBeInTheDocument();
});
test('should NOT display modal if the permission is access-permissions and has more than one granted role', async () => {
const morePermissions: IPermission[] = [
{
_id: 'access-permissions',
_updatedAt: new Date('2023-01-01'),
roles: ['admin', 'owner'],
},
];
render(
<PermissionsTable
permissions={morePermissions}
total={morePermissions.length}
setFilter={() => undefined}
roleList={roles}
paginationData={paginationData}
/>,
{
wrapper: mockAppRoot().build(),
},
);
await userEvent.click(screen.getByRole('checkbox', { name: 'access-permissions - Administrator' }));
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});

View File

@@ -0,0 +1,130 @@
import type { IPermission, IRole } from '@rocket.chat/core-typings';
import { Margins } from '@rocket.chat/fuselage';
import { PageContent } from '@rocket.chat/ui-client';
import type { Meta } from '@storybook/react';
import PermissionsTable from './PermissionsTable';
import { createMockedPagination } from '../../../../../tests/mocks/data';
export default {
component: PermissionsTable,
decorators: [
(fn) => (
<PageContent marginBlock='neg-x8'>
<Margins block={8}>{fn()}</Margins>
</PageContent>
),
],
} satisfies Meta<typeof PermissionsTable>;
const roles: IRole[] = [
{
description: 'Owner of the workspace',
name: 'owner',
protected: true,
scope: 'Users',
_id: 'owner',
_updatedAt: new Date(),
},
{
description: 'Administrator',
name: 'admin',
protected: true,
scope: 'Users',
_id: 'admin',
_updatedAt: new Date(),
},
{
description: 'Leader',
name: 'leader',
protected: false,
scope: 'Subscriptions',
_id: 'leader',
_updatedAt: new Date(),
},
{
description: 'Moderator',
name: 'moderator',
protected: false,
scope: 'Subscriptions',
_id: 'moderator',
_updatedAt: new Date(),
},
{
description: 'User',
name: 'user',
protected: true,
scope: 'Users',
_id: 'user',
_updatedAt: new Date(),
},
{
description: 'Guest',
name: 'guest',
protected: true,
scope: 'Users',
_id: 'guest',
_updatedAt: new Date(),
},
{
description: 'Bot',
name: 'bot',
protected: true,
scope: 'Users',
_id: 'bot',
_updatedAt: new Date(),
},
{
description: 'App',
name: 'app',
protected: true,
scope: 'Users',
_id: 'app',
_updatedAt: new Date(),
},
];
const permissions: IPermission[] = [
{
_id: '0',
_updatedAt: new Date('2023-01-01'),
roles: ['admin'],
},
{
_id: '1',
_updatedAt: new Date('2023-01-01'),
roles: ['user'],
},
{
_id: '2',
_updatedAt: new Date('2023-01-01'),
roles: ['user'],
},
{
_id: '3',
_updatedAt: new Date('2023-01-01'),
roles: ['user'],
},
];
const paginationData = createMockedPagination(permissions.length, 10);
export const Default = {
args: {
total: 10,
permissions,
roleList: roles,
setFilter: () => undefined,
paginationData,
},
};
export const Empty = {
args: {
total: 0,
permissions: [],
roleList: [],
setFilter: () => undefined,
paginationData,
},
};

View File

@@ -0,0 +1,112 @@
import type { IPermission, IRole } from '@rocket.chat/core-typings';
import { css } from '@rocket.chat/css-in-js';
import { Pagination, Palette } from '@rocket.chat/fuselage';
import { GenericTable, GenericTableHeader, GenericTableHeaderCell, GenericTableBody } from '@rocket.chat/ui-client';
import type { usePagination } from '@rocket.chat/ui-client';
import { useEndpoint } from '@rocket.chat/ui-contexts';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import PermissionRow from './PermissionRow';
import PermissionsTableFilter from './PermissionsTableFilter';
import RoleHeader from './RoleHeader';
import GenericNoResults from '../../../../components/GenericNoResults';
export type PermissionsTableProps = {
roleList: IRole[];
permissions: IPermission[];
setFilter: (filter: string) => void;
total: number;
paginationData: ReturnType<typeof usePagination>;
};
const PermissionsTable = ({ roleList, permissions, setFilter, total, paginationData }: PermissionsTableProps) => {
const { t } = useTranslation();
const addPermissionRole = useEndpoint('POST', '/v1/permissions.addRole');
const removePermissionRole = useEndpoint('POST', '/v1/permissions.removeRole');
const grantRole = useCallback(
async (permissionId: IPermission['_id'], role: IRole['_id']) => {
await addPermissionRole({ permissionId, role });
},
[addPermissionRole],
);
const removeRole = useCallback(
async (permissionId: IPermission['_id'], role: IRole['_id']) => {
await removePermissionRole({ permissionId, role });
},
[removePermissionRole],
);
const { current, itemsPerPage, setCurrent, setItemsPerPage, ...paginationProps } = paginationData;
const tableCustomStyle = css`
// Makes the first column of the table sticky
tr > th {
&:first-child {
position: sticky;
left: 0;
background-color: ${Palette.surface['surface-light']};
z-index: 12;
}
}
tr > td {
&:first-child {
position: sticky;
left: 0;
box-shadow: -1px 0 0 ${Palette.stroke['stroke-light']} inset;
background-color: ${Palette.surface['surface-light']};
z-index: 11;
}
}
tr:hover {
td {
&:first-child {
background-color: ${Palette.surface['surface-hover']};
}
}
td > :nth-child(2) {
visibility: visible;
opacity: 1;
}
}
`;
return (
<>
<PermissionsTableFilter onChange={setFilter} />
{permissions?.length === 0 && <GenericNoResults />}
{permissions?.length > 0 && (
<>
<GenericTable className={[tableCustomStyle]} fixed={false}>
<GenericTableHeader>
<GenericTableHeaderCell width='x120'>{t('Name')}</GenericTableHeaderCell>
{roleList?.map(({ _id, name, description }) => (
<RoleHeader key={_id} _id={_id} name={name} description={description} />
))}
</GenericTableHeader>
<GenericTableBody>
{permissions.map((permission) => (
<PermissionRow key={permission._id} permission={permission} roleList={roleList} onGrant={grantRole} onRemove={removeRole} />
))}
</GenericTableBody>
</GenericTable>
<Pagination
divider
current={current}
itemsPerPage={itemsPerPage}
count={total}
onSetItemsPerPage={setItemsPerPage}
onSetCurrent={setCurrent}
{...paginationProps}
/>
</>
)}
</>
);
};
export default PermissionsTable;

View File

@@ -0,0 +1,31 @@
import { Icon, TextInput } from '@rocket.chat/fuselage';
import { useStableCallback, useDebouncedValue } from '@rocket.chat/fuselage-hooks';
import type { ChangeEvent } from 'react';
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
/**
*
* TODO: Replaced this by FilterByText, it has the same render
*/
const PermissionsTableFilter = ({ onChange }: { onChange: (debouncedFilter: string) => void }) => {
const { t } = useTranslation();
const [filter, setFilter] = useState('');
const debouncedFilter = useDebouncedValue(filter, 500);
useEffect(() => {
onChange(debouncedFilter);
}, [debouncedFilter, onChange]);
const handleFilter = useStableCallback(({ currentTarget: { value } }: ChangeEvent<HTMLInputElement>) => {
setFilter(value);
});
return (
<div>
<TextInput value={filter} onChange={handleFilter} placeholder={t('Search')} endAddon={<Icon name='magnifier' size='x20' />} />
</div>
);
};
export default PermissionsTableFilter;

View File

@@ -0,0 +1,72 @@
import type { IRole } from '@rocket.chat/core-typings';
import { Margins, Box, CheckBox, Throbber } from '@rocket.chat/fuselage';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { GenericModal, GenericTableCell } from '@rocket.chat/ui-client';
import { useSetModal } from '@rocket.chat/ui-contexts';
import { useState, memo } from 'react';
import { useTranslation } from 'react-i18next';
import { AuthorizationUtils, confirmationRequiredPermissions } from '../../../../../app/authorization/lib';
export type RoleCellProps = {
_id: IRole['_id'];
name: IRole['name'];
description: IRole['description'];
onChange: (roleId: IRole['_id'], granted: boolean) => Promise<boolean>;
permissionId: string;
permissionName: string;
grantedRoles: IRole['_id'][];
};
const RoleCell = ({ _id, name, description, onChange, permissionId, permissionName, grantedRoles = [] }: RoleCellProps) => {
const { t } = useTranslation();
const setModal = useSetModal();
const [granted, setGranted] = useState(() => !!grantedRoles.includes(_id));
const [loading, setLoading] = useState(false);
const isRestrictedForRole = AuthorizationUtils.isPermissionRestrictedForRole(permissionId, _id);
const shouldDisplayConfirmation = confirmationRequiredPermissions.includes(permissionId) && grantedRoles.length === 1 && granted;
const handleChange = useStableCallback(() => {
if (shouldDisplayConfirmation) {
const handleSubmit = () => {
handleConfirmChange();
setModal(null);
};
return setModal(
<GenericModal onConfirm={handleSubmit} onCancel={() => setModal(null)} confirmText={t('Remove')} variant='danger'>
{t('Last_role_in_permission_warning')}
</GenericModal>,
);
}
return handleConfirmChange();
});
const handleConfirmChange = useStableCallback(async () => {
setLoading(true);
const result = await onChange(_id, granted);
setGranted(result);
setLoading(false);
});
const isDisabled = !!loading || !!isRestrictedForRole;
const checkboxLabel = `${permissionName} - ${description || name}`;
return (
<GenericTableCell withTruncatedText>
<Margins inline={2}>
<CheckBox aria-label={checkboxLabel} checked={granted} onChange={handleChange} disabled={isDisabled} />
{!loading && (
<Box display='inline' color='hint' invisible>
{description || name}
</Box>
)}
{loading && <Throbber size='x12' display='inline-block' />}
</Margins>
</GenericTableCell>
);
};
export default memo(RoleCell);

View File

@@ -0,0 +1,33 @@
import type { IRole } from '@rocket.chat/core-typings';
import { Button } from '@rocket.chat/fuselage';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { GenericTableHeaderCell } from '@rocket.chat/ui-client';
import { useRoute } from '@rocket.chat/ui-contexts';
import { memo } from 'react';
export type RoleHeaderProps = {
_id: IRole['_id'];
name: IRole['name'];
description: IRole['description'];
};
const RoleHeader = ({ _id, name, description }: RoleHeaderProps) => {
const router = useRoute('admin-permissions');
const handleEditRole = useStableCallback(() => {
router.push({
context: 'edit',
_id,
});
});
return (
<GenericTableHeaderCell paddingInline={4} padding={8}>
<Button small icon='edit' secondary onClick={handleEditRole}>
{description || name}
</Button>
</GenericTableHeaderCell>
);
};
export default memo(RoleHeader);

View File

@@ -0,0 +1 @@
export { default } from './PermissionsTable';

View File

@@ -0,0 +1,76 @@
import type { SelectOption } from '@rocket.chat/fuselage';
import { Field, FieldLabel, FieldRow, FieldError, FieldHint, TextInput, Select, ToggleSwitch } from '@rocket.chat/fuselage';
import { useMemo } from 'react';
import { useFormContext, Controller } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import type { EditRolePageFormData } from './EditRolePage';
export type RoleFormProps = {
className?: string;
editing?: boolean;
isProtected?: boolean;
isDisabled?: boolean;
};
const RoleForm = ({ className, editing = false, isProtected = false, isDisabled = false }: RoleFormProps) => {
const { t } = useTranslation();
const {
register,
control,
formState: { errors },
} = useFormContext<EditRolePageFormData>();
const options: SelectOption[] = useMemo(
() => [
['Users', t('Global')],
['Subscriptions', t('Rooms')],
],
[t],
);
return (
<>
<Field className={className}>
<FieldLabel>{t('Role')}</FieldLabel>
<FieldRow>
<TextInput
disabled={editing || isDisabled}
placeholder={t('Role')}
{...register('name', { required: t('Required_field', { field: t('Role') }) })}
/>
</FieldRow>
{errors?.name && <FieldError>{errors.name.message}</FieldError>}
</Field>
<Field className={className}>
<FieldLabel>{t('Description')}</FieldLabel>
<FieldRow>
<TextInput placeholder={t('Description')} disabled={isDisabled} {...register('description')} />
</FieldRow>
<FieldHint>{t('Leave_the_description_field_blank_if_you_dont_want_to_show_the_role')}</FieldHint>
</Field>
<Field className={className}>
<FieldLabel>{t('Scope')}</FieldLabel>
<FieldRow>
<Controller
name='scope'
control={control}
render={({ field }) => <Select {...field} options={options} disabled={isProtected || isDisabled} placeholder={t('Scope')} />}
/>
</FieldRow>
</Field>
<Field className={className}>
<FieldRow>
<FieldLabel>{t('Users must use Two Factor Authentication')}</FieldLabel>
<Controller
name='mandatory2fa'
control={control}
render={({ field: { value, ...field } }) => <ToggleSwitch {...field} checked={value} disabled={isDisabled} />}
/>
</FieldRow>
</Field>
</>
);
};
export default RoleForm;

View File

@@ -0,0 +1,175 @@
import type { IRole, IRoom } from '@rocket.chat/core-typings';
import { Box, Field, FieldLabel, FieldRow, Margins, ButtonGroup, Button, Callout, FieldError } from '@rocket.chat/fuselage';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { usePagination, Page, PageHeader, PageContent } from '@rocket.chat/ui-client';
import { useToastMessageDispatch, useEndpoint, useRouter } from '@rocket.chat/ui-contexts';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useId, useMemo } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import UsersInRoleTable from './UsersInRoleTable';
import { useRemoveUserFromRole } from './hooks/useRemoveUserFromRole';
import RoomAutoComplete from '../../../../components/RoomAutoComplete';
import UserAutoCompleteMultiple from '../../../../components/UserAutoCompleteMultiple';
type UsersInRolePayload = {
rid?: IRoom['_id'];
users: string[];
};
export type UsersInRolePageProps = { role: IRole };
const UsersInRolePage = ({ role }: UsersInRolePageProps) => {
const { t } = useTranslation();
const dispatchToastMessage = useToastMessageDispatch();
const queryClient = useQueryClient();
const {
control,
handleSubmit,
formState: { errors, isDirty },
watch,
} = useForm<UsersInRolePayload>({ defaultValues: { users: [] } });
const { _id, name, description } = role;
const router = useRouter();
const addUserToRoleEndpoint = useEndpoint('POST', '/v1/roles.addUserToRole');
const { rid } = watch();
const roomFieldId = useId();
const usersFieldId = useId();
const handleAdd = useStableCallback(async ({ users, rid }: UsersInRolePayload) => {
try {
await Promise.all(
users.map(async (user) => {
if (user) {
await addUserToRoleEndpoint({ roleId: _id, username: user, roomId: rid });
}
}),
);
dispatchToastMessage({ type: 'success', message: t('Users_added') });
queryClient.invalidateQueries({
queryKey: ['getUsersInRole'],
});
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
}
});
const getUsersInRoleEndpoint = useEndpoint('GET', '/v1/roles.getUsersInRole');
const paginationData = usePagination();
const { itemsPerPage, current } = paginationData;
const query = useMemo(
() => ({
role: _id,
...(rid && { roomId: rid }),
...(itemsPerPage && { count: itemsPerPage }),
...(current && { offset: current }),
}),
[itemsPerPage, current, rid, _id],
);
const { data, isLoading, isSuccess, refetch, isError } = useQuery({
queryKey: ['getUsersInRole', _id, query],
queryFn: async () => getUsersInRoleEndpoint(query),
});
const handleRemove = useRemoveUserFromRole({ rid, roleId: _id, roleName: name, roleDescription: description });
return (
<Page>
<PageHeader title={`${t('Users_in_role')} "${description || name}"`}>
<ButtonGroup>
<Button onClick={() => router.navigate(`/admin/permissions/edit/${_id}`)}>{t('Back')}</Button>
</ButtonGroup>
</PageHeader>
<PageContent>
<Box display='flex' flexDirection='column' width='full' marginInline='neg-x4'>
<Margins inline={4}>
{role.scope !== 'Users' && (
<Field marginBlockEnd={4}>
<FieldLabel htmlFor={roomFieldId}>{t('Choose_a_room')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='rid'
rules={{ required: t('Required_field', { field: t('Room') }) }}
render={({ field: { onChange, value } }) => (
<RoomAutoComplete
id={roomFieldId}
aria-required='true'
aria-invalid={Boolean(errors.rid)}
aria-describedby={`${roomFieldId}-error`}
scope='admin'
value={value}
onChange={onChange}
placeholder={t('Room')}
/>
)}
/>
</FieldRow>
{errors.rid && (
<FieldError aria-live='assertive' id={`${roomFieldId}-error`}>
{errors.rid.message}
</FieldError>
)}
</Field>
)}
<Field>
<FieldLabel htmlFor={usersFieldId}>{t('Add_users')}</FieldLabel>
<FieldRow>
<Controller
control={control}
name='users'
rules={{ required: t('Required_field', { field: t('Users') }) }}
render={({ field: { onChange, value } }) => (
<UserAutoCompleteMultiple
id={usersFieldId}
aria-required='true'
aria-invalid={Boolean(errors.users)}
aria-describedby={`${usersFieldId}-error`}
value={value}
placeholder={t('Users')}
onChange={onChange}
/>
)}
/>
<Button marginInlineStart={8} primary onClick={handleSubmit(handleAdd)} disabled={!isDirty}>
{t('Add')}
</Button>
</FieldRow>
{errors.users && (
<FieldRow>
<FieldError aria-live='assertive' id={`${usersFieldId}-error`}>
{errors.users.message}
</FieldError>
</FieldRow>
)}
</Field>
</Margins>
</Box>
<Margins blockStart={8}>
{(role.scope === 'Users' || rid) && (
<UsersInRoleTable
isLoading={isLoading}
isError={isError}
isSuccess={isSuccess}
total={data?.total || 0}
users={data?.users || []}
onRemove={handleRemove}
refetch={refetch}
paginationData={paginationData}
/>
)}
{role.scope !== 'Users' && !rid && <Callout type='info'>{t('Select_a_room')}</Callout>}
</Margins>
</PageContent>
</Page>
);
};
export default UsersInRolePage;

View File

@@ -0,0 +1,17 @@
import { useRouteParameter } from '@rocket.chat/ui-contexts';
import UsersInRolePage from './UsersInRolePage';
import { useRole } from '../hooks/useRole';
const UsersInRolePageWithData = () => {
const _id = useRouteParameter('_id');
const role = useRole(_id);
if (!role) {
return null;
}
return <UsersInRolePage role={role} />;
};
export default UsersInRolePageWithData;

View File

@@ -0,0 +1,21 @@
import { mockAppRoot } from '@rocket.chat/mock-providers';
import { composeStories } from '@storybook/react';
import { render } from '@testing-library/react';
import { axe } from 'jest-axe';
import * as stories from './UsersInRoleTable.stories';
const testCases = Object.values(composeStories(stories)).map((Story) => [Story.storyName || 'Story', Story]);
test.each(testCases)(`renders %s without crashing`, async (_storyname, Story) => {
const { baseElement } = render(<Story />, { wrapper: mockAppRoot().build() });
expect(baseElement).toMatchSnapshot();
});
test.each(testCases)('%s should have no a11y violations', async (_storyname, Story) => {
const { container } = render(<Story />, { wrapper: mockAppRoot().build() });
// TODO: Needed to skip `button-name` because fuselage‘s `Pagination` buttons are missing names
const results = await axe(container, { rules: { 'button-name': { enabled: false } } });
expect(results).toHaveNoViolations();
});

View File

@@ -0,0 +1,86 @@
import { Margins } from '@rocket.chat/fuselage';
import { PageContent } from '@rocket.chat/ui-client';
import type { Meta } from '@storybook/react';
import UsersInRoleTable from './UsersInRoleTable';
import { createMockedPagination } from '../../../../../../tests/mocks/data';
export default {
component: UsersInRoleTable,
decorators: [
(fn) => (
<PageContent marginBlock='neg-x8'>
<Margins block={8}>{fn()}</Margins>
</PageContent>
),
],
} satisfies Meta<typeof UsersInRoleTable>;
const generateMockedUsers = (count: number) =>
Array.from({ length: count }, (_, i) => ({
_id: `${i + 1}`,
username: `user.${i + 1}`,
name: `User ${i + 1}`,
emails: [{ address: `user${i + 1}@example.com`, verified: i % 2 === 0 }],
createdAt: new Date().toISOString(),
_updatedAt: new Date().toISOString(),
roles: [i < 5 ? 'admin' : 'user'],
type: 'user',
active: true,
}));
const mockedUsers = generateMockedUsers(5);
const paginationData = createMockedPagination(mockedUsers.length, 30);
export const Default = {
args: {
total: 30,
isLoading: false,
isError: false,
isSuccess: true,
users: mockedUsers,
onRemove: () => undefined,
refetch: () => undefined,
paginationData,
},
};
export const withLoading = {
args: {
total: 0,
isLoading: true,
isError: false,
isSuccess: false,
users: [],
onRemove: () => undefined,
refetch: () => undefined,
paginationData,
},
};
export const withNoResults = {
args: {
total: 0,
isLoading: false,
isError: false,
isSuccess: true,
users: [],
onRemove: () => undefined,
refetch: () => undefined,
paginationData,
},
};
export const withError = {
args: {
total: 0,
isLoading: false,
isError: true,
isSuccess: false,
users: [],
onRemove: () => undefined,
refetch: () => undefined,
paginationData,
},
};

View File

@@ -0,0 +1,77 @@
import type { IUserInRole, Serialized } from '@rocket.chat/core-typings';
import { Pagination } from '@rocket.chat/fuselage';
import {
GenericTable,
GenericTableHeader,
GenericTableHeaderCell,
GenericTableBody,
GenericTableLoadingTable,
} from '@rocket.chat/ui-client';
import type { usePagination } from '@rocket.chat/ui-client';
import { useTranslation } from 'react-i18next';
import UsersInRoleTableRow from './UsersInRoleTableRow';
import GenericError from '../../../../../components/GenericError';
import GenericNoResults from '../../../../../components/GenericNoResults';
export type UsersInRoleTableProps = {
isLoading: boolean;
isError: boolean;
isSuccess: boolean;
total: number;
users: Serialized<IUserInRole>[];
onRemove: (username: IUserInRole['username']) => void;
paginationData: ReturnType<typeof usePagination>;
refetch: () => void;
};
const UsersInRoleTable = ({ isLoading, isSuccess, isError, total, users, onRemove, refetch, paginationData }: UsersInRoleTableProps) => {
const { t } = useTranslation();
const { current, itemsPerPage, setCurrent, setItemsPerPage, ...paginationProps } = paginationData;
const headers = (
<>
<GenericTableHeaderCell>{t('Name')}</GenericTableHeaderCell>
<GenericTableHeaderCell>{t('Email')}</GenericTableHeaderCell>
<GenericTableHeaderCell width='x80'>{t('Actions')}</GenericTableHeaderCell>
</>
);
return (
<>
{isLoading && (
<GenericTable>
<GenericTableHeader>{headers}</GenericTableHeader>
<GenericTableBody>
<GenericTableLoadingTable headerCells={3} />
</GenericTableBody>
</GenericTable>
)}
{isSuccess && users?.length > 0 && (
<>
<GenericTable>
<GenericTableHeader>{headers}</GenericTableHeader>
<GenericTableBody>
{users.map((user) => (
<UsersInRoleTableRow key={user?._id} user={user} onRemove={onRemove} />
))}
</GenericTableBody>
</GenericTable>
<Pagination
divider
current={current}
itemsPerPage={itemsPerPage}
count={total}
onSetItemsPerPage={setItemsPerPage}
onSetCurrent={setCurrent}
{...paginationProps}
/>
</>
)}
{isSuccess && users?.length === 0 && <GenericNoResults />}
{isError && <GenericError buttonAction={refetch} />}
</>
);
};
export default UsersInRoleTable;

View File

@@ -0,0 +1,50 @@
import type { IUserInRole, Serialized } from '@rocket.chat/core-typings';
import { Box, IconButton } from '@rocket.chat/fuselage';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { UserAvatar } from '@rocket.chat/ui-avatar';
import { GenericTableRow, GenericTableCell } from '@rocket.chat/ui-client';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { getUserEmailAddress } from '../../../../../../lib/getUserEmailAddress';
export type UsersInRoleTableRowProps = {
user: Serialized<IUserInRole>;
onRemove: (username: IUserInRole['username']) => void;
};
const UsersInRoleTableRow = ({ user, onRemove }: UsersInRoleTableRowProps) => {
const { t } = useTranslation();
const { _id, name, username, avatarETag } = user;
const email = getUserEmailAddress(user);
const handleRemove = useStableCallback(() => {
onRemove(username);
});
return (
<GenericTableRow key={_id} tabIndex={0} role='link'>
<GenericTableCell withTruncatedText>
<Box display='flex' alignItems='center'>
<UserAvatar size='x40' username={username ?? ''} etag={avatarETag} />
<Box display='flex' withTruncatedText marginInline={8}>
<Box fontScale='p2m' withTruncatedText color='default'>
{name || username}
</Box>
{name && (
<Box marginInlineStart={4} fontScale='p2' color='hint' withTruncatedText>
{`@${username}`}
</Box>
)}
</Box>
</Box>
</GenericTableCell>
<GenericTableCell withTruncatedText>{email}</GenericTableCell>
<GenericTableCell>
<IconButton small icon='trash' title={t('Remove')} danger onClick={handleRemove} />
</GenericTableCell>
</GenericTableRow>
);
};
export default memo(UsersInRoleTableRow);

View File

@@ -0,0 +1 @@
export { default } from './UsersInRoleTable';

View File

@@ -0,0 +1,52 @@
import type { IRole, IRoom, IUserInRole } from '@rocket.chat/core-typings';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { GenericModal } from '@rocket.chat/ui-client';
import { useSetModal, useToastMessageDispatch, useEndpoint } from '@rocket.chat/ui-contexts';
import { useQueryClient } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
export const useRemoveUserFromRole = ({
rid,
roleId,
roleName,
roleDescription,
}: {
rid?: IRoom['_id'];
roleId: IRole['_id'];
roleName: IRole['name'];
roleDescription: IRole['description'];
}) => {
const { t } = useTranslation();
const setModal = useSetModal();
const dispatchToastMessage = useToastMessageDispatch();
const queryClient = useQueryClient();
const removeUserFromRoleEndpoint = useEndpoint('POST', '/v1/roles.removeUserFromRole');
const handleRemove = useStableCallback((username: IUserInRole['username']) => {
const remove = async () => {
try {
if (!username) throw new Error('Username is required');
await removeUserFromRoleEndpoint({ roleId, username, scope: rid });
dispatchToastMessage({ type: 'success', message: t('User_removed') });
queryClient.invalidateQueries({
queryKey: ['getUsersInRole'],
});
} catch (error) {
dispatchToastMessage({ type: 'error', message: error });
} finally {
setModal(null);
}
};
setModal(
<GenericModal variant='danger' onConfirm={remove} onCancel={() => setModal(null)} confirmText={t('Delete')}>
{t('The_user_s_will_be_removed_from_role_s', { username, role: roleDescription || roleName })}
</GenericModal>,
);
});
return handleRemove;
};

View File

@@ -0,0 +1 @@
export { default } from './UsersInRolePageWithData';

View File

@@ -0,0 +1,89 @@
import { filterPermissionKeys, mapPermissionKeys } from './mapPermissionKeys';
describe('mapPermissionKeys', () => {
it('should return an empty array if there are no permissions', () => {
const t: any = (string: string) => string;
const result = mapPermissionKeys({ t, permissions: [] });
expect(result).toEqual([]);
});
it('should map the permissions and return an array of objects with _id and i18nLabels', () => {
const t: any = (string: string) => string;
const result = mapPermissionKeys({
t,
permissions: [
{
_id: 'delete-team',
roles: ['admin'],
_updatedAt: new Date(),
},
{
_id: 'delete-user',
roles: ['admin'],
_updatedAt: new Date(),
},
{
_id: 'delete-channel',
roles: ['admin'],
_updatedAt: new Date(),
},
],
});
expect(result).toEqual([
{
_id: 'delete-team',
i18nLabels: ['delete-team'],
},
{
_id: 'delete-user',
i18nLabels: ['delete-user'],
},
{
_id: 'delete-channel',
i18nLabels: ['delete-channel'],
},
]);
});
});
describe('filterPermissionKeys', () => {
it('should return an empty array if there are no permissions', () => {
const result = filterPermissionKeys([], '');
expect(result).toEqual([]);
});
it('should filter the permissions and return an array ids that match with the filter text', () => {
const result = filterPermissionKeys(permissionKeys, 'delete');
expect(result).toEqual(['delete-team', 'delete-user', 'delete-channel']);
});
it('should match case insensitive and in any order', () => {
const result = filterPermissionKeys(permissionKeys, 'team DELETE');
expect(result).toEqual(['delete-team']);
});
it('should return an empty array if there are no matches with the filter text', () => {
const result = filterPermissionKeys(permissionKeys, 'mailer');
expect(result).toEqual([]);
});
});
const permissionKeys = [
{
_id: 'delete-team',
i18nLabels: ['delete-team', 'Delete team'],
},
{
_id: 'delete-user',
i18nLabels: ['delete-user', 'Delete user'],
},
{
_id: 'delete-channel',
i18nLabels: ['delete-channel', 'Delete channel'],
},
];

View File

@@ -0,0 +1,22 @@
import type { IPermission } from '@rocket.chat/core-typings';
import { escapeRegExp } from '@rocket.chat/tools';
import type { TFunction } from 'i18next';
export const mapPermissionKeys = ({ t, permissions }: { t: TFunction; permissions: IPermission[] }) =>
permissions.map(({ _id, settingId, group, section }) => ({
_id,
i18nLabels: [group && t(group), section && t(section), settingId && t(settingId), t(_id)].filter(Boolean) as string[],
}));
export const filterPermissionKeys = (permissionKeys: { _id: string; i18nLabels: string[] }[], filter: string): string[] => {
const words = escapeRegExp(filter).split(' ').filter(Boolean);
return permissionKeys
.filter(({ _id, i18nLabels }) =>
words.every(
(word) =>
_id.toLocaleLowerCase().includes(word.toLocaleLowerCase()) ||
i18nLabels.join(' ').toLocaleLowerCase().includes(word.toLocaleLowerCase()),
),
)
.map(({ _id }) => _id);
};

View File

@@ -0,0 +1,29 @@
import type { IRole, IPermission } from '@rocket.chat/core-typings';
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
import { useToastMessageDispatch } from '@rocket.chat/ui-contexts';
export const useChangeRole = ({
onGrant,
onRemove,
permissionId,
}: {
onGrant: (permissionId: IPermission['_id'], roleId: IRole['_id']) => Promise<void>;
onRemove: (permissionId: IPermission['_id'], roleId: IRole['_id']) => Promise<void>;
permissionId: IPermission['_id'];
}): ((roleId: IRole['_id'], granted: boolean) => Promise<boolean>) => {
const dispatchToastMessage = useToastMessageDispatch();
return useStableCallback(async (roleId: IRole['_id'], granted: boolean) => {
try {
if (granted) {
await onRemove(permissionId, roleId);
} else {
await onGrant(permissionId, roleId);
}
return !granted;
} catch (error: unknown) {
dispatchToastMessage({ type: 'error', message: error });
}
return granted;
});
};

View File

@@ -0,0 +1,21 @@
import { useDebouncedValue } from '@rocket.chat/fuselage-hooks';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Permissions } from '../../../../stores';
import { filterPermissionKeys, mapPermissionKeys } from '../helpers/mapPermissionKeys';
export const useFilteredPermissions = ({ filter }: { filter: string }) => {
const { t } = useTranslation();
const mappedPermissionKeys = useMemo(() => {
const permissions = Array.from(Permissions.state.records.values());
return mapPermissionKeys({ t, permissions });
}, [t]);
const debouncedFilter = useDebouncedValue(filter, 400);
return useMemo(() => {
return filterPermissionKeys(mappedPermissionKeys, debouncedFilter);
}, [debouncedFilter, mappedPermissionKeys]);
};

View File

@@ -0,0 +1,35 @@
import type { IRole, IPermission } from '@rocket.chat/core-typings';
import { useCallback } from 'react';
import { useShallow } from 'zustand/shallow';
import { useFilteredPermissions } from './useFilteredPermissions';
import { CONSTANTS } from '../../../../../app/authorization/lib';
import { pipe } from '../../../../lib/cachedStores/pipe';
import { Permissions, Roles } from '../../../../stores';
export const usePermissionsAndRoles = (
type = 'permissions',
filter = '',
limit = 25,
skip = 0,
): { permissions: IPermission[]; total: number; roleList: IRole[] } => {
const filteredIds = useFilteredPermissions({ filter });
const predicate = useCallback(
(record: IPermission): boolean => {
if (type === 'permissions') {
return record.level !== CONSTANTS.SETTINGS_LEVEL && filteredIds.includes(record._id);
}
return record.level === CONSTANTS.SETTINGS_LEVEL && filteredIds.includes(record._id);
},
[filteredIds, type],
);
const { apply: transform } = pipe<IPermission>().sortByField('_id', 1).slice(skip, limit);
const permissions = Permissions.use(useShallow((state) => transform(state.filter(predicate))));
const permissionsTotal = Permissions.use(useShallow((state) => state.count(predicate)));
const roleList = Roles.use(useShallow((state) => Array.from(state.records.values())));
return { permissions, total: permissionsTotal, roleList };
};

View File

@@ -0,0 +1,5 @@
import type { IRole } from '@rocket.chat/core-typings';
import { Roles } from '../../../../stores';
export const useRole = (_id?: IRole['_id']) => Roles.use((state) => (_id ? state.get(_id) : undefined));