2
0

authorities_menus.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package system
  2. import (
  3. "context"
  4. sysModel "github.com/flipped-aurora/gin-vue-admin/server/model/system"
  5. "github.com/flipped-aurora/gin-vue-admin/server/service/system"
  6. "github.com/pkg/errors"
  7. "gorm.io/gorm"
  8. )
  9. const initOrderMenuAuthority = initOrderMenu + initOrderAuthority
  10. type initMenuAuthority struct{}
  11. // auto run
  12. func init() {
  13. system.RegisterInit(initOrderMenuAuthority, &initMenuAuthority{})
  14. }
  15. func (i *initMenuAuthority) MigrateTable(ctx context.Context) (context.Context, error) {
  16. return ctx, nil // do nothing
  17. }
  18. func (i *initMenuAuthority) TableCreated(ctx context.Context) bool {
  19. return false // always replace
  20. }
  21. func (i *initMenuAuthority) InitializerName() string {
  22. return "sys_menu_authorities"
  23. }
  24. func (i *initMenuAuthority) InitializeData(ctx context.Context) (next context.Context, err error) {
  25. db, ok := ctx.Value("db").(*gorm.DB)
  26. if !ok {
  27. return ctx, system.ErrMissingDBContext
  28. }
  29. initAuth := &initAuthority{}
  30. authorities, ok := ctx.Value(initAuth.InitializerName()).([]sysModel.SysAuthority)
  31. if !ok {
  32. return ctx, errors.Wrap(system.ErrMissingDependentContext, "创建 [菜单-权限] 关联失败, 未找到权限表初始化数据")
  33. }
  34. menus, ok := ctx.Value(new(initMenu).InitializerName()).([]sysModel.SysBaseMenu)
  35. if !ok {
  36. return next, errors.Wrap(errors.New(""), "创建 [菜单-权限] 关联失败, 未找到菜单表初始化数据")
  37. }
  38. next = ctx
  39. // 888
  40. if err = db.Model(&authorities[0]).Association("SysBaseMenus").Replace(menus); err != nil {
  41. return next, err
  42. }
  43. // 8881
  44. menu8881 := menus[:2]
  45. menu8881 = append(menu8881, menus[7])
  46. if err = db.Model(&authorities[1]).Association("SysBaseMenus").Replace(menu8881); err != nil {
  47. return next, err
  48. }
  49. // 9528
  50. if err = db.Model(&authorities[2]).Association("SysBaseMenus").Replace(menus[:11]); err != nil {
  51. return next, err
  52. }
  53. if err = db.Model(&authorities[2]).Association("SysBaseMenus").Append(menus[12:17]); err != nil {
  54. return next, err
  55. }
  56. return next, nil
  57. }
  58. func (i *initMenuAuthority) DataInserted(ctx context.Context) bool {
  59. db, ok := ctx.Value("db").(*gorm.DB)
  60. if !ok {
  61. return false
  62. }
  63. auth := &sysModel.SysAuthority{}
  64. if ret := db.Model(auth).
  65. Where("authority_id = ?", 9528).Preload("SysBaseMenus").Find(auth); ret != nil {
  66. if ret.Error != nil {
  67. return false
  68. }
  69. return len(auth.SysBaseMenus) > 0
  70. }
  71. return false
  72. }