package pub import ( "context" "time" "perms-system-server/internal/consts" permModel "perms-system-server/internal/model/perm" "perms-system-server/internal/response" "perms-system-server/internal/svc" "perms-system-server/internal/types" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/stores/sqlx" "golang.org/x/crypto/bcrypt" ) type SyncPermsLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewSyncPermsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SyncPermsLogic { return &SyncPermsLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *SyncPermsLogic) SyncPerms(req *types.SyncPermsReq) (resp *types.SyncPermsResp, err error) { product, err := l.svcCtx.SysProductModel.FindOneByAppKey(l.ctx, req.AppKey) if err != nil { return nil, response.ErrUnauthorized("无效的appKey") } if err := bcrypt.CompareHashAndPassword([]byte(product.AppSecret), []byte(req.AppSecret)); err != nil { return nil, response.ErrUnauthorized("appSecret验证失败") } if product.Status != consts.StatusEnabled { return nil, response.ErrForbidden("产品已被禁用") } existingMap, err := l.svcCtx.SysPermModel.FindMapByProductCode(l.ctx, product.Code) if err != nil { return nil, err } now := time.Now().Unix() var added, updated int64 codes := make([]string, 0, len(req.Perms)) var toInsert []*permModel.SysPerm var toUpdate []*permModel.SysPerm seen := make(map[string]bool, len(req.Perms)) for _, item := range req.Perms { if seen[item.Code] { continue } seen[item.Code] = true codes = append(codes, item.Code) existing, ok := existingMap[item.Code] if !ok { toInsert = append(toInsert, &permModel.SysPerm{ ProductCode: product.Code, Name: item.Name, Code: item.Code, Remark: item.Remark, Status: consts.StatusEnabled, CreateTime: now, UpdateTime: now, }) added++ continue } if existing.Name != item.Name || existing.Remark != item.Remark || existing.Status != consts.StatusEnabled { existing.Name = item.Name existing.Remark = item.Remark existing.Status = consts.StatusEnabled existing.UpdateTime = now toUpdate = append(toUpdate, existing) updated++ } } var disabled int64 if err := l.svcCtx.SysPermModel.TransactCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error { if len(toInsert) > 0 { if err := l.svcCtx.SysPermModel.BatchInsertWithTx(ctx, session, toInsert); err != nil { return err } } if len(toUpdate) > 0 { if err := l.svcCtx.SysPermModel.BatchUpdateWithTx(ctx, session, toUpdate); err != nil { return err } } var err error disabled, err = l.svcCtx.SysPermModel.DisableNotInCodesWithTx(ctx, session, product.Code, codes, now) return err }); err != nil { return nil, err } if added > 0 || updated > 0 || disabled > 0 { l.svcCtx.UserDetailsLoader.CleanByProduct(l.ctx, product.Code) } return &types.SyncPermsResp{ Added: added, Updated: updated, Disabled: disabled, }, nil }