sysUserPermModel.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package userperm
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "perms-system-server/internal/consts"
  7. "github.com/zeromicro/go-zero/core/stores/cache"
  8. "github.com/zeromicro/go-zero/core/stores/sqlx"
  9. )
  10. var _ SysUserPermModel = (*customSysUserPermModel)(nil)
  11. type (
  12. SysUserPermModel interface {
  13. sysUserPermModel
  14. FindPermIdsByUserIdAndEffectForProduct(ctx context.Context, userId int64, effect string, productCode string) ([]int64, error)
  15. DeleteByUserIdForProductTx(ctx context.Context, session sqlx.Session, userId int64, productCode string) error
  16. }
  17. customSysUserPermModel struct {
  18. *defaultSysUserPermModel
  19. }
  20. )
  21. func NewSysUserPermModel(conn sqlx.SqlConn, c cache.CacheConf, cachePrefix string, opts ...cache.Option) SysUserPermModel {
  22. return &customSysUserPermModel{
  23. defaultSysUserPermModel: newSysUserPermModel(conn, c, cachePrefix, opts...),
  24. }
  25. }
  26. func (m *customSysUserPermModel) FindPermIdsByUserIdAndEffectForProduct(ctx context.Context, userId int64, effect string, productCode string) ([]int64, error) {
  27. var ids []int64
  28. query := fmt.Sprintf(
  29. "SELECT up.`permId` FROM %s up INNER JOIN `sys_perm` p ON up.`permId` = p.`id` WHERE up.`userId` = ? AND up.`effect` = ? AND p.`productCode` = ? AND p.`status` = ?",
  30. m.table)
  31. if err := m.QueryRowsNoCacheCtx(ctx, &ids, query, userId, effect, productCode, consts.StatusEnabled); err != nil {
  32. return nil, err
  33. }
  34. return ids, nil
  35. }
  36. func (m *customSysUserPermModel) DeleteByUserIdForProductTx(ctx context.Context, session sqlx.Session, userId int64, productCode string) error {
  37. var list []*SysUserPerm
  38. findQuery := fmt.Sprintf("SELECT %s FROM %s WHERE `userId` = ? AND `permId` IN (SELECT `id` FROM `sys_perm` WHERE `productCode` = ?) FOR UPDATE", sysUserPermRows, m.table)
  39. if err := session.QueryRowsCtx(ctx, &list, findQuery, userId, productCode); err != nil {
  40. return err
  41. }
  42. if len(list) == 0 {
  43. return nil
  44. }
  45. keys := make([]string, 0, len(list)*2)
  46. for _, data := range list {
  47. keys = append(keys,
  48. fmt.Sprintf("%s%v", cacheSysUserPermIdPrefix, data.Id),
  49. fmt.Sprintf("%s%v:%v", cacheSysUserPermUserIdPermIdPrefix, data.UserId, data.PermId),
  50. )
  51. }
  52. _, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (sql.Result, error) {
  53. query := fmt.Sprintf("DELETE FROM %s WHERE `userId` = ? AND `permId` IN (SELECT `id` FROM `sys_perm` WHERE `productCode` = ?)", m.table)
  54. return session.ExecCtx(ctx, query, userId, productCode)
  55. }, keys...)
  56. return err
  57. }