diff --git a/packages/sanity/src/core/util/index.ts b/packages/sanity/src/core/util/index.ts index 87a39606ab7..1f8cbb2f127 100644 --- a/packages/sanity/src/core/util/index.ts +++ b/packages/sanity/src/core/util/index.ts @@ -15,3 +15,4 @@ export * from './uncaughtErrorHandler' export * from './useLoadable' export * from './useThrottledCallback' export * from './useUnique' +export * from './userHasRole' diff --git a/packages/sanity/src/core/util/userHasRole.test.ts b/packages/sanity/src/core/util/userHasRole.test.ts new file mode 100644 index 00000000000..208ffca591c --- /dev/null +++ b/packages/sanity/src/core/util/userHasRole.test.ts @@ -0,0 +1,45 @@ +import type {CurrentUser} from '@sanity/types' +import {userHasRole} from './userHasRole' + +const roleLessUser: CurrentUser = { + id: 'pabc123', + email: 'some@user.com', + name: 'Some User', + role: '', + roles: [], +} + +const adminUser: CurrentUser = { + ...roleLessUser, + role: 'administrator', // Legacy + roles: [{name: 'administrator', title: 'Administrator'}], +} + +const multiRoleUser: CurrentUser = { + ...adminUser, + role: 'editor', // Legacy + roles: [ + {name: 'translator', title: 'Translator'}, + {name: 'editor', title: 'Editor'}, + ], +} + +test('userHasRole(): no roles', () => { + expect(userHasRole(roleLessUser, 'administrator')).toBe(false) +}) + +test('userHasRole(): no match', () => { + expect(userHasRole(adminUser, 'dogwalker')).toBe(false) +}) + +test('userHasRole(): match (single role)', () => { + expect(userHasRole(adminUser, 'administrator')).toBe(true) +}) + +test('userHasRole(): match (multiple roles)', () => { + expect(userHasRole(multiRoleUser, 'editor')).toBe(true) +}) + +test('userHasRole(): no match (multiple roles)', () => { + expect(userHasRole(multiRoleUser, 'administrator')).toBe(false) +}) diff --git a/packages/sanity/src/core/util/userHasRole.ts b/packages/sanity/src/core/util/userHasRole.ts new file mode 100644 index 00000000000..516933e58e7 --- /dev/null +++ b/packages/sanity/src/core/util/userHasRole.ts @@ -0,0 +1,24 @@ +import type {CurrentUser} from '@sanity/types' + +/** + * Checks whether or not the given user has the role with the given ID + * + * @param user - The user to check (currently only the current user is supported) + * @param roleId - The ID of the role to check for + * @returns True if the user has the role, false otherwise + * @example + * Fetch the current user and check if they have the role "administrator": + * ``` + * import {userHasRole, useCurrentUser} from 'sanity' + * + * export function MyComponent() { + * const user = useCurrentUser() + * const hasAdminRole = userHasRole(user, 'administrator') + * return
Is administrator: {hasAdminRole ? 'Yes' : 'No'}
+ * } + * ``` + * @public + */ +export function userHasRole(user: CurrentUser, roleId: string): boolean { + return user.roles.some((role) => role.name === roleId) +}