Bỏ qua, đến nội dung

API reference

Database schema

Quan hệ giữa các bảng

Bảng roles - chi tiết

FieldTypeMô tả
nameuid (PK)ID duy nhất, prefix r_
titlestring (unique)Tên hiển thị, hỗ trợ i18n
descriptionstringMô tả role
strategyjsonStrategy mặc định, ví dụ { actions: ['view', 'create'] }
defaultbooleanNếu true, user mới tự động nhận role này
hiddenbooleanẨn khỏi danh sách role trên UI
allowConfigurebooleanCho phép truy cập trang cấu hình
allowNewMenubooleanCho phép tạo menu page mới
snippetsset<string>Danh sách snippet (ví dụ ['ui.*', 'pm', 'pm.*'])
menuUiSchemasbelongsToManyUI schema menu mà role được phép truy cập
resourceshasManydataSourcesRolesResources
usersbelongsToManyusers qua rolesUsers

Strategy field

json
{
  "actions": ["create", "view", "update", "destroy"]
}

Hoặc với scope:

json
{
  "actions": ["view:own", "update:own", "create", "destroy:own"]
}

view:own = chỉ xem bản ghi do mình tạo.

usingActionsConfig - hai chế độ permission

Giá trịÝ nghĩa
falseCollection dùng strategy mặc định của role
trueCollection có cấu hình action riêng (rows trong dataSourcesRolesResourcesActions)

Custom API endpoints

availableActions:list

Trả về danh sách action mà hệ thống hỗ trợ phân quyền.

GET /api/availableActions:list

Response:

json
[
  { "name": "create", "displayName": "Create", "allowConfigureFields": true },
  { "name": "view", "displayName": "View", "allowConfigureFields": true },
  { "name": "update", "displayName": "Update", "allowConfigureFields": true },
  { "name": "destroy", "displayName": "Delete", "allowConfigureFields": false },
  { "name": "export", "displayName": "Export", "allowConfigureFields": true }
]

roles.collections:list

Danh sách collection cho một role, kèm trạng thái cấu hình.

GET /api/roles/{roleName}/collections:list?page=1&pageSize=20

Response mỗi item:

json
{
  "name": "orders",
  "title": "Đơn hàng",
  "usingConfig": "strategy",
  "exists": false
}
FieldÝ nghĩa
usingConfig"strategy" = dùng strategy mặc định, "resourceAction" = có cấu hình riêng
existstrue nếu đã có row trong dataSourcesRolesResources cho role này

roles:check

Kiểm tra quyền hiệu lực của user hiện tại. Dùng cho client để quyết định hiển thị UI.

GET /api/roles:check

Response:

json
{
  "role": "member",
  "roles": ["member"],
  "roleMode": "default",
  "availableActions": ["create", "view", "update", "destroy", "export"],
  "actionAlias": { "get": "view", "list": "view" },
  "allowAll": false,
  "allowConfigure": false,
  "allowMenuItemIds": ["uid1", "uid2"],
  "anonymous": false,
  "resources": {
    "orders": {
      "view": { "fields": ["id", "title", "status"], "filter": {} },
      "create": { "fields": ["title", "status"] }
    }
  },
  "uiButtonSchemasBlacklist": ["uid3"]
}

roles:setSystemRoleMode

Đặt chế độ role hệ thống.

POST /api/roles:setSystemRoleMode
Body: { "roleMode": "default" | "allow-use-union" | "only-use-union" }
ModeÝ nghĩa
defaultUser sử dụng một role tại một thời điểm
allow-use-unionUser có thể chọn "tất cả role" (union)
only-use-unionLuôn dùng union tất cả role

users:setDefaultRole

Đổi role mặc định cho user hiện tại.

POST /api/users:setDefaultRole
Body: { "roleName": "admin" }

roleName có thể là __union__ (khi roleMode cho phép) để dùng union role.

Không thể set anonymous.

Ví dụ sử dụng API

Tạo role mới

typescript
const response = await agent.resource('roles').create({
  values: {
    name: 'editor',
    title: 'Biên tập viên',
    strategy: {
      actions: ['view', 'create'],
    },
  },
});
// response.statusCode === 200

Cấu hình permission riêng cho collection

typescript
// Gán permissions cho collection "posts" trên role "editor"
await agent.resource('roles.resources', 'editor').create({
  values: {
    name: 'posts',
    usingActionsConfig: true,
    actions: [
      { name: 'create' },
      { name: 'view', fields: ['title', 'content'] },
      { name: 'update', fields: ['title', 'content'] },
    ],
  },
});

// Kiểm tra lại - danh sách collections của role
const listResp = await agent.resource('roles.collections', 'editor').list({
  filter: { name: 'posts' },
});
// listResp.body.data[0].usingConfig === 'resourceAction'

Tạo scope và gán vào action

typescript
// Tạo scope "published posts"
const { body: { data: scope } } = await agent
  .resource('dataSourcesRolesResourcesScopes')
  .create({
    values: {
      resourceName: 'posts',
      name: 'published posts',
      scope: { published: true },
    },
  });

// Gán scope vào action view
await agent.resource('roles.resources', 'editor').create({
  values: {
    name: 'posts',
    usingActionsConfig: true,
    actions: [
      { name: 'view', fields: ['title'], scope: scope.id },
      { name: 'create' },
    ],
  },
});

Kiểm tra quyền hiệu lực

typescript
const checkResp = await agent.resource('roles').check();
const { actions } = checkResp.body.data;

// actions là map dạng { 'posts:create': {...}, 'posts:view': {...} }
console.log(actions['posts:create']); // defined → có quyền
console.log(actions['posts:destroy']); // undefined → không có quyền

Lấy ACL meta cho danh sách (client dùng ẩn/hiện nút)

typescript
const response = await agent
  .set('X-With-ACL-Meta', true)
  .resource('posts')
  .list({});

const { data, meta } = response.body;
// meta.allowedActions.view = [1, 2, 3]    → row IDs được phép xem
// meta.allowedActions.update = [1, 2]      → row IDs được phép sửa
// meta.allowedActions.destroy = [1]        → row IDs được phép xóa

Luồng dữ liệu: UI → DB → ACL

Standard CRUD endpoints

Ngoài custom endpoints ở trên, plugin sử dụng framework CRUD tiêu chuẩn:

ResourceActionsMô tả
roleslist, get, create, update, destroyQuản lý role
roles.resourceslist, get, create, updatePermission per collection per role
roles.snippetslist, add, removeSnippet assignment
roles.menuUiSchemaslist, set, toggleMenu access per role
roles.userslist, add, removeUser-role assignment

Fixed params - bảo vệ hệ thống

Plugin đăng ký fixed params ngăn xóa/sửa dữ liệu hệ thống:

ResourceActionFilterÝ nghĩa
rolesdestroyname != root, admin, memberKhông xóa role hệ thống
rolesResourcesScopesdestroy, updatekey != all, ownKhông sửa/xóa scope mặc định
collectionsdestroyname != roles, rolesUsersKhông xóa collection ACL

Exports

Module server/index.ts export thêm middleware và model để plugin khác tái sử dụng:

ExportMô tả
setCurrentRoleMiddleware gắn role vào request
withACLMetaMiddleware bổ sung ACL meta vào response
applyQueryPermissionÁp dụng query filter theo quyền
RoleModelModel class cho roles
RoleResourceModelModel class cho resources
RoleResourceActionModelModel class cho actions
UNION_ROLE_KEYConstant '__union__'
SystemRoleModeEnum default, allow-use-union, only-use-union