permission.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package middleware
  2. import (
  3. "github.com/casbin/casbin/v2/util"
  4. "net/http"
  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. for _, i := range CasbinExclude {
  27. if util.KeyMatch2(c.Request.URL.Path, i.Url) && c.Request.Method == i.Method {
  28. casbinExclude = true
  29. break
  30. }
  31. }
  32. if casbinExclude {
  33. log.Infof("Casbin exclusion, no validation method:%s path:%s", c.Request.Method, c.Request.URL.Path)
  34. c.Next()
  35. return
  36. }
  37. res, err = e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method)
  38. if err != nil {
  39. log.Errorf("AuthCheckRole error:%s method:%s path:%s", err, c.Request.Method, c.Request.URL.Path)
  40. response.Error(c, 500, err, "")
  41. return
  42. }
  43. if res {
  44. log.Infof("isTrue: %v role: %s method: %s path: %s", res, v["rolekey"], c.Request.Method, c.Request.URL.Path)
  45. c.Next()
  46. } else {
  47. log.Warnf("isTrue: %v role: %s method: %s path: %s message: %s", res, v["rolekey"], c.Request.Method, c.Request.URL.Path, "当前request无权限,请管理员确认!")
  48. c.JSON(http.StatusOK, gin.H{
  49. "code": 403,
  50. "msg": "对不起,您没有该接口访问权限,请联系管理员",
  51. })
  52. c.Abort()
  53. return
  54. }
  55. }
  56. }