role.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package permission
  2. import (
  3. log "IotAdmin/core/logger"
  4. jwtauth "IotAdmin/core/sdk/pkg/jwt-auth"
  5. "IotAdmin/core/sdk/pkg/response"
  6. "github.com/casbin/casbin/v2"
  7. "github.com/casbin/casbin/v2/util"
  8. "github.com/gin-gonic/gin"
  9. )
  10. func CheckRoleApi(c *gin.Context, v jwtauth.MapClaims, e *casbin.SyncedEnforcer) (res bool) {
  11. res = true
  12. //检查权限 角色为 admin 直接放行
  13. if v["rolekey"] == "admin" {
  14. return
  15. }
  16. url := c.Request.URL.Path
  17. if util.KeyMatch2(url, "/api/sys/*") || util.KeyMatch2(url, "/api/web/*") {
  18. return
  19. }
  20. res = false
  21. for _, i := range CasbinExclude {
  22. if util.KeyMatch2(url, i.Url) && c.Request.Method == i.Method {
  23. res = true
  24. break
  25. }
  26. }
  27. if res {
  28. log.Infof("Casbin exclusion, no validation method:%s path:%s", c.Request.Method, c.Request.URL.Path)
  29. return
  30. }
  31. res, err := e.Enforce(v["rolekey"], c.Request.URL.Path, c.Request.Method)
  32. if err != nil {
  33. log.Errorf("AuthCheckRole error:%s method:%s path:%s", err, c.Request.Method, c.Request.URL.Path)
  34. response.Error(c, 500, err, "")
  35. return false
  36. }
  37. return res
  38. }
  39. type UrlInfo struct {
  40. Url string
  41. Method string
  42. }
  43. // CasbinExclude casbin 排除的路由列表
  44. var CasbinExclude = []UrlInfo{
  45. {Url: "/", Method: "GET"},
  46. {Url: "/info", Method: "GET"},
  47. {Url: "/api/login", Method: "POST"},
  48. {Url: "/api/refresh-token", Method: "POST"},
  49. {Url: "/api/logout", Method: "POST"},
  50. {Url: "/api/captcha", Method: "POST"},
  51. {Url: "/api/metrics", Method: "GET"},
  52. {Url: "/api/health", Method: "GET"},
  53. }