mengstack-api/internal/modules/rbac/infrastructure/role_repo.go
MengStack Dev f8c374a624 feat(rbac): M3 RBAC 权限模型完整实现
- 4 表设计: permissions, roles, role_permissions(m2m), user_roles
- 多租户隔离: 角色和用户角色分配按 tenant_id 隔离
- 权限并集: 多角色用户取权限并集,无继承
- 系统角色保护: is_system 角色不可修改/删除
- 种子数据: 7 个默认权限 + 3 个系统角色(super_admin/tenant_admin/member)
- 权限中间件: RequirePermission 支持按路由粒度控制
- API 路由: /api/v1/rbac/ 下完整 CRUD 端点
- fx 注册: RBAC Module 集成到 app.go
2026-10-03 00:54:26 +08:00

66 lines
1.8 KiB
Go

package infrastructure
import (
"context"
"mengstack/internal/modules/rbac/domain"
"gorm.io/gorm"
)
type roleRepo struct {
db *gorm.DB
}
func NewRoleRepository(db *gorm.DB) domain.RoleRepository {
return &roleRepo{db: db}
}
func (r *roleRepo) Create(ctx context.Context, role *domain.Role) error {
return r.db.WithContext(ctx).Create(role).Error
}
func (r *roleRepo) FindByID(ctx context.Context, tenantID string, id uint) (*domain.Role, error) {
var role domain.Role
err := r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).First(&role).Error
return &role, err
}
func (r *roleRepo) FindByIDWithPermissions(ctx context.Context, tenantID string, id uint) (*domain.Role, error) {
var role domain.Role
err := r.db.WithContext(ctx).
Preload("Permissions").
Where("roles.id = ? AND roles.tenant_id = ?", id, tenantID).
First(&role).Error
return &role, err
}
func (r *roleRepo) FindByTenant(ctx context.Context, tenantID string) ([]domain.Role, error) {
var roles []domain.Role
err := r.db.WithContext(ctx).
Preload("Permissions").
Where("tenant_id = ?", tenantID).
Order("name").
Find(&roles).Error
return roles, err
}
func (r *roleRepo) Update(ctx context.Context, role *domain.Role) error {
return r.db.WithContext(ctx).Save(role).Error
}
func (r *roleRepo) Delete(ctx context.Context, tenantID string, id uint) error {
return r.db.WithContext(ctx).
Where("id = ? AND tenant_id = ?", id, tenantID).
Delete(&domain.Role{}).Error
}
func (r *roleRepo) SetPermissions(ctx context.Context, roleID uint, permIDs []uint) error {
role := &domain.Role{ID: roleID}
perms := make([]domain.Permission, len(permIDs))
for i, id := range permIDs {
perms[i] = domain.Permission{ID: id}
}
return r.db.WithContext(ctx).Model(role).Association("Permissions").Replace(perms)
}