Files
huang eaa70ac255 feat: 实现 RBAC 权限系统和数据权限控制 (004-rbac-data-permission)
主要功能:
- 实现完整的 RBAC 权限系统(账号、角色、权限的多对多关联)
- 基于 owner_id + shop_id 的自动数据权限过滤
- 使用 PostgreSQL WITH RECURSIVE 查询下级账号
- Redis 缓存优化下级账号查询性能(30分钟过期)
- 支持多租户数据隔离和层级权限管理

技术实现:
- 新增 Account、Role、Permission 模型及关联关系表
- 实现 GORM Scopes 自动应用数据权限过滤
- 添加数据库迁移脚本(000002_rbac_data_permission、000003_add_owner_id_shop_id)
- 完善错误码定义(1010-1027 为 RBAC 相关错误)
- 重构 main.go 采用函数拆分提高可读性

测试覆盖:
- 添加 Account、Role、Permission 的集成测试
- 添加数据权限过滤的单元测试和集成测试
- 添加下级账号查询和缓存的单元测试
- 添加 API 回归测试确保向后兼容

文档更新:
- 更新 README.md 添加 RBAC 功能说明
- 更新 CLAUDE.md 添加技术栈和开发原则
- 添加 docs/004-rbac-data-permission/ 功能总结和使用指南

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-18 16:44:06 +08:00

