check_rbac.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package interceptor
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "github.com/xinliangnote/go-gin-api/configs"
  6. "github.com/xinliangnote/go-gin-api/internal/code"
  7. "github.com/xinliangnote/go-gin-api/internal/pkg/core"
  8. "github.com/xinliangnote/go-gin-api/internal/repository/redis"
  9. "github.com/xinliangnote/go-gin-api/internal/services/admin"
  10. "github.com/xinliangnote/go-gin-api/pkg/errors"
  11. "github.com/xinliangnote/go-gin-api/pkg/urltable"
  12. )
  13. func (i *interceptor) CheckRBAC() core.HandlerFunc {
  14. return func(c core.Context) {
  15. token := c.GetHeader("Token")
  16. if token == "" {
  17. c.AbortWithError(core.Error(
  18. http.StatusUnauthorized,
  19. code.AuthorizationError,
  20. code.Text(code.AuthorizationError)).WithError(errors.New("Header 中缺少 Token 参数")),
  21. )
  22. return
  23. }
  24. if !i.cache.Exists(configs.RedisKeyPrefixLoginUser + token) {
  25. c.AbortWithError(core.Error(
  26. http.StatusUnauthorized,
  27. code.CacheGetError,
  28. code.Text(code.CacheGetError)).WithError(errors.New("请先登录")),
  29. )
  30. return
  31. }
  32. if !i.cache.Exists(configs.RedisKeyPrefixLoginUser + token + ":action") {
  33. c.AbortWithError(core.Error(
  34. http.StatusUnauthorized,
  35. code.CacheGetError,
  36. code.Text(code.CacheGetError)).WithError(errors.New("当前账号未配置 RBAC 权限")),
  37. )
  38. return
  39. }
  40. actionData, err := i.cache.Get(configs.RedisKeyPrefixLoginUser+token+":action", redis.WithTrace(c.Trace()))
  41. if err != nil {
  42. c.AbortWithError(core.Error(
  43. http.StatusUnauthorized,
  44. code.CacheGetError,
  45. code.Text(code.CacheGetError)).WithError(err),
  46. )
  47. return
  48. }
  49. var actions []admin.MyActionData
  50. err = json.Unmarshal([]byte(actionData), &actions)
  51. if err != nil {
  52. c.AbortWithError(core.Error(
  53. http.StatusUnauthorized,
  54. code.AuthorizationError,
  55. code.Text(code.AuthorizationError)).WithError(err),
  56. )
  57. return
  58. }
  59. if len(actions) > 0 {
  60. table := urltable.NewTable()
  61. for _, v := range actions {
  62. _ = table.Append(v.Method + v.Api)
  63. }
  64. if pattern, _ := table.Mapping(c.Method() + c.Path()); pattern == "" {
  65. c.AbortWithError(core.Error(
  66. http.StatusBadRequest,
  67. code.RBACError,
  68. code.Text(code.RBACError)).WithError(errors.New(c.Method() + c.Path() + " 未进行 RBAC 授权")),
  69. )
  70. return
  71. }
  72. }
  73. }
  74. }