45 lines
1.3 KiB
Go
45 lines
1.3 KiB
Go
package logic
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
sysModel "sundynix-micro-go/app/system/model"
|
|
"sundynix-micro-go/app/system/rpc/internal/svc"
|
|
"sundynix-micro-go/app/system/rpc/system"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type AssignUserRolesLogic struct {
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
logx.Logger
|
|
}
|
|
|
|
func NewAssignUserRolesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AssignUserRolesLogic {
|
|
return &AssignUserRolesLogic{ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx)}
|
|
}
|
|
|
|
// AssignUserRoles 给用户授权角色(全量替换)
|
|
func (l *AssignUserRolesLogic) AssignUserRoles(in *system.AssignUserRolesReq) (*system.CommonResp, error) {
|
|
err := l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
|
|
// 先清除旧的角色关联
|
|
if err := tx.Where("user_id = ?", in.UserId).Delete(&sysModel.SundynixUserRole{}).Error; err != nil {
|
|
return fmt.Errorf("清除角色关联失败: %w", err)
|
|
}
|
|
// 重新批量写入
|
|
for _, rid := range in.RoleIds {
|
|
if err := tx.Create(&sysModel.SundynixUserRole{UserID: in.UserId, RoleID: rid}).Error; err != nil {
|
|
return fmt.Errorf("关联角色失败: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &system.CommonResp{Code: 200, Msg: "success"}, nil
|
|
}
|