permission.go 1.9 KB

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