Files
junhong_cmp_fiber/tests/integration/data_permission_test.go
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

326 lines
9.3 KiB
Go

package integration
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/break/junhong_cmp_fiber/internal/model"
"github.com/break/junhong_cmp_fiber/internal/store/postgres"
"github.com/break/junhong_cmp_fiber/pkg/constants"
"github.com/break/junhong_cmp_fiber/pkg/middleware"
)
// TestDataPermission_HierarchicalFiltering 测试层级数据权限过滤
func TestDataPermission_HierarchicalFiltering(t *testing.T) {
store, cleanup := setupTestDB(t)
defer cleanup()
ctx := context.Background()
db := store.DB()
// 创建层级结构: A -> B -> C
accountA := &model.Account{
Username: "user_a",
Phone: "13800000001",
Password: "hashed_password",
UserType: constants.UserTypePlatform,
Status: constants.StatusEnabled,
Creator: 1,
Updater: 1,
}
require.NoError(t, db.Create(accountA).Error)
shopID := uint(100)
accountA.ShopID = &shopID
require.NoError(t, db.Save(accountA).Error)
accountB := &model.Account{
Username: "user_b",
Phone: "13800000002",
Password: "hashed_password",
UserType: constants.UserTypeAgent,
ParentID: &accountA.ID,
ShopID: &shopID,
Status: constants.StatusEnabled,
Creator: 1,
Updater: 1,
}
require.NoError(t, db.Create(accountB).Error)
accountC := &model.Account{
Username: "user_c",
Phone: "13800000003",
Password: "hashed_password",
UserType: constants.UserTypeEnterprise,
ParentID: &accountB.ID,
ShopID: &shopID,
Status: constants.StatusEnabled,
Creator: 1,
Updater: 1,
}
require.NoError(t, db.Create(accountC).Error)
// 创建测试数据表
type TestData struct {
ID uint `gorm:"primarykey"`
Name string
OwnerID uint
ShopID uint
}
require.NoError(t, db.AutoMigrate(&TestData{}))
// 插入测试数据
testData := []TestData{
{Name: "data_a", OwnerID: accountA.ID, ShopID: 100},
{Name: "data_b", OwnerID: accountB.ID, ShopID: 100},
{Name: "data_c", OwnerID: accountC.ID, ShopID: 100},
{Name: "data_other", OwnerID: 999, ShopID: 100},
}
require.NoError(t, db.Create(&testData).Error)
// 创建 AccountStore 用于递归查询
accountStore := postgres.NewAccountStore(db, nil) // Redis 可选
t.Run("A 用户可以看到 A、B、C 的数据", func(t *testing.T) {
ctxWithA := middleware.SetUserContext(ctx, accountA.ID, constants.UserTypePlatform, 100)
var results []TestData
err := db.WithContext(ctxWithA).
Scopes(postgres.DataPermissionScope(ctxWithA, accountStore)).
Find(&results).Error
require.NoError(t, err)
assert.Len(t, results, 3)
})
t.Run("B 用户可以看到 B、C 的数据", func(t *testing.T) {
ctxWithB := middleware.SetUserContext(ctx, accountB.ID, constants.UserTypeAgent, 100)
var results []TestData
err := db.WithContext(ctxWithB).
Scopes(postgres.DataPermissionScope(ctxWithB, accountStore)).
Find(&results).Error
require.NoError(t, err)
assert.Len(t, results, 2)
})
t.Run("C 用户只能看到自己的数据", func(t *testing.T) {
ctxWithC := middleware.SetUserContext(ctx, accountC.ID, constants.UserTypeEnterprise, 100)
var results []TestData
err := db.WithContext(ctxWithC).
Scopes(postgres.DataPermissionScope(ctxWithC, accountStore)).
Find(&results).Error
require.NoError(t, err)
assert.Len(t, results, 1)
assert.Equal(t, "data_c", results[0].Name)
})
}
// TestDataPermission_WithoutDataFilter 测试 WithoutDataFilter 选项
func TestDataPermission_WithoutDataFilter(t *testing.T) {
store, cleanup := setupTestDB(t)
defer cleanup()
ctx := context.Background()
db := store.DB()
// 创建测试账号
shopID := uint(100)
accountA := &model.Account{
Username: "user_a",
Phone: "13800000001",
Password: "hashed_password",
UserType: constants.UserTypePlatform,
ShopID: &shopID,
Status: constants.StatusEnabled,
Creator: 1,
Updater: 1,
}
require.NoError(t, db.Create(accountA).Error)
// 创建测试数据表
type TestData struct {
ID uint `gorm:"primarykey"`
Name string
OwnerID uint
ShopID uint
}
require.NoError(t, db.AutoMigrate(&TestData{}))
// 插入测试数据
testData := []TestData{
{Name: "data_a", OwnerID: accountA.ID, ShopID: 100},
{Name: "data_b", OwnerID: 999, ShopID: 100},
{Name: "data_c", OwnerID: 888, ShopID: 200},
}
require.NoError(t, db.Create(&testData).Error)
// 创建 AccountStore
accountStore := postgres.NewAccountStore(db, nil)
t.Run("正常查询应该过滤数据", func(t *testing.T) {
ctxWithA := middleware.SetUserContext(ctx, accountA.ID, constants.UserTypePlatform, 100)
var results []TestData
err := db.WithContext(ctxWithA).
Scopes(postgres.DataPermissionScope(ctxWithA, accountStore)).
Find(&results).Error
require.NoError(t, err)
assert.Len(t, results, 1)
})
t.Run("不带用户上下文时返回空数据", func(t *testing.T) {
var results []TestData
err := db.WithContext(ctx).
Scopes(postgres.DataPermissionScope(ctx, accountStore)).
Find(&results).Error
require.NoError(t, err)
assert.Len(t, results, 0)
})
}
// TestDataPermission_CrossShopIsolation 测试跨店铺数据隔离
func TestDataPermission_CrossShopIsolation(t *testing.T) {
store, cleanup := setupTestDB(t)
defer cleanup()
ctx := context.Background()
db := store.DB()
// 创建两个不同店铺的账号
shopID100 := uint(100)
accountA := &model.Account{
Username: "user_shop100",
Phone: "13800000001",
Password: "hashed_password",
UserType: constants.UserTypePlatform,
ShopID: &shopID100,
Status: constants.StatusEnabled,
Creator: 1,
Updater: 1,
}
require.NoError(t, db.Create(accountA).Error)
shopID200 := uint(200)
accountB := &model.Account{
Username: "user_shop200",
Phone: "13800000002",
Password: "hashed_password",
UserType: constants.UserTypePlatform,
ShopID: &shopID200,
Status: constants.StatusEnabled,
Creator: 1,
Updater: 1,
}
require.NoError(t, db.Create(accountB).Error)
// 创建测试数据表
type TestData struct {
ID uint `gorm:"primarykey"`
Name string
OwnerID uint
ShopID uint
}
require.NoError(t, db.AutoMigrate(&TestData{}))
// 插入不同店铺的数据
testData := []TestData{
{Name: "data_shop100_1", OwnerID: accountA.ID, ShopID: 100},
{Name: "data_shop100_2", OwnerID: accountA.ID, ShopID: 100},
{Name: "data_shop200_1", OwnerID: accountB.ID, ShopID: 200},
{Name: "data_shop200_2", OwnerID: accountB.ID, ShopID: 200},
}
require.NoError(t, db.Create(&testData).Error)
// 创建 AccountStore
accountStore := postgres.NewAccountStore(db, nil)
t.Run("店铺 100 用户只能看到店铺 100 的数据", func(t *testing.T) {
ctxWithA := middleware.SetUserContext(ctx, accountA.ID, constants.UserTypePlatform, 100)
var results []TestData
err := db.WithContext(ctxWithA).
Scopes(postgres.DataPermissionScope(ctxWithA, accountStore)).
Find(&results).Error
require.NoError(t, err)
assert.Len(t, results, 2)
for _, r := range results {
assert.Equal(t, uint(100), r.ShopID)
}
})
t.Run("店铺 200 用户只能看到店铺 200 的数据", func(t *testing.T) {
ctxWithB := middleware.SetUserContext(ctx, accountB.ID, constants.UserTypePlatform, 200)
var results []TestData
err := db.WithContext(ctxWithB).
Scopes(postgres.DataPermissionScope(ctxWithB, accountStore)).
Find(&results).Error
require.NoError(t, err)
assert.Len(t, results, 2)
for _, r := range results {
assert.Equal(t, uint(200), r.ShopID)
}
})
t.Run("店铺 100 用户看不到店铺 200 的数据", func(t *testing.T) {
ctxWithA := middleware.SetUserContext(ctx, accountA.ID, constants.UserTypePlatform, 100)
var results []TestData
err := db.WithContext(ctxWithA).
Scopes(postgres.DataPermissionScope(ctxWithA, accountStore)).
Where("shop_id = ?", 200). // 尝试查询店铺 200 的数据
Find(&results).Error
require.NoError(t, err)
assert.Len(t, results, 0, "不应该看到其他店铺的数据")
})
}
// TestDataPermission_RootUserBypass 测试 root 用户跳过数据权限过滤
func TestDataPermission_RootUserBypass(t *testing.T) {
store, cleanup := setupTestDB(t)
defer cleanup()
ctx := context.Background()
db := store.DB()
// 创建 root 用户
rootUser := &model.Account{
Username: "root_user",
Phone: "13800000000",
Password: "hashed_password",
UserType: constants.UserTypeRoot,
Status: constants.StatusEnabled,
Creator: 1,
Updater: 1,
}
require.NoError(t, db.Create(rootUser).Error)
// 创建测试数据表
type TestData struct {
ID uint `gorm:"primarykey"`
Name string
OwnerID uint
ShopID uint
}
require.NoError(t, db.AutoMigrate(&TestData{}))
// 插入不同店铺、不同用户的数据
testData := []TestData{
{Name: "data_1", OwnerID: 1, ShopID: 100},
{Name: "data_2", OwnerID: 2, ShopID: 200},
{Name: "data_3", OwnerID: 3, ShopID: 300},
{Name: "data_4", OwnerID: 4, ShopID: 400},
}
require.NoError(t, db.Create(&testData).Error)
// 创建 AccountStore
accountStore := postgres.NewAccountStore(db, nil)
t.Run("root 用户可以看到所有数据", func(t *testing.T) {
ctxWithRoot := middleware.SetUserContext(ctx, rootUser.ID, constants.UserTypeRoot, 100)
var results []TestData
err := db.WithContext(ctxWithRoot).
Scopes(postgres.DataPermissionScope(ctxWithRoot, accountStore)).
Find(&results).Error
require.NoError(t, err)
assert.Len(t, results, 4, "root 用户应该看到所有数据")
})
}