permission.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. identity, _ := v["identity"]
  25. var userId float64
  26. if identity != nil {
  27. if f, ok := identity.(float64); ok {
  28. userId = f
  29. }
  30. }
  31. if rolekey == "admin" || userId == 1 {
  32. res = true
  33. c.Next()
  34. return
  35. }
  36. for _, i := range CasbinExclude {
  37. if util.KeyMatch2(c.Request.URL.Path, i.Url) && c.Request.Method == i.Method {
  38. casbinExclude = true
  39. break
  40. }
  41. }
  42. if casbinExclude {
  43. log.Infof("Casbin exclusion, no validation method:%s path:%s", c.Request.Method, c.Request.URL.Path)
  44. c.Next()
  45. return
  46. }
  47. enforceSub := rolekey
  48. if postCode, ok := v["postCode"]; ok && postCode != nil && postCode.(string) != "" {
  49. enforceSub = postCode.(string)
  50. }
  51. res, err = mycasbin.EnforceRoute(enforceSub, "", c.Request, e)
  52. if err != nil {
  53. log.Errorf("AuthCheckRole error: %s method:%s path:%s", err, c.Request.Method, c.Request.URL.Path)
  54. response.Error(c, 500, err, err.Error())
  55. return
  56. }
  57. if res {
  58. log.Infof("isTrue: %v role: %s method: %s path: %s", res, v["roleKey"], c.Request.Method, c.Request.URL.Path)
  59. c.Next()
  60. return
  61. } else {
  62. log.Warnf("isFalse: %v role: %s method: %s path: %s message: %s", res, v["roleKey"], c.Request.Method, c.Request.URL.Path, "当前request无权限,请管理员确认!")
  63. c.JSON(http.StatusOK, gin.H{
  64. "code": 403,
  65. "msg": "对不起,您没有该接口访问权限,请联系管理员",
  66. })
  67. c.Abort()
  68. return
  69. }
  70. }
  71. }