permission.go 1.8 KB

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