签入版本

This commit is contained in:
小蚂蚁云
2026-10-20 21:19:44 +08:00
commit 7e70ed6942
2943 changed files with 498573 additions and 0 deletions
@@ -0,0 +1,132 @@
# 5.9 数据权限
:::tip 概述
数据权限控制用户能看到哪些数据,基于角色的 `data_scope` 字段进行过滤。支持三种范围:全部数据、本部门数据、仅本人数据。
:::
## 三种范围
```text
┌─────────────────────────────────────────────────────────┐
│ data_scope = 1 │
│ 全部数据(不过滤) │
│ │
│ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │
│ │ A │ │ B │ │ C │ │ D │ │ E │ ← 所有部门所有人的数据 │
│ └───┘ └───┘ └───┘ └───┘ └───┘ │
└─────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ data_scope = 2 │
│ 本部门数据 │
│ │
│ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │
│ │ A │ │ B │ │███│ │ D │ │ E │ ← 只看到本部门数据 │
│ └───┘ └───┘ └───┘ └───┘ └───┘ │
└─────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ data_scope = 3 │
│ 仅本人数据 │
│ │
│ ┌───┐ ┌───┐ ┌───┐ ┌───┐ ┌───┐ │
│ │ A │ │ B │ │███│ │ D │ │ E │ ← 只看到自己创建的数据 │
│ └───┘ └───┘ └───┘ └───┘ └───┘ │
└─────────────────────────────────────────────────────────┘
```
## 配置方式
在 Logic 中配置数据权限字段即可启用:
```php
class UserLogic extends BaseTenantLogic
{
/**
* 数据权限:部门关联字段名(用于按部门过滤)
*
* @var string
*/
protected string $dataScopeDeptField = 'dept_id';
}
class ArticleLogic extends BaseTenantLogic
{
/**
* 数据权限:归属字段名(用于按创建人过滤)
*
* @var string
*/
protected string $dataScopeUserField = 'create_user';
}
```
## 实现机制
```php
// app/BaseLogic.php
protected function applyDataScope($model)
{
// 未配置数据权限字段则跳过
if (empty($this->dataScopeUserField) && empty($this->dataScopeDeptField)) {
return $model;
}
// 获取当前用户信息
$userInfo = request()->userInfo ?? null;
$uid = $userInfo->uid ?? 0;
$roleId = $userInfo->role_id ?? 0;
// 获取角色的数据权限范围
$dataScope = $this->getRoleDataScope($roleId);
// 1=全部数据,不做过滤
if ($dataScope == 1) {
return $model;
}
// 2=本部门数据
if ($dataScope == 2 && $this->dataScopeDeptField) {
$deptId = $this->getUserDeptId($uid);
if ($deptId) {
$model = $model->where($this->dataScopeDeptField, $deptId);
}
return $model;
}
// 3=仅本人数据
if ($dataScope == 3 && $this->dataScopeUserField) {
$model = $model->where($this->dataScopeUserField, $userInfo->username);
return $model;
}
return $model;
}
```
## 角色配置
在角色管理中设置 `data_scope` 字段:
| 值 | 范围 | 适用场景 |
|----|------|----------|
| 1 | 全部数据 | 管理层、超级管理员 |
| 2 | 本部门数据 | 部门经理 |
| 3 | 仅本人数据 | 普通员工 |
## 缓存说明
角色的数据权限范围带 1 小时缓存(`role_data_scope_{roleId}`)。修改角色权限后需等待缓存过期或手动清除。
## 超级管理员
`uid=1` 的超级管理员不受数据权限限制,始终看到全部数据。详见 [RBAC 权限管理](/zh/core/rbac.html)。
## 与租户隔离的关系
数据权限和租户隔离是两个独立的维度:
- **租户隔离**:按 `tenant_id` 过滤,不同租户数据完全隔离
- **数据权限**:在同一租户内,按部门或创建人进一步过滤
两者可以同时生效,租户隔离优先级更高。