Permission Control
Univer provides permission control capabilities, typically used to restrict user operations on workbooks, sheets, and ranges. When a user performs an operation without permission, the code execution can be halted and the user will be prompted about the missing permissions. For example, you can set area protection within a range, which allows setting whether other collaborators can edit, read, copy, filter, etc., within the protected range.
Precautions before use
Univer provides extendable foundational capabilities, not customized features. If you have more extensive and tailored requirements such as persistence or organizational structures, you need to implement the storage of permission rules and integrate organizational structures yourself. In this case, you need to write custom plugins to achieve this. Therefore, after setting permissions, you might find the permission list empty when viewing it, or user information returns empty when you check it. This is because this information needs to be fetched via API requests; it's custom logic that requires additional implementation on your part. You can refer to the third-party integration below.
Core Concepts
- Scope of Action: Permissions can be applied at three levels: workbook, worksheet, and range.
- Permission Points: Each function corresponds to a permission point, and modifying the point can control whether the function is available.
- Protection Rules: Before setting permission points for worksheets and ranges, you need to create protection rules
Permission Point Explanation
Local non-persistent (non-collaborative editing environment) permission control can be directly achieved by modifying the permission points. For persistent permissions, please refer to the "Integration of Third-Party Authorization Service" section below. In a collaborative editing scenario, updating permission points will synchronize the server state:
- false: This permission point requires at least the
ownerrole - true: This permission point requires at least the
readerrole
Basic Example
The most common permission setting methods are shown below at three levels: workbook, worksheet, and range.
Workbook Permissions Code Example
Currently, workbook-level permissions are directly modified through the API. We provide the Facade API, and you can use this API to set permissions for different functions of the workbook.
Taking edit permission as an example (other functions require replacing the permission points, see the list of permission points - Workbook for details), you can use the following code to set the entire workbook to be non-editable:
const fWorkbook = univerAPI.getActiveWorkbook()
const workbookPermission = fWorkbook.getWorkbookPermission()
// Set the workbook to be non-editable
await workbookPermission.setPoint(univerAPI.Enum.WorkbookPermissionPoint.Edit, false)Key points:
- Workbook permissions points can be directly set without the need to create protection rules.
Worksheet Permissions Code Example
Worksheet and range-related permissions can be set via both the Facade API and command. Here, we'll use worksheet edit permissions as an example. Other worksheet functions require replacing the permission points, see the list of permission points - Worksheet for details.
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const worksheetPermission = fWorksheet.getWorksheetPermission()
// Create worksheet protection, allow specified users to edit
const permissionId = await worksheetPermission.protect({
allowedUsers: ['user1', 'user2'],
name: 'My Worksheet Protection',
})
// If you need to set permission points, you must first create worksheet protection
await worksheetPermission.setPoint(univerAPI.Enum.WorksheetPermissionPoint.Edit, false)Delete Worksheet Permissions
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const worksheetPermission = fWorksheet.getWorksheetPermission()
// Remove worksheet protection
await worksheetPermission.unprotect()Custom Range Permissions Code Example
Range permissions can also be set via API and command modes. Here, we'll use range edit permissions as an example. Other range functions require replacing the permission points, see the list of permission points - Range for details.
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const fRange = fWorksheet.getRange('A1:B2')
const rangePermission = fRange.getRangePermission()
// Set range protection permission, allow specified users to edit but not allow others to view
const rule = await rangePermission.protect({
name: 'My protected range',
allowViewByOthers: false,
allowedUsers: ['user1', 'user2'],
})
console.log(rule)
// If you need to set permission points, you must first create range protection.
await rule.setPoint(univerAPI.Enum.RangePermissionPoint.Edit, false)
await rule.setPoint(univerAPI.Enum.RangePermissionPoint.View, true)Delete Range Protection Permissions
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const fRange = fWorksheet.getRange('A1:B2')
const rangePermission = fRange.getRangePermission()
// delete all rules within the range
await rangePermission.unprotect()
// Or delete specific rules within the range
const rules = await rangePermission.listRules()
if (rules.length > 0) {
await rules[0].remove()
}Extended usage
When you need to add permission verification in your own plug-in, you can directly manipulate the permission points.
Here we take WorkbookEditablePermission as an example and add permission verification in your own plug-in. Other points are similar.
import { IPermissionService } from '@univerjs/core'
import { WorkbookEditablePermission } from '@univerjs/sheets'
class YourService {
constructor(@IPermissionService private _permissionService: IPermissionService) {
}
setWorkbookNotEditable() {
this._permissionService.updatePermissionPoint(new WorkbookEditablePermission('unitId').id, false)
}
setWorkbookEditable() {
this._permissionService.updatePermissionPoint(new WorkbookEditablePermission('unitId').id, true)
}
}You can also extend and modify other permission points to achieve permission control for different functions. For a specific list of points, please refer to the bottom of the article.
How to extend the permission point
If you need to customize permission points, you can implement IPermissionPoint and register it to the permission service:
import type { IPermissionPoint } from '@univerjs/core'
import { IPermissionService, PermissionStatus } from '@univerjs/core'
import { UnitAction, UnitObject } from '@univerjs/protocol'
export class CustomPermissionPoint implements IPermissionPoint {
type = UnitObject.Unkonwn // your type
subType = UnitAction.View // your subType
status = PermissionStatus.INIT
value = true // Initial values
id: string
constructor(unitId: string, subUnitId: string, customId: string) {
// The id attribute needs to be guaranteed to be unique throughout `IPermissionService`.
this.id = `${unitId}.${subUnitId}.${customId}`
}
}
class YourService {
constructor(@IPermissionService private _permissionService: IPermissionService) {
this._init()
}
_init() {
this._permissionService.addPermissionPoint(new CustomPermissionPoint('unitId', 'subUnitId', 'my-id'))
}
}
// How to use it elsewhere
class ConsumeService {
constructor(@IPermissionService private _permissionService: IPermissionService) {
}
doSomething() {
const point = this._permissionService.getPermissionPoint(new CustomPermissionPoint('unitId', 'subUnitId', 'my-id').id)
console.log(point.value)
}
bindEvent() {
// This will get an RX object, allowing you to listen for changes to the current permissions and make a list of changes
const pount$ = this._permissionService.getPermissionPoint$(new CustomPermissionPoint('unitId', 'subUnitId', 'my-id').id)
console.log(pount$)
}
}Integration of Third-Party Authorization Service(Advanced Usage)
Caution
It is recommended to avoid mixing custom permission access with the Permission Facade API, as it allows for more granular control over permission points.
The logic for determining permissions is typically handled by an external service, which involves a communication process. In the frontend SDK implementation, we use the AuthzIoLocalService to handle this logic.
In a production environment, we need to replace this implementation with a backend service. The frontend needs to implement the corresponding request functions based on the IAuthzIoService interface for runtime replacement.

Here is a simple example demonstrating the addition and deletion of protected range permissions for two predefined roles (Owner/Reader). The Owner has editing/viewing permissions for protected ranges, while the Reader cannot edit or view the contents of cells within protected ranges.
import type { Injector } from '@univerjs/core'
import type { IActionInfo, IAllowedRequest, IBatchAllowedResponse, ICollaborator, ICreateRequest, ICreateRequest_SelectRangeObject, IListPermPointRequest, IPermissionPoint, IPutCollaboratorsRequest, IUnitRoleKV, IUpdatePermPointRequest } from '@univerjs/protocol'
import { createDefaultUser, generateRandomId, IAuthzIoService, Inject, IResourceManagerService, isDevRole, Univer, UserManagerService } from '@univerjs/core'
import { ObjectScope, UnitAction, UnitObject, UnitRole, UniverType } from '@univerjs/protocol'
class YourAuthzService implements IAuthzIoService {
private _permissionMap: Map<string, ICreateRequest_SelectRangeObject & { objectType: UnitObject }> = new Map([])
constructor(
@IResourceManagerService private _resourceManagerService: IResourceManagerService,
@Inject(UserManagerService) private _userManagerService: UserManagerService,
) {
this._initSnapshot()
this._initDefaultUser()
}
private _initDefaultUser() {
const currentUser = this._userManagerService.getCurrentUser()
const currentUserIsValid = currentUser && currentUser.userID
if (!currentUserIsValid) {
this._userManagerService.setCurrentUser(createDefaultUser(UnitRole.Owner))
}
}
private _getRole(type: UnitRole) {
const user = this._userManagerService.getCurrentUser()
if (!user) {
return false
}
return isDevRole(user.userID, type)
}
private _initSnapshot() {
this._resourceManagerService.registerPluginResource({
toJson: (_unitId: string) => {
const obj = [...this._permissionMap.keys()].reduce((r, k) => {
const v = this._permissionMap.get(k)
r[k] = v!
return r
}, {} as Record<string, ICreateRequest_SelectRangeObject & { objectType: UnitObject }>)
return JSON.stringify(obj)
},
parseJson: (json: string) => {
return JSON.parse(json)
},
pluginName: 'SHEET_AuthzIoMockService_PLUGIN',
businesses: [UniverType.UNIVER_SHEET, UniverType.UNIVER_DOC, UniverType.UNIVER_SLIDE],
onLoad: (_unitId, resource) => {
for (const key in resource) {
this._permissionMap.set(key, resource[key])
}
},
onUnLoad: () => {
this._permissionMap.clear()
},
})
}
async create(config: ICreateRequest): Promise<string> {
const permissionId = generateRandomId(8)
if (config.objectType === UnitObject.SelectRange && config.selectRangeObject) {
this._permissionMap.set(permissionId, { ...config.selectRangeObject, objectType: config.objectType })
}
return permissionId
}
async batchAllowed(config: IAllowedRequest[]): Promise<IBatchAllowedResponse['objectActions']> {
const selectionRangeConfig = config.filter(c => c.objectType === UnitObject.SelectRange)
if (selectionRangeConfig.length) {
const currentUser = this._userManagerService.getCurrentUser()
const res = [] as IBatchAllowedResponse['objectActions']
selectionRangeConfig.forEach((c) => {
res.push({
unitID: c.unitID,
objectID: c.objectID,
actions: c.actions.map((action) => {
if (isDevRole(currentUser.userID, UnitRole.Owner)) {
return { action, allowed: true }
}
return { action, allowed: false }
}),
})
})
return res
}
return Promise.resolve([])
}
async list(config: IListPermPointRequest): Promise <IPermissionPoint[]> {
const result: IPermissionPoint[] = []
config.objectIDs.forEach((objectID) => {
const rule = this._permissionMap.get(objectID)
if (rule) {
const item = {
objectID,
unitID: config.unitID,
objectType: rule!.objectType,
name: rule!.name,
shareOn: false,
shareRole: UnitRole.Owner,
shareScope: -1,
scope: {
read: ObjectScope.AllCollaborator,
edit: ObjectScope.AllCollaborator,
},
creator: createDefaultUser(UnitRole.Owner),
strategies: [
{
action: UnitAction.View,
role: UnitRole.Owner,
},
{
action: UnitAction.Edit,
role: UnitRole.Owner,
},
],
actions: config.actions.map((a) => {
return { action: a, allowed: this._getRole(UnitRole.Owner) }
}),
}
result.push(item)
}
})
return result
}
async listCollaborators(): Promise<ICollaborator[]> {
// List the existing collaborators
return []
}
async allowed(_config: IAllowedRequest): Promise<IActionInfo[]> {
// Because this is a mockService for handling permissions, we will not write real logic in it. We will only return an empty array to ensure that the permissions originally set by the user are not modified.
// If you want to achieve persistence of permissions, you can modify the logic here.
return Promise.resolve([])
}
async listRoles(): Promise<{ roles: IUnitRoleKV[], actions: UnitAction[] }> {
return {
roles: [],
actions: [],
}
}
async update(config: IUpdatePermPointRequest): Promise<void> {
// Update bit information
}
async updateCollaborator(): Promise<void> {
// Update collaborator information
return undefined
}
async createCollaborator(): Promise<void> {
// Create new collaborator information
return undefined
}
async deleteCollaborator(): Promise<void> {
return undefined
}
async putCollaborators(config: IPutCollaboratorsRequest): Promise<void> {
return undefined
}
}
export class YourPlugin extends Plugin {
constructor(
_config: unknown,
@Inject(Injector) protected override _injector: Injector,
) {
}
override onStarting(): void {
this._injector.add([IAuthzIoService, { useClass: YourAuthzService }])
}
}
// By setting the override option to [[IAuthzIoService, null]], you can instruct Univer not to register the built-in IAuthzIoService.
// This way, Univer will use the service provided by YourAuthzService as the implementation of the authorization service.
const univer = new Univer({
override: [[IAuthzIoService, null]],
})
univer.registerPlugin(YourPlugin)List of permission points
To access the specific code related to permission point at the given URL, you can refer to the code.
In the case where the permission control of the workbook intersects with the worksheet/range, all permissions must be set to true in order to use them.
Workbook Permissions
| API Enum | Corresponding Permission Point Class | Description |
|---|---|---|
| univerAPI.Enum.WorkbookPermissionPoint.Edit | WorkbookEditablePermission | Can edit |
| univerAPI.Enum.WorkbookPermissionPoint.View | WorkbookViewPermission | Can view |
| univerAPI.Enum.WorkbookPermissionPoint.Print | WorkbookPrintPermission | Can print |
| univerAPI.Enum.WorkbookPermissionPoint.Export | WorkbookExportPermission | Can export |
| univerAPI.Enum.WorkbookPermissionPoint.Share | WorkbookSharePermission | Can share |
| univerAPI.Enum.WorkbookPermissionPoint.CopyContent | WorkbookCopyPermission | Can copy |
| univerAPI.Enum.WorkbookPermissionPoint.DuplicateFile | WorkbookDuplicatePermission | Can duplicate |
| univerAPI.Enum.WorkbookPermissionPoint.Comment | WorkbookCommentPermission | Can comment |
| univerAPI.Enum.WorkbookPermissionPoint.ManageCollaborator | WorkbookManageCollaboratorPermission | Can manage collaborators |
| univerAPI.Enum.WorkbookPermissionPoint.CreateSheet | WorkbookCreateSheetPermission | Can create worksheets |
| univerAPI.Enum.WorkbookPermissionPoint.DeleteSheet | WorkbookDeleteSheetPermission | Can delete worksheets |
| univerAPI.Enum.WorkbookPermissionPoint.RenameSheet | WorkbookRenameSheetPermission | Can rename worksheets |
| univerAPI.Enum.WorkbookPermissionPoint.MoveSheet | WorkbookMoveSheetPermission | Can move worksheets |
| univerAPI.Enum.WorkbookPermissionPoint.HideSheet | WorkbookHideSheetPermission | Can hide worksheets |
| univerAPI.Enum.WorkbookPermissionPoint.CopySheet | WorkbookCopySheetPermission | Can copy worksheets |
| univerAPI.Enum.WorkbookPermissionPoint.ViewHistory | WorkbookViewHistoryPermission | Can view history |
| univerAPI.Enum.WorkbookPermissionPoint.RecoverHistory | WorkbookRecoverHistoryPermission | Can recover history |
| univerAPI.Enum.WorkbookPermissionPoint.CreateProtection | WorkbookCreateProtectPermission | Can create protection |
| univerAPI.Enum.WorkbookPermissionPoint.InsertRow | WorkbookInsertRowPermission | Can insert rows |
| univerAPI.Enum.WorkbookPermissionPoint.InsertColumn | WorkbookInsertColumnPermission | Can insert columns |
| univerAPI.Enum.WorkbookPermissionPoint.DeleteRow | WorkbookDeleteRowPermission | Can delete rows |
| univerAPI.Enum.WorkbookPermissionPoint.DeleteColumn | WorkbookDeleteColumnPermission | Can delete columns |
Worksheet Permissions
| API Enum | Corresponding Permission Point Class | Description |
|---|---|---|
| univerAPI.Enum.WorksheetPermissionPoint.Edit | WorksheetEditPermission | Can edit |
| univerAPI.Enum.WorksheetPermissionPoint.View | WorksheetViewPermission | Can view |
| univerAPI.Enum.WorksheetPermissionPoint.Copy | WorksheetCopyPermission | Can copy |
| univerAPI.Enum.WorksheetPermissionPoint.SetCellValue | WorksheetSetCellValuePermission | Can edit cell values |
| univerAPI.Enum.WorksheetPermissionPoint.SetCellStyle | WorksheetSetCellStylePermission | Can edit cell styles |
| univerAPI.Enum.WorksheetPermissionPoint.SetRowStyle | WorksheetSetRowStylePermission | Can set row styles |
| univerAPI.Enum.WorksheetPermissionPoint.SetColumnStyle | WorksheetSetColumnStylePermission | Can set column styles |
| univerAPI.Enum.WorksheetPermissionPoint.InsertRow | WorksheetInsertRowPermission | Can insert rows |
| univerAPI.Enum.WorksheetPermissionPoint.InsertColumn | WorksheetInsertColumnPermission | Can insert columns |
| univerAPI.Enum.WorksheetPermissionPoint.DeleteRow | WorksheetDeleteRowPermission | Can delete rows |
| univerAPI.Enum.WorksheetPermissionPoint.DeleteColumn | WorksheetDeleteColumnPermission | Can delete columns |
| univerAPI.Enum.WorksheetPermissionPoint.Sort | WorksheetSortPermission | Can sort |
| univerAPI.Enum.WorksheetPermissionPoint.Filter | WorksheetFilterPermission | Can filter |
| univerAPI.Enum.WorksheetPermissionPoint.PivotTable | WorksheetPivotTablePermission | Can use pivot tables |
| univerAPI.Enum.WorksheetPermissionPoint.InsertHyperlink | WorksheetInsertHyperlinkPermission | Can use hyperlinks |
| univerAPI.Enum.WorksheetPermissionPoint.ManageCollaborator | WorksheetManageCollaboratorPermission | Can manage collaborators |
| univerAPI.Enum.WorksheetPermissionPoint.DeleteProtection | WorksheetDeleteProtectionPermission | Can delete protection |
Range Protection
| API Enum | Corresponding Permission Point Class | Description |
|---|---|---|
| univerAPI.Enum.RangePermissionPoint.Edit | RangeProtectionPermissionEditPoint | Can edit protected ranges |
| univerAPI.Enum.RangePermissionPoint.View | RangeProtectionPermissionViewPoint | Can view content of protected ranges |
| univerAPI.Enum.RangePermissionPoint.Delete | RangeProtectionPermissionDeleteProtectionPoint | Can delete protected ranges |
Configuration
Protection Range Shadow Strategy
The permission background shadow is displayed by default. You can hide it using the following code:
createUniver({
presets: [
UniverSheetsCorePreset({
sheets: {
/**
* Strategy for showing the protected range shadow.
* - true or 'always': Show shadow for all protected ranges (default behavior)
* - 'non-editable': Only show shadow for ranges that cannot be edited (Edit permission is false)
* - 'non-viewable': Only show shadow for ranges that cannot be viewed (View permission is false)
* - false or 'none': Never show shadow for protected ranges
* @default true
*/
protectedRangeShadow: false,
},
}),
],
})univer.registerPlugin(UniverSheetsUIPlugin, {
/**
* Strategy for showing the protected range shadow.
* - true or 'always': Show shadow for all protected ranges (default behavior)
* - 'non-editable': Only show shadow for ranges that cannot be edited (Edit permission is false)
* - 'non-viewable': Only show shadow for ranges that cannot be viewed (View permission is false)
* - false or 'none': Never show shadow for protected ranges
* @default true
*/
protectedRangeShadow: false,
})Also can be modified dynamically through the API:
// Set to only show shadows for non-editable ranges
univerAPI.setProtectedRangeShadowStrategy('non-editable')
// Get the current protected range shadow display strategy
console.log(univerAPI.getProtectedRangeShadowStrategy())
// Subscribe to changes in the protected range shadow strategy
const subscription = univerAPI.getProtectedRangeShadowStrategy$().subscribe((strategy) => {
console.log('Global strategy changed to:', strategy)
// Update UI or perform other actions
})
// Later, unsubscribe to clean up
subscription.unsubscribe()Custom User Component
Univer's built-in custom user components are limited in their adaptability. If you need more complex custom components, you can create them using the following method.
You can refer to Custom Components for how to create custom components.
const { univer } = createUniver({
presets: [
UniverSheetsCorePreset({
sheets: {
protectedRangeUserSelector: {
/**
* custom component, should implement the `IPermissionDetailUserPartProps` interface.
*/
component: CustomPermissionDetailUserPart,
/**
* The framework of the component. Must be passed correctly.
*/
framework: 'react',
},
},
}),
],
})univer.registerPlugin(UniverSheetsUIPlugin, {
protectedRangeUserSelector: {
/**
* custom component, should implement the `IPermissionDetailUserPartProps` interface.
*/
component: CustomPermissionDetailUserPart,
/**
* The framework of the component. Must be passed correctly.
*/
framework: 'react',
},
})After completing the custom user settings, please synchronize it to the sheetPermissionUserManagerService service's _selectUserList for later use.
import { SheetPermissionUserManagerService, useDependency } from '@univerjs/preset-sheets-core'
const sheetPermissionUserManagerService = useDependency(SheetPermissionUserManagerService)
// For the specific data structure, refer to: https://github.com/dream-num/univer/blob/b4d4cfa063c9e6d5a82d1fc6b05edc206a415252/packages/sheets-ui/src/services/permission/sheet-permission-user-list.service.ts#L57
sheetPermissionUserManagerService.setSelectUserList([])import { SheetPermissionUserManagerService } from '@univerjs/sheets-ui'
import { useDependency } from '@univerjs/ui'
const sheetPermissionUserManagerService = useDependency(SheetPermissionUserManagerService)
// For the specific data structure, refer to: https://github.com/dream-num/univer/blob/b4d4cfa063c9e6d5a82d1fc6b05edc206a415252/packages/sheets-ui/src/services/permission/sheet-permission-user-list.service.ts#L57
sheetPermissionUserManagerService.setSelectUserList([])Facade API
The Facade API provides a unified entry point for permissions. Below, we will group common methods by workbook, worksheet, and range.
Workbook Permissions
Get Workbook Permission Instance
const fWorkbook = univerAPI.getActiveWorkbook()
const workbookPermission = fWorkbook.getWorkbookPermission()Set Workbook Permission Point
WorkbookPermissionPoint enum values list can be found in Workbook Permission Points List.
const fWorkbook = univerAPI.getActiveWorkbook()
const workbookPermission = fWorkbook.getWorkbookPermission()
// Set the workbook print permission to unavailable
await workbookPermission.setPoint(univerAPI.Enum.WorkbookPermissionPoint.Print, false)Using predefined modes:
const fWorkbook = univerAPI.getActiveWorkbook()
const workbookPermission = fWorkbook.getWorkbookPermission()
// Set to owner mode
await workbookPermission.setMode('owner')
// Set to editor mode
await workbookPermission.setMode('editor')
// Set to viewer mode
await workbookPermission.setMode('viewer')
// Set to commenter mode
await workbookPermission.setMode('commenter')Using shortcut methods:
FWorkbookPermission.setReadOnly(): Set to read-only mode, equivalent tosetMode('viewer')FWorkbookPermission.setEditable(): Set to editable mode, equivalent tosetMode('editor')
Get Workbook Permission Point Status
const fWorkbook = univerAPI.getActiveWorkbook()
const workbookPermission = fWorkbook.getWorkbookPermission()
// Get workbook print permission status
const canPrint = workbookPermission.getPoint(univerAPI.Enum.WorkbookPermissionPoint.Print)
console.log('Can print:', canPrint)
// Get all workbook permission point statuses
const snapshot = workbookPermission.getSnapshot()
console.log('Workbook permission snapshot:', snapshot)Using shortcut methods:
FWorkbookPermission.canEdit(): Check if the workbook is editable
Collaborator Management
Caution
Collaborator management related APIs are only available when using the collaborative editing feature and integrating with the USIP service. When using a custom permission service, please refer to the "Integration of Third-Party Authorization Service" section above to implement the collaborator management logic yourself.
- Get Collaborators List
const fWorkbook = univerAPI.getActiveWorkbook()
const workbookPermission = fWorkbook.getWorkbookPermission()
const collaborators = await workbookPermission.listCollaborators()
console.log(collaborators)- Add Collaborators
const fWorkbook = univerAPI.getActiveWorkbook()
const workbookPermission = fWorkbook.getWorkbookPermission()
// Add multiple collaborators at once
await workbookPermission.setCollaborators([
{
user: { userID: 'user1', name: 'John Doe', avatar: 'https://...' },
role: univerAPI.Enum.UnitRole.Editor,
},
{
user: { userID: 'user2', name: 'Jane Smith', avatar: '' },
role: univerAPI.Enum.UnitRole.Reader,
},
])
// Add single Collaborator
await workbookPermission.addCollaborator(
{ userID: 'user1', name: 'John Doe', avatar: 'https://...' },
univerAPI.Enum.UnitRole.Editor,
)- Update Collaborator Role
const fWorkbook = univerAPI.getActiveWorkbook()
const workbookPermission = fWorkbook.getWorkbookPermission()
await workbookPermission.updateCollaborator(
{ userID: 'user1', name: 'John Doe Updated', avatar: 'https://...' },
univerAPI.Enum.UnitRole.Reader,
)- Remove Collaborators
const fWorkbook = univerAPI.getActiveWorkbook()
const workbookPermission = fWorkbook.getWorkbookPermission()
// Remove multiple collaborators
await workbookPermission.removeCollaborators(['user1', 'user2'])
// Remove single collaborator
await workbookPermission.removeCollaborator('user1')Worksheet Permissions
Get Worksheet Permission Instance
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const worksheetPermission = fWorksheet.getWorksheetPermission()Worksheet Protection
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const worksheetPermission = fWorksheet.getWorksheetPermission()
// Set worksheet protection, allowing specified users to edit
const permissionId = await worksheetPermission.protect({
allowedUsers: ['user1', 'user2'],
name: 'My Worksheet Protection',
})
// Check if the worksheet is protected
const isProtected = worksheetPermission.isProtected()
console.log('Is worksheet protected:', isProtected)
if (isProtected) {
// Remove worksheet protection
await worksheetPermission.unprotect()
}Set Worksheet Permission Point
WorksheetPermissionPoint enum values list can be found in Worksheet Permission Points List.
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const worksheetPermission = fWorksheet.getWorksheetPermission()
// If you need to set permission points, you must first create worksheet protection
await worksheetPermission.protect()
// Set the worksheet insert row permission to unavailable
await worksheetPermission.setPoint(univerAPI.Enum.WorksheetPermissionPoint.InsertRow, false)Using predefined modes:
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const worksheetPermission = fWorksheet.getWorksheetPermission()
// If you need to set permission points, you must first create worksheet protection
await worksheetPermission.protect()
// Set to editable mode
await worksheetPermission.setMode('editable')
// Set to read-only mode
await worksheetPermission.setMode('readOnly')
// Set to filter/sort only mode
await worksheetPermission.setMode('filterOnly')
// Set to custom mode
await worksheetPermission.applyConfig({
mode: 'readOnly',
points: {
[univerAPI.Enum.WorksheetPermissionPoint.InsertRow]: true,
[univerAPI.Enum.WorksheetPermissionPoint.InsertColumn]: true,
},
})Using shortcut methods:
FWorksheetPermission.setReadOnly(): Set to read-only mode, equivalent tosetMode('readOnly')FWorksheetPermission.setEditable(): Set to editable mode, equivalent tosetMode('editable')
Get Worksheet Permission Point Status
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const worksheetPermission = fWorksheet.getWorksheetPermission()
// Get worksheet insert row permission status
const canInsertRow = worksheetPermission.getPoint(univerAPI.Enum.WorksheetPermissionPoint.InsertRow)
// Get all worksheet permission point statuses
const snapshot = worksheetPermission.getSnapshot()Using shortcut methods:
FWorksheetPermission.canEdit(): boolean: Check if the worksheet is editableFWorksheetPermission.canEditCell(row: number, col: number): boolean: Check if a specific cell is editableFWorksheetPermission.canView(): boolean: Check if the worksheet is viewableFWorksheetPermission.canViewCell(row: number, col: number): boolean: Check if a specific cell is viewableFWorksheetPermission.debugCellPermission(row: number, col: number): ICellPermissionDebugInfo: Get permission debug info for a specific cell
Range Permissions
Get Range Permission Instance
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const fRange = fWorksheet.getRange('A1:B2')
const rangePermission = fRange.getRangePermission()Set Range Protection
- Set range protection using the worksheet-level permission:
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const worksheetPermission = fWorksheet.getWorksheetPermission()
// Set multiple protected ranges, A1:B2 is not editable but viewable by others, C3:D4 is editable by specified users but not viewable by others
const rules = await worksheetPermission.protectRanges([
{
ranges: [fWorksheet.getRange('A1:B2')],
options: { name: 'Protected Area 1', allowViewByOthers: true },
},
{
ranges: [fWorksheet.getRange('C3:D4')],
options: { name: 'Protected Area 2', allowViewByOthers: false, allowedUsers: ['user1'] },
},
])
console.log(rules)
// Get all protection rules for the worksheet
const rules = await worksheetPermission.listRangeProtectionRules()
console.log(rules)
// Delete the first protection rule
await worksheetPermission.unprotectRules([rules[0].id])
// Or delete protection range through `FRangeProtectionRule.remove()`
await ruleList[0].remove()- Set range protection using the range-level permission:
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const fRange = fWorksheet.getRange('A1:B2')
const rangePermission = fRange.getRangePermission()
// Set protection for the range, allowing specified users to edit but not allowing others to view
const rule = await rangePermission.protect({
name: 'My protected range',
allowViewByOthers: false,
allowedUsers: ['user1', 'user2'],
})
console.log(rule)
// Get all protection rules for the range
const rules = await rangePermission.listRules()
console.log(rules)
// Delete all protection rules for the range
await rangePermission.unprotect()
// Or delete protection rules through `FRangeProtectionRule.remove()`
await rules[0].remove()Set Range Permission Point
RangePermissionPoint enum values list can be found in Range Protection Points List.
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const fRange = fWorksheet.getRange('A1:B2')
const rangePermission = fRange.getRangePermission()
// If you need to set permission points, you must first create range protection
if (rangePermission.isProtected()) {
const rules = await rangePermission.listRules()
// Set the edit permission of the first protection rule to unavailable, and the view permission to available
await rules[0].setPoint(univerAPI.Enum.RangePermissionPoint.Edit, false)
await rules[0].setPoint(univerAPI.Enum.RangePermissionPoint.View, true)
} else {
const rule = await rangePermission.protect({
name: 'My protected range',
allowViewByOthers: false,
allowedUsers: ['user1', 'user2'],
})
// Set the edit permission of the A1:B2 selection to unavailable, and the view permission to available
await rule.setPoint(univerAPI.Enum.RangePermissionPoint.Edit, false)
await rule.setPoint(univerAPI.Enum.RangePermissionPoint.View, true)
}Range Permission Rule API
Here are some member methods of FRangeProtectionRule:
| API | Description |
|---|---|
id: string | The unique identifier of the protection rule |
permissionId: string | The permission ID associated with the protection rule |
ranges: FRange[] | The ranges covered by the protection rule |
options: IRangeProtectionOptions | The options of the protection rule, including the name of the rule, whether to allow others to view, and the list of users allowed to edit |
updateRanges(ranges: FRange[]): Promise<boolean> | Update the ranges covered by the protection rule |
remove(): Promise<boolean> | Remove the protection rule |
setPoint(point: RangePermissionPoint, value: boolean): Promise<void> | Set the status of a specific permission point for the protection rule (e.g., edit/view/delete) |
getPoint(point: RangePermissionPoint): boolean | Get the status of a specific permission point for the protection rule (e.g., edit/view/delete) |
canEdit(): boolean | Check if the protection rule allows editing |
canView(): boolean | Check if the protection rule allows viewing |
canDelete(): boolean | Check if the protection rule allows deletion |
getSnapshot(): RangePermissionSnapshot | Get a snapshot of the current permission status of the protection rule, including all permission points |
const fWorkbook = univerAPI.getActiveWorkbook()
const fWorksheet = fWorkbook.getActiveSheet()
const worksheetPermission = fWorksheet.getWorksheetPermission()
const rules = await worksheetPermission.listRangeProtectionRules()
const rule = rules?.[0]
// ID Get the ID of the first protection rule
const ruleId = rule?.id
console.log(ruleId)
// Get the ranges of the first protection rule
const ranges = rule?.ranges
console.log(ranges)
// A1:C3 Update the ranges of the first protection rule to A1:C3
await rule?.updateRanges([fWorksheet.getRange('A1:C3')])
// Remove the first protection rule
await rule?.remove()Remove Permission Dialog
univerAPI.setPermissionDialogVisible(false)Old API Migration Guide
| API Method Description | Migration Guide |
|---|---|
| Get Permission Instance | Old API: FWorkbook.getPermission()New API: Workbook: FWorkbook.getWorkbookPermission()Worksheet: FWorksheet.getWorksheetPermission()Range: FRange.getRangePermission() |
| Set Workbook Permission Point | Old API: FPermission.setWorkbookPermissionPoint(unitId: string, FPointClass: WorkbookPermissionPointConstructor, value: boolean)New API: FWorkbookPermission.setPoint(point: WorkbookPermissionPoint, value: boolean) |
| Get Workbook Permission Point Status | Old API: FPermission.checkWorkbookPermissionPoint(unitId: string, FPointClass: WorkbookPermissionPointConstructor): booleanNew API: FWorkbookPermission.getPoint(point: WorkbookPermissionPoint): boolean |
| Set Workbook Edit Permission | Old API: FPermission.setWorkbookEditPermission(unitId: string, value: boolean)New API: FWorkbookPermission.setPoint(univerAPI.Enum.WorkbookPermissionPoint.Edit, value: boolean) |
| Add Worksheet Protection | Old API: FPermission.addWorksheetBasePermission(unitId: string, subUnitId: string)New API: FWorksheetPermission.protect(options?: IWorksheetProtectionOptions) |
| Remove Worksheet Protection | Old API: FPermission.removeWorksheetPermission(unitId: string, subUnitId: string)New API: FWorksheetPermission.unprotect() |
| Set Worksheet Permission Point | Old API: FPermission.setWorksheetPermissionPoint(unitId: string, subUnitId: string, FPointClass: WorkSheetPermissionPointConstructor, value: boolean)New API: FWorksheetPermission.setPoint(point: WorksheetPermissionPoint, value: boolean) |
| Get Worksheet Permission Point Status | Old API: FPermission.checkWorksheetPermissionPoint(unitId: string, subUnitId: string, FPointClass: WorkSheetPermissionPointConstructor): booleanNew API: FWorksheetPermission.getPoint(point: WorksheetPermissionPoint): boolean |
| Get Permission Info of Specific Cell | Old API: FPermission.getPermissionInfoWithCell(unitId: string, subUnitId: string, row: number, column: number)New API: FWorksheetPermission.debugCellPermission(row: number, col: number): ICellPermissionDebugInfo |
| Set Range Protection Permission | Old API: FPermission.addRangeBaseProtection(unitId: string, subUnitId: string, ranges: FRange[])New API: Worksheet: FWorksheetPermission.protectRanges(configs)Range: FRangePermission.protect(options?: IRangeProtectionOptions) |
| Remove Range Protection Permission | Old API: FPermission.removeRangeProtection(unitId: string, subUnitId: string, ruleIds: string[])New API: Worksheet: FWorksheetPermission.unprotectRules(ruleIds: string[])Range: FRangePermission.unprotect()Range Protection Rule: FRangeProtectionRule.remove() |
| Set Range Protection Permission Point | Old API: FPermission.setRangeProtectionPermissionPoint(unitId: string, subUnitId: string, permissionId: string, FPointClass: RangePermissionPointConstructor, value: boolean)New API: FRangeProtectionRule.setPoint(point: RangePermissionPoint, value: boolean) |
| Update Range Protection Permission Ranges | Old API: FPermission.setRangeProtectionRanges(unitId: string, subUnitId: string, ruleId: string, ranges: FRange[])New API: FRangeProtectionRule.updateRanges(ranges: FRange[]) |
| Remove Permission Dialog | Old API: FPermission.setPermissionDialogVisible(false)New API: univerAPI.setPermissionDialogVisible(false) |
How is this guide?
