Admin权限与角色

RBAC Configuration Guide

Detailed Guide to Role Permission Configuration

Basic Concepts · Configuration Steps · Best Practices


🎯 Overview

RBAC (Role-Based Access Control) is NextJS Base's permission management system, managing user access permissions through roles.

Core Concepts

User

   └─── Has Role ───► Role

         ┌───────────────┼───────────────┐
         │               │               │
         ▼               ▼               ▼
    Permission        Menu        Inherit Menu Permissions
   (Permission)     (Menu)     (inheritMenuPermissions)
         │               │
         ▼               ▼
    Server Actions    Page Access

📚 Basic Concepts

Permission

Permissions define operations users can perform:

FieldDescriptionExample
namePermission nameView Post, Create Post
parentIdParent ID (supports tree)null / Parent permission ID
crudCategoryCRUD categorypost, user, role
actionsAssociated Server Actions['sysGetPostList', 'sysCreatePost']
apisAssociated API paths['/api/v1/posts']

Menus define admin sidebar display:

FieldDescriptionExample
nameMenu namePost Management
parentIdParent ID (supports tree)null / Parent menu ID
urlPage path/admin/content/posts
iconIconFileTextOutlined
permissionAssociated permission ID array['perm_id_1', 'perm_id_2']

Role

Roles are collections of permissions and menus:

FieldDescriptionExample
nameRole nameadmin, editor
permissionPermission ID array['perm_id_1', 'perm_id_2']
menuMenu ID array['menu_id_1', 'menu_id_2']
inheritMenuPermissionsWhether to inherit menu permissionstrue / false

📝 Configuration Steps

Step 1: Create Permissions

Create permissions in the "Permission Management" page:

Post Management (Parent Permission)
├── View Post
│   └── actions: ['sysGetPostList', 'sysGetPostDetail']
├── Create Post
│   └── actions: ['sysCreatePost']
├── Edit Post
│   └── actions: ['sysUpdatePost']
└── Delete Post
    └── actions: ['sysDeletePost', 'sysBatchDeletePost']

Configuration Example:

FieldParent PermissionChild Permission (View Post)
NamePost ManagementView Post
Parent-Post Management
CRUD Categorypostpost
Actions[]['sysGetPostList', 'sysGetPostDetail']

Step 2: Create Menus

Create menus in the "Menu Management" page:

Content Management (Parent Menu)
├── Post Management
│   ├── URL: /admin/content/posts
│   ├── Icon: FileTextOutlined
│   └── Associated Permissions: [View Post, Create Post, Edit Post, Delete Post]
└── Category Management
    ├── URL: /admin/content/categories
    └── Associated Permissions: [View Category, Create Category, ...]

Step 3: Create Roles

Create roles in the "Role Management" page:

Admin Role:

FieldValue
Nameadmin
Permissions[] (can be empty)
Menus[All menus]
Inherit Menu Permissions✅ Yes

Editor Role:

FieldValue
Nameeditor
Permissions[View Post, Create Post, Edit Post]
Menus[Post Management]
Inherit Menu Permissions❌ No

Step 4: Assign Roles to Users

Assign roles to users in the "User Management" page:

  1. Find target user
  2. Click "Edit"
  3. Select role in "Role" field
  4. Ensure "Backend Access" is enabled
  5. Save

🔐 Permission Check Flow

Action Permission Check

// 1. Call Server Action
sysGetPostListAction()

// 2. wrapAction parses Action name
//    - Prefix: sys → requires admin permission
//    - Operation: GetPostList

// 3. Check if user has admin access permission
if (!user.hasBackendAccess) {
  throw new Error('No admin access permission')
}

// 4. Get all permissions of user's roles
const permissions = await getUserPermissions(user.roles)

// 5. Check if Action is in permission list
const allowedActions = permissions.flatMap(p => p.actions)
if (!allowedActions.includes('sysGetPostList')) {
  throw new Error('No permission to perform this operation')
}

// 6. Execute business logic

Permission Aggregation and Menu Inheritance

  • User permissions = Union of role's explicit permission and all "inherit menu permissions" roles' menu-associated permissions. Implementation location: app/(admin)/actions/dao/sys.js#getUserPermissionIds.
  • Inheritance logic: If role inheritMenuPermissions === true, add each menu's permission from the role's menu together, then deduplicate.
  • Action matching: Permissions' actions (supports wildcards like sysCreateExample*) are extracted and matched against current Server Action by checkUserHasActionPermission.
  • Example: Menu "with permissions" associates permission "example write(no delete)" whose actions include sysCreateExample*/sysUpdateExample*/sysBatchUpdateExample*/sysActivateExample*/sysDeactivateExample*. After granting this menu to a role and checking "Inherit Menu Permissions", then granting the role to a user, the user ultimately has the above action permissions.
// 1. Get user roles
const roles = await getRoles(user.roles)

// 2. Aggregate all menu IDs
const menuIds = roles.flatMap(r => r.menu)

// 3. Get menu details
const menus = await getMenus(menuIds)

// 4. Filter enabled and non-hidden menus
const visibleMenus = menus.filter(m => m.enable && !m.hidden)

// 5. Build menu tree and render sidebar

🎨 Configuration Examples

Example: E-commerce System Permissions

Product Management
├── View Product [sysGetProductList, sysGetProductDetail]
├── Create Product [sysCreateProduct]
├── Edit Product [sysUpdateProduct]
├── Delete Product [sysDeleteProduct]
└── Toggle Product Status [sysToggleProductStatus]

Order Management
├── View Order [sysGetOrderList, sysGetOrderDetail]
├── Process Order [sysUpdateOrder]
├── Cancel Order [sysCancelOrder]
└── Export Order [sysExportOrder]

User Management
├── View User [sysGetUserList, sysGetUserDetail]
├── Edit User [sysUpdateUser]
├── Ban User [sysBanUser]
└── Reset Password [sysResetUserPassword]

Example: Role Configuration

Super Admin:

{
  name: 'super_admin',
  permission: [],  // Empty, use menu inheritance
  menu: ['All menu IDs'],
  inheritMenuPermissions: true,
}

Operator:

{
  name: 'operator',
  permission: [
    'View Product', 'Edit Product', 'Toggle Product Status',
    'View Order', 'Process Order',
  ],
  menu: ['Product Management', 'Order Management'],
  inheritMenuPermissions: false,
}

Customer Service:

{
  name: 'customer_service',
  permission: [
    'View Order',
    'View User',
  ],
  menu: ['Order Management', 'User Management'],
  inheritMenuPermissions: false,
}

✅ Best Practices

1. Permission Granularity

✅ Recommended: Fine-grained permissions
├── View Post
├── Create Post
├── Edit Post
└── Delete Post

❌ Not Recommended: Coarse-grained permissions
└── Post Management (includes all operations)

2. Use CRUD Category

// ✅ Recommended: Use crudCategory for grouping
{
  name: 'View Post',
  crudCategory: 'post',  // Easy to filter and manage
  actions: ['sysGetPostList'],
}

3. Menu Permission Inheritance

// ✅ Admin: Use inheritance to simplify configuration
{
  name: 'admin',
  menu: ['All menus'],
  inheritMenuPermissions: true,  // Automatically get menu-associated permissions
}

// ✅ Regular Role: Explicitly assign permissions
{
  name: 'editor',
  permission: ['Specific permissions'],
  menu: ['Edit-related menus'],
  inheritMenuPermissions: false,  // Precise permission control
}

4. Permission Naming Convention

{Module Name} - {Operation}

Examples:
- Post Management - View
- Post Management - Create
- Post Management - Edit
- Post Management - Delete

5. Regular Auditing

  • Regularly check role permission configuration
  • Remove unused permissions
  • Check if user role assignments are reasonable
  • Review operation logs for anomalies