node_list.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package rbac
  2. import (
  3. "context"
  4. "cp-organization-management/errors"
  5. "cp-organization-management/model"
  6. pb_v1 "cp-organization-management/pb/v1"
  7. "cp-organization-management/utils"
  8. "encoding/json"
  9. "fmt"
  10. "github.com/jaryhe/gopkgs/database"
  11. "github.com/jaryhe/gopkgs/logger"
  12. "github.com/jinzhu/gorm"
  13. "go.uber.org/zap"
  14. "google.golang.org/grpc/status"
  15. )
  16. func getChild(pid int64, m map[int64][]*pb_v1.RbacNodeItem) (ret []*pb_v1.RbacNodeItem) {
  17. if _, ok := m[pid]; !ok {
  18. return ret
  19. }
  20. ret = append(ret, m[pid]...)
  21. for k, v := range ret {
  22. ret[k].Childs = getChild(v.Id, m)
  23. }
  24. return ret
  25. }
  26. func NodeTree(array []model.RbacNode) (ret []*pb_v1.RbacNodeItem) {
  27. m := map[int64][]*pb_v1.RbacNodeItem{}
  28. for _, v := range array {
  29. item := pb_v1.RbacNodeItem{
  30. Id:v.Id,
  31. Pid:v.Pid,
  32. Method:v.Method,
  33. Resource:v.Resource,
  34. Object:v.Object,
  35. Router:v.Router,
  36. Name:v.Name,
  37. }
  38. m[v.Pid] = append(m[v.Pid], &item)
  39. }
  40. return getChild(0, m)
  41. }
  42. func NodeTreeSelect(array []model.RbacNode) (ret []*pb_v1.RbacNodeItem) {
  43. m := map[int64][]*pb_v1.RbacNodeItem{}
  44. for _, v := range array {
  45. item := pb_v1.RbacNodeItem{
  46. Id:v.Id,
  47. Pid:v.Pid,
  48. Method:v.Method,
  49. Resource:v.Resource,
  50. Object:v.Object,
  51. Router:v.Router,
  52. Name:v.Name,
  53. Select:true,
  54. }
  55. m[v.Pid] = append(m[v.Pid], &item)
  56. }
  57. return getChild(0, m)
  58. }
  59. func RbacNodeList(ctx context.Context, req *pb_v1.RbacNodeListRequest) (reply *pb_v1.RbacNodeListReply, err error) {
  60. reply = &pb_v1.RbacNodeListReply{}
  61. // 捕获各个task中的异常并返回给调用者
  62. defer func() {
  63. if r := recover(); r != nil {
  64. err = fmt.Errorf("%+v", r)
  65. e := &status.Status{}
  66. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  67. logger.Error("err",
  68. zap.String("system_err", err.Error()),
  69. zap.Stack("stacktrace"))
  70. }
  71. }
  72. }()
  73. if req.OrganizationCode == "" {
  74. return nil, errors.ParamsError
  75. }
  76. dbname := utils.GetDbName(req.OrganizationCode)
  77. p := model.NewRbacNode(dbname)
  78. list := []model.RbacNode{}
  79. where := map[string]interface{}{
  80. "is_super":false,
  81. }
  82. if req.IsAll {
  83. where = nil
  84. }
  85. err = p.QueryAll(database.DB(), where, &list)
  86. if err != nil {
  87. if err == gorm.ErrRecordNotFound {
  88. return reply, nil
  89. }
  90. return nil, errors.DataBaseError
  91. }
  92. reply.List = NodeTree(list)
  93. return reply, nil
  94. }