fix: 角色删除前校验分配情况,禁止删除使用中的角色

角色被删除后,其关联的账号-角色记录未清理,导致 CountByAccountID
统计到孤儿记录,使被分配该角色的账号无法重新分配新角色。

修复方案:删除角色前检查 tb_account_role 和 tb_shop_role,
若仍有账号或店铺持有该角色则返回 1028 错误,强制管理员显式
解除所有分配后再删除,保证数据一致性与审计完整性。
This commit is contained in:
2026-04-07 17:23:49 +08:00
parent 434a8b0349
commit 7e489a19fb
5 changed files with 50 additions and 6 deletions

View File

@@ -23,14 +23,18 @@ type Service struct {
roleStore *postgres.RoleStore
permissionStore *postgres.PermissionStore
rolePermissionStore *postgres.RolePermissionStore
accountRoleStore *postgres.AccountRoleStore
shopRoleStore *postgres.ShopRoleStore
}
// New 创建角色服务
func New(roleStore *postgres.RoleStore, permissionStore *postgres.PermissionStore, rolePermissionStore *postgres.RolePermissionStore) *Service {
func New(roleStore *postgres.RoleStore, permissionStore *postgres.PermissionStore, rolePermissionStore *postgres.RolePermissionStore, accountRoleStore *postgres.AccountRoleStore, shopRoleStore *postgres.ShopRoleStore) *Service {
return &Service{
roleStore: roleStore,
permissionStore: permissionStore,
rolePermissionStore: rolePermissionStore,
accountRoleStore: accountRoleStore,
shopRoleStore: shopRoleStore,
}
}
@@ -126,7 +130,6 @@ func (s *Service) Update(ctx context.Context, id uint, req *dto.UpdateRoleReques
// Delete 软删除角色
func (s *Service) Delete(ctx context.Context, id uint) error {
// 检查角色存在
_, err := s.roleStore.GetByID(ctx, id)
if err != nil {
if err == gorm.ErrRecordNotFound {
@@ -135,6 +138,20 @@ func (s *Service) Delete(ctx context.Context, id uint) error {
return errors.Wrap(errors.CodeInternalError, err, "获取角色失败")
}
accountCount, err := s.accountRoleStore.CountByRoleID(ctx, id)
if err != nil {
return errors.Wrap(errors.CodeInternalError, err, "检查角色分配情况失败")
}
shopCount, err := s.shopRoleStore.CountByRoleID(ctx, id)
if err != nil {
return errors.Wrap(errors.CodeInternalError, err, "检查角色分配情况失败")
}
if accountCount > 0 || shopCount > 0 {
return errors.New(errors.CodeRoleInUse, fmt.Sprintf("该角色已分配给 %d 个账号、%d 个店铺,请先移除相关分配后再删除", accountCount, shopCount))
}
if err := s.roleStore.Delete(ctx, id); err != nil {
return errors.Wrap(errors.CodeInternalError, err, "删除角色失败")
}