permission.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package middleware
  2. import (
  3. "net/http"
  4. "github.com/casbin/casbin/v2/util"
  5. "github.com/gin-gonic/gin"
  6. "github.com/go-admin-team/go-admin-core/sdk"
  7. "github.com/go-admin-team/go-admin-core/sdk/api"
  8. "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
  9. "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
  10. )
  11. // AuthCheckRole 权限检查中间件
  12. func AuthCheckRole() gin.HandlerFunc {
  13. return func(c *gin.Context) {
  14. log := api.GetRequestLogger(c)
  15. data, _ := c.Get(jwtauth.JwtPayloadKey)
  16. v := data.(jwtauth.MapClaims)
  17. e := sdk.Runtime.GetCasbinKey(c.Request.Host)
  18. var res, casbinExclude bool
  19. var err error
  20. //检查权限
  21. if v["rolekey"] == "admin" {
  22. res = true
  23. c.Next()
  24. return
  25. }
  26. //TODO: 临时使用,需要调整sys_api对接口的管理
  27. if v["rolekey"] == "normal" {
  28. res = true
  29. c.Next()
  30. return
  31. }
  32. if v["rolekey"] == "abnormal" {
  33. res = true
  34. c.Next()
  35. return
  36. }
  37. for _, i := range CasbinExclude {
  38. if util.KeyMatch2(c.Request.URL.Path, i.Url) && c.Request.Method == i.Method {
  39. casbinExclude = true
  40. break
  41. }
  42. }
  43. if casbinExclude {
  44. log.Infof("Casbin exclusion, no validation method:%s path:%s", c.Request.Method, c.Request.URL.Path)
  45. c.Next()
  46. return
  47. }
  48. res, err = e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method)
  49. if err != nil {
  50. log.Errorf("AuthCheckRole error:%s method:%s path:%s", err, c.Request.Method, c.Request.URL.Path)
  51. response.Error(c, 500, err, "")
  52. return
  53. }
  54. if res {
  55. log.Infof("isTrue: %v role: %s method: %s path: %s", res, v["rolekey"], c.Request.Method, c.Request.URL.Path)
  56. c.Next()
  57. } else {
  58. log.Warnf("isTrue: %v role: %s method: %s path: %s message: %s", res, v["rolekey"], c.Request.Method, c.Request.URL.Path, "当前request无权限,请管理员确认!")
  59. c.JSON(http.StatusOK, gin.H{
  60. "code": 403,
  61. "msg": "对不起,您没有该接口访问权限,请联系管理员",
  62. })
  63. c.Abort()
  64. return
  65. }
  66. }
  67. }