509 lines
17 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Data Model: RBAC 表结构与数据权限过滤
**Feature**: 004-rbac-data-permission
**Date**: 2025-11-18
## 概述
本功能定义 5 个 RBAC 核心表(账号、角色、权限、账号-角色关联、角色-权限关联)和 1 个辅助表数据变更日志以及为现有业务表添加数据权限字段owner_id, shop_id
**设计原则**
- ✅ 禁止外键约束(遵循 Constitution Principle IX
- ✅ GORM 模型禁止 ORM 关联标签
- ✅ 所有表支持软删除(`deleted_at` 字段)
- ✅ 时间字段由 GORM 自动管理
---
## 1. Account (账号表)
**表名**: `tb_account`
### 字段定义
| 字段名 | 类型 | 约束 | 说明 |
|--------|------|------|------|
| id | BIGSERIAL | PRIMARY KEY | 账号主键 |
| username | VARCHAR(50) | UNIQUE NOT NULL | 用户名 |
| phone | VARCHAR(20) | UNIQUE NOT NULL | 手机号 |
| password | VARCHAR(255) | NOT NULL | bcrypt 哈希密码 |
| user_type | SMALLINT | NOT NULL | 用户类型1=root, 2=平台, 3=代理, 4=企业 |
| shop_id | INTEGER | NULL | 所属店铺 ID |
| parent_id | INTEGER | NULL | 上级账号 ID自关联 |
| status | SMALLINT | NOT NULL DEFAULT 1 | 状态0=禁用, 1=启用 |
| creator | INTEGER | NOT NULL | 创建人 ID |
| updater | INTEGER | NOT NULL | 更新人 ID |
| created_at | TIMESTAMP | NOT NULL | 创建时间GORM 自动填充) |
| updated_at | TIMESTAMP | NOT NULL | 更新时间GORM 自动更新) |
| deleted_at | TIMESTAMP | NULL | 软删除时间 |
### 索引
```sql
CREATE UNIQUE INDEX idx_account_username ON tb_account(username) WHERE deleted_at IS NULL;
CREATE UNIQUE INDEX idx_account_phone ON tb_account(phone) WHERE deleted_at IS NULL;
CREATE INDEX idx_account_user_type ON tb_account(user_type);
CREATE INDEX idx_account_shop_id ON tb_account(shop_id);
CREATE INDEX idx_account_parent_id ON tb_account(parent_id);
CREATE INDEX idx_account_deleted_at ON tb_account(deleted_at);
```
### 业务规则
1. **username 和 phone 唯一性**:软删除后可以使用相同的用户名/手机号重新注册
2. **parent_id 不可更改**:账号创建时设置 parent_id创建后禁止修改
3. **层级关系**只有本级账号能创建下级账号A 创建 BB 创建 C
4. **软删除**:删除账号时设置 deleted_at递归查询下级 ID 时仍包含软删除账号
### GORM 模型
```go
// internal/model/account.go
type Account struct {
ID uint `gorm:"primarykey" json:"id"`
Username string `gorm:"uniqueIndex:idx_account_username,where:deleted_at IS NULL;not null;size:50" json:"username"`
Phone string `gorm:"uniqueIndex:idx_account_phone,where:deleted_at IS NULL;not null;size:20" json:"phone"`
Password string `gorm:"not null;size:255" json:"-"` // 不返回给客户端
UserType int `gorm:"not null;index" json:"user_type"` // 1=root, 2=平台, 3=代理, 4=企业
ShopID *uint `gorm:"index" json:"shop_id,omitempty"`
ParentID *uint `gorm:"index" json:"parent_id,omitempty"`
Status int `gorm:"not null;default:1" json:"status"` // 0=禁用, 1=启用
Creator uint `gorm:"not null" json:"creator"`
Updater uint `gorm:"not null" json:"updater"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
UpdatedAt time.Time `gorm:"not null" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
}
func (Account) TableName() string {
return "tb_account"
}
```
---
## 2. Role (角色表)
**表名**: `tb_role`
### 字段定义
| 字段名 | 类型 | 约束 | 说明 |
|--------|------|------|------|
| id | BIGSERIAL | PRIMARY KEY | 角色主键 |
| role_name | VARCHAR(50) | NOT NULL | 角色名称 |
| role_desc | VARCHAR(255) | NULL | 角色描述 |
| role_type | SMALLINT | NOT NULL | 角色类型1=超级, 2=代理, 3=企业 |
| status | SMALLINT | NOT NULL DEFAULT 1 | 状态0=禁用, 1=启用 |
| creator | INTEGER | NOT NULL | 创建人 ID |
| updater | INTEGER | NOT NULL | 更新人 ID |
| created_at | TIMESTAMP | NOT NULL | 创建时间 |
| updated_at | TIMESTAMP | NOT NULL | 更新时间 |
| deleted_at | TIMESTAMP | NULL | 软删除时间 |
### 索引
```sql
CREATE INDEX idx_role_role_type ON tb_role(role_type);
CREATE INDEX idx_role_deleted_at ON tb_role(deleted_at);
```
### GORM 模型
```go
// internal/model/role.go
type Role struct {
ID uint `gorm:"primarykey" json:"id"`
RoleName string `gorm:"not null;size:50" json:"role_name"`
RoleDesc string `gorm:"size:255" json:"role_desc"`
RoleType int `gorm:"not null;index" json:"role_type"` // 1=超级, 2=代理, 3=企业
Status int `gorm:"not null;default:1" json:"status"`
Creator uint `gorm:"not null" json:"creator"`
Updater uint `gorm:"not null" json:"updater"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
UpdatedAt time.Time `gorm:"not null" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
}
func (Role) TableName() string {
return "tb_role"
}
```
---
## 3. Permission (权限表)
**表名**: `tb_permission`
### 字段定义
| 字段名 | 类型 | 约束 | 说明 |
|--------|------|------|------|
| id | BIGSERIAL | PRIMARY KEY | 权限主键 |
| perm_name | VARCHAR(50) | NOT NULL | 权限名称 |
| perm_code | VARCHAR(100) | UNIQUE NOT NULL | 权限编码(如 `user:create` |
| perm_type | SMALLINT | NOT NULL | 权限类型1=菜单, 2=按钮 |
| url | VARCHAR(255) | NULL | URL 路径 |
| parent_id | INTEGER | NULL | 上级权限 ID支持层级 |
| sort | INTEGER | NOT NULL DEFAULT 0 | 排序序号 |
| status | SMALLINT | NOT NULL DEFAULT 1 | 状态0=禁用, 1=启用 |
| creator | INTEGER | NOT NULL | 创建人 ID |
| updater | INTEGER | NOT NULL | 更新人 ID |
| created_at | TIMESTAMP | NOT NULL | 创建时间 |
| updated_at | TIMESTAMP | NOT NULL | 更新时间 |
| deleted_at | TIMESTAMP | NULL | 软删除时间 |
### 索引
```sql
CREATE UNIQUE INDEX idx_permission_code ON tb_permission(perm_code) WHERE deleted_at IS NULL;
CREATE INDEX idx_permission_type ON tb_permission(perm_type);
CREATE INDEX idx_permission_parent_id ON tb_permission(parent_id);
CREATE INDEX idx_permission_deleted_at ON tb_permission(deleted_at);
```
### GORM 模型
```go
// internal/model/permission.go
type Permission struct {
ID uint `gorm:"primarykey" json:"id"`
PermName string `gorm:"not null;size:50" json:"perm_name"`
PermCode string `gorm:"uniqueIndex:idx_permission_code,where:deleted_at IS NULL;not null;size:100" json:"perm_code"`
PermType int `gorm:"not null;index" json:"perm_type"` // 1=菜单, 2=按钮
URL string `gorm:"size:255" json:"url,omitempty"`
ParentID *uint `gorm:"index" json:"parent_id,omitempty"`
Sort int `gorm:"not null;default:0" json:"sort"`
Status int `gorm:"not null;default:1" json:"status"`
Creator uint `gorm:"not null" json:"creator"`
Updater uint `gorm:"not null" json:"updater"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
UpdatedAt time.Time `gorm:"not null" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
}
func (Permission) TableName() string {
return "tb_permission"
}
```
---
## 4. AccountRole (账号-角色关联表)
**表名**: `tb_account_role`
### 字段定义
| 字段名 | 类型 | 约束 | 说明 |
|--------|------|------|------|
| id | BIGSERIAL | PRIMARY KEY | 关联主键 |
| account_id | INTEGER | NOT NULL | 账号 ID |
| role_id | INTEGER | NOT NULL | 角色 ID |
| status | SMALLINT | NOT NULL DEFAULT 1 | 状态0=禁用, 1=启用 |
| creator | INTEGER | NOT NULL | 创建人 ID |
| updater | INTEGER | NOT NULL | 更新人 ID |
| created_at | TIMESTAMP | NOT NULL | 创建时间 |
| updated_at | TIMESTAMP | NOT NULL | 更新时间 |
| deleted_at | TIMESTAMP | NULL | 软删除时间 |
### 索引
```sql
CREATE INDEX idx_account_role_account_id ON tb_account_role(account_id);
CREATE INDEX idx_account_role_role_id ON tb_account_role(role_id);
CREATE INDEX idx_account_role_deleted_at ON tb_account_role(deleted_at);
CREATE UNIQUE INDEX idx_account_role_unique ON tb_account_role(account_id, role_id) WHERE deleted_at IS NULL;
```
### 业务规则
1. **联合唯一约束**:同一账号不能重复分配相同角色(软删除后可重新分配)
2. **软删除支持**:支持软删除和审计追踪
### GORM 模型
```go
// internal/model/account_role.go
type AccountRole struct {
ID uint `gorm:"primarykey" json:"id"`
AccountID uint `gorm:"not null;index;uniqueIndex:idx_account_role_unique,where:deleted_at IS NULL" json:"account_id"`
RoleID uint `gorm:"not null;index;uniqueIndex:idx_account_role_unique,where:deleted_at IS NULL" json:"role_id"`
Status int `gorm:"not null;default:1" json:"status"`
Creator uint `gorm:"not null" json:"creator"`
Updater uint `gorm:"not null" json:"updater"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
UpdatedAt time.Time `gorm:"not null" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
}
func (AccountRole) TableName() string {
return "tb_account_role"
}
```
---
## 5. RolePermission (角色-权限关联表)
**表名**: `tb_role_permission`
### 字段定义
| 字段名 | 类型 | 约束 | 说明 |
|--------|------|------|------|
| id | BIGSERIAL | PRIMARY KEY | 关联主键 |
| role_id | INTEGER | NOT NULL | 角色 ID |
| perm_id | INTEGER | NOT NULL | 权限 ID |
| status | SMALLINT | NOT NULL DEFAULT 1 | 状态0=禁用, 1=启用 |
| creator | INTEGER | NOT NULL | 创建人 ID |
| updater | INTEGER | NOT NULL | 更新人 ID |
| created_at | TIMESTAMP | NOT NULL | 创建时间 |
| updated_at | TIMESTAMP | NOT NULL | 更新时间 |
| deleted_at | TIMESTAMP | NULL | 软删除时间 |
### 索引
```sql
CREATE INDEX idx_role_permission_role_id ON tb_role_permission(role_id);
CREATE INDEX idx_role_permission_perm_id ON tb_role_permission(perm_id);
CREATE INDEX idx_role_permission_deleted_at ON tb_role_permission(deleted_at);
CREATE UNIQUE INDEX idx_role_permission_unique ON tb_role_permission(role_id, perm_id) WHERE deleted_at IS NULL;
```
### GORM 模型
```go
// internal/model/role_permission.go
type RolePermission struct {
ID uint `gorm:"primarykey" json:"id"`
RoleID uint `gorm:"not null;index;uniqueIndex:idx_role_permission_unique,where:deleted_at IS NULL" json:"role_id"`
PermID uint `gorm:"not null;index;uniqueIndex:idx_role_permission_unique,where:deleted_at IS NULL" json:"perm_id"`
Status int `gorm:"not null;default:1" json:"status"`
Creator uint `gorm:"not null" json:"creator"`
Updater uint `gorm:"not null" json:"updater"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
UpdatedAt time.Time `gorm:"not null" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
}
func (RolePermission) TableName() string {
return "tb_role_permission"
}
```
---
## 6. DataTransferLog (数据变更日志表)
**表名**: `tb_data_transfer_log`
### 字段定义
| 字段名 | 类型 | 约束 | 说明 |
|--------|------|------|------|
| id | BIGSERIAL | PRIMARY KEY | 日志主键 |
| table_name | VARCHAR(100) | NOT NULL | 业务表名 |
| record_id | INTEGER | NOT NULL | 业务数据 ID |
| old_owner_id | INTEGER | NULL | 原归属者 ID |
| new_owner_id | INTEGER | NOT NULL | 新归属者 ID |
| operator_id | INTEGER | NOT NULL | 操作人 ID |
| transfer_reason | VARCHAR(500) | NULL | 分配原因 |
| created_at | TIMESTAMP | NOT NULL | 创建时间 |
### 索引
```sql
CREATE INDEX idx_data_transfer_log_table_record ON tb_data_transfer_log(table_name, record_id);
CREATE INDEX idx_data_transfer_log_operator_id ON tb_data_transfer_log(operator_id);
CREATE INDEX idx_data_transfer_log_created_at ON tb_data_transfer_log(created_at);
```
### 业务规则
1. **只追加Append-Only**:此表不支持更新和删除,只允许插入
2. **审计追踪**:记录完整的数据归属变更历史链
### GORM 模型
```go
// internal/model/data_transfer_log.go
type DataTransferLog struct {
ID uint `gorm:"primarykey" json:"id"`
TableName string `gorm:"not null;size:100;index:idx_data_transfer_log_table_record" json:"table_name"`
RecordID uint `gorm:"not null;index:idx_data_transfer_log_table_record" json:"record_id"`
OldOwnerID *uint `json:"old_owner_id,omitempty"`
NewOwnerID uint `gorm:"not null" json:"new_owner_id"`
OperatorID uint `gorm:"not null;index" json:"operator_id"`
TransferReason string `gorm:"size:500" json:"transfer_reason,omitempty"`
CreatedAt time.Time `gorm:"not null;index" json:"created_at"`
}
func (DataTransferLog) TableName() string {
return "tb_data_transfer_log"
}
```
---
## 7. 现有业务表的扩展
### 7.1 User 表tb_user
**新增字段**
| 字段名 | 类型 | 约束 | 说明 |
|--------|------|------|------|
| owner_id | INTEGER | NULL | 数据归属者 ID历史数据允许 NULL新记录必须非 NULL |
| shop_id | INTEGER | NULL | 店铺 ID历史数据允许 NULL新记录必须非 NULL |
**新增索引**
```sql
CREATE INDEX idx_user_owner_id ON tb_user(owner_id);
CREATE INDEX idx_user_shop_id ON tb_user(shop_id);
```
**更新 GORM 模型**
```go
// internal/model/user.go
type User struct {
// ... 原有字段 ...
OwnerID *uint `gorm:"index" json:"owner_id,omitempty"` // 新增
ShopID *uint `gorm:"index" json:"shop_id,omitempty"` // 新增
}
```
### 7.2 Order 表tb_order
**新增字段**
| 字段名 | 类型 | 约束 | 说明 |
|--------|------|------|------|
| owner_id | INTEGER | NULL | 数据归属者 ID |
| shop_id | INTEGER | NULL | 店铺 ID |
**新增索引**
```sql
CREATE INDEX idx_order_owner_id ON tb_order(owner_id);
CREATE INDEX idx_order_shop_id ON tb_order(shop_id);
```
**更新 GORM 模型**
```go
// internal/model/order.go
type Order struct {
// ... 原有字段 ...
OwnerID *uint `gorm:"index" json:"owner_id,omitempty"` // 新增
ShopID *uint `gorm:"index" json:"shop_id,omitempty"` // 新增
}
```
---
## 8. 数据关系图
```
tb_account (账号表)
├── parent_id → tb_account.id (自关联,层级关系)
├── tb_account_role.account_id (多对多关联)
│ └── tb_account_role.role_id → tb_role.id
│ └── tb_role_permission.role_id → tb_role.id
│ └── tb_role_permission.perm_id → tb_permission.id
└── owner_id (业务表数据归属)
├── tb_user.owner_id
├── tb_order.owner_id
└── tb_data_transfer_log.old_owner_id / new_owner_id
tb_permission (权限表)
└── parent_id → tb_permission.id (自关联,层级关系)
```
**注意**:以上关系均为**逻辑关系**,数据库层面不建立外键约束,代码层面不使用 GORM 关联标签。
---
## 9. 状态转换图
### Account 状态转换
```
[创建] → 启用(1)
禁用(0) ↔ 启用(1)
[软删除] (deleted_at != NULL)
```
### 软删除行为
- 软删除账号后,`deleted_at` 字段被设置为当前时间
- 软删除账号的数据对上级仍然可见(递归查询下级 ID 包含软删除账号)
- 软删除账号的 username 和 phone 可以被重新使用(唯一索引使用 `WHERE deleted_at IS NULL`
---
## 10. 数据权限过滤规则
### 过滤条件
所有业务表查询时自动应用以下条件(除非使用 WithoutDataFilter 选项):
```sql
WHERE owner_id IN (ID列表) AND shop_id = shop_id
```
### 特殊情况
1. **root 用户user_type=1**:跳过数据权限过滤,返回所有数据
2. **C 端业务用户**:使用 WithoutDataFilter 选项,改为基于业务字段(如 iccid/device_id过滤
3. **系统任务**Context 中无用户信息时,不应用过滤
---
## 11. 数据校验规则
### Account 创建校验
- username: 3-20 个字符,字母、数字、下划线
- phone: 11 位中国大陆手机号
- password: 最少 8 位,包含字母和数字
- user_type: 必须为 1-4
- parent_id: 非 root 用户必须提供 parent_id
### Account 更新校验
- **禁止修改**: user_type, parent_id
- **可选修改**: username, phone, status
### Role/Permission 校验
- role_name/perm_name: 不为空,长度 ≤50
- perm_code: 不为空,格式为 `module:action`(如 `user:create`
---
## 总结
本数据模型设计遵循以下原则:
1.**无外键约束**:所有表关系通过 ID 字段手动维护
2.**软删除支持**:所有表(除 DataTransferLog支持软删除
3.**GORM 自动时间管理**created_at 和 updated_at 由 GORM 自动处理
4.**审计字段完整**creator 和 updater 记录操作人
5.**索引优化**:所有查询条件和关联字段都有索引支持
6.**唯一性约束**username、phone、perm_code 使用软删除感知的唯一索引
7.**数据权限字段**owner_id 和 shop_id 用于多租户数据隔离