package middleware import ( "fmt" "github.com/gin-gonic/gin" "goweb/core" . "goweb/global" "net/http" ) // AuthorityVerify 权限验证中间件 func AuthorityVerify() gin.HandlerFunc { return func(c *gin.Context) { // 取出用户ID userId, existed := c.Get("userId") if !existed { core.R(c).FailWithMessageAndCode("请先登录", http.StatusUnauthorized) c.Abort() return } Log.Info(userId) // 从数据库加载权限规则数据 err := Enforcer.LoadPolicy() if err != nil { core.R(c).FailWithMessage("权限加载失败") c.Abort() return } // 取出Path和Method p := c.Request.URL.Path m := c.Request.Method // 验证权限 ok, err := Enforcer.Enforce(fmt.Sprint(userId), p, m) if err != nil { core.R(c).FailWithMessage("权限验证失败") c.Abort() return } if !ok { core.R(c).FailWithMessage("权限不足") c.Abort() return } c.Next() } }