collector.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package permlib
  2. import (
  3. "strings"
  4. "code.clickto.dev/weiym/permlib/pb"
  5. )
  6. func (e *Engine) collectPerms() []*pb.PermItem {
  7. seen := make(map[string]bool)
  8. var perms []*pb.PermItem
  9. add := func(code, name string) {
  10. if seen[code] {
  11. return
  12. }
  13. seen[code] = true
  14. if name == "" {
  15. name = generatePermName(code)
  16. }
  17. perms = append(perms, &pb.PermItem{Code: code, Name: name})
  18. }
  19. for _, decl := range e.staticPerms {
  20. add(decl.Code, decl.Name)
  21. dataCode := apiToDataCode(decl.Code)
  22. if dataCode != "" {
  23. add(dataCode, "")
  24. }
  25. }
  26. return perms
  27. }
  28. func apiToDataCode(apiCode string) string {
  29. if !strings.HasPrefix(apiCode, "api:") {
  30. return ""
  31. }
  32. return "data:" + apiCode[4:]
  33. }
  34. func generatePermName(code string) string {
  35. parts := strings.Split(code, ":")
  36. if len(parts) < 2 {
  37. return code
  38. }
  39. actionMap := map[string]string{
  40. "read": "读取",
  41. "write": "写入",
  42. "create": "创建",
  43. "update": "更新",
  44. "delete": "删除",
  45. "list": "列表",
  46. "detail": "详情",
  47. }
  48. capitalize := func(s string) string {
  49. if len(s) == 0 {
  50. return s
  51. }
  52. return strings.ToUpper(s[:1]) + s[1:]
  53. }
  54. // 字段权限:data:model:field:read|write → "{Model} {field} 字段 [读取|写入]"
  55. if parts[0] == "data" && len(parts) == 4 {
  56. action := actionMap[parts[3]]
  57. if action == "" {
  58. action = parts[3]
  59. }
  60. return capitalize(parts[1]) + " " + parts[2] + "字段 " + action
  61. }
  62. // 接口/数据权限:api:model:action 或 data:model:action
  63. var result []string
  64. for i := 1; i < len(parts); i++ {
  65. p := parts[i]
  66. if mapped, ok := actionMap[p]; ok {
  67. result = append(result, mapped)
  68. } else {
  69. result = append(result, capitalize(p))
  70. }
  71. }
  72. return strings.Join(result, " ")
  73. }