add_group.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package rbac
  2. import (
  3. "context"
  4. "cp-organization-management/errors"
  5. "cp-organization-management/impl/v1/common"
  6. "cp-organization-management/model"
  7. pb_v1 "cp-organization-management/pb/v1"
  8. "cp-organization-management/utils"
  9. "encoding/json"
  10. "fmt"
  11. "github.com/jaryhe/gopkgs/database"
  12. "github.com/jaryhe/gopkgs/logger"
  13. "github.com/jinzhu/gorm"
  14. "go.uber.org/zap"
  15. "google.golang.org/grpc/status"
  16. "strings"
  17. )
  18. func RbacGroupAdd(ctx context.Context, req *pb_v1.RbacGroupAddRequest) (reply *pb_v1.RbacGroupAddReply, err error) {
  19. reply = &pb_v1.RbacGroupAddReply{}
  20. // 捕获各个task中的异常并返回给调用者
  21. defer func() {
  22. if r := recover(); r != nil {
  23. err = fmt.Errorf("%+v", r)
  24. e := &status.Status{}
  25. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  26. logger.Error("err",
  27. zap.String("system_err", err.Error()),
  28. zap.Stack("stacktrace"))
  29. }
  30. }
  31. }()
  32. if req.OrganizationCode == "" || req.NodeList == "" || req.Name == "" || req.Uid == 0{
  33. return nil, errors.ParamsError
  34. }
  35. // 检查角色名
  36. dbname := utils.GetDbName(req.OrganizationCode)
  37. loginUser, err := common.GetUserBaseInfo(req.Uid, dbname)
  38. if err != nil {
  39. return nil, err
  40. }
  41. superGroupId, err := common.GetSuperGroup(dbname)
  42. if err != nil {
  43. return nil, err
  44. }
  45. if superGroupId != loginUser.GroupId {
  46. return nil, errors.NotSuperGroupError
  47. }
  48. p := model.NewRbacGroup(dbname)
  49. where := map[string]interface{}{
  50. "name":req.Name,
  51. }
  52. err = p.Find(database.DB(), where)
  53. if err != nil && err != gorm.ErrRecordNotFound {
  54. return nil, errors.DataBaseError
  55. }
  56. if p.Id > 0 {
  57. return nil, status.Error(10003, "角色名已存在")
  58. }
  59. // 检查node
  60. node := model.NewRbacNode(dbname)
  61. nodeList := []model.RbacNode{}
  62. err = node.QueryAll(database.DB(), nil, &nodeList)
  63. if err != nil {
  64. return nil, errors.DataBaseError
  65. }
  66. m := map[string]bool{}
  67. for _, v := range nodeList {
  68. m[fmt.Sprintf("%d", v.Id)] = true
  69. }
  70. array := strings.Split(req.NodeList, ",")
  71. for _, v := range array {
  72. if _, ok := m[v]; !ok {
  73. return nil, status.Error(10003, fmt.Sprintf("节点(%s)不存在", v))
  74. }
  75. }
  76. // 插入数据
  77. p.NodeList = req.NodeList
  78. p.Name = req.Name
  79. err = p.Insert(database.DB())
  80. if err != nil {
  81. return nil, errors.DataBaseError
  82. }
  83. reply.Id = p.Id
  84. return reply, nil
  85. }