2021-08-20 14:59:13 +08:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"github.com/gin-gonic/gin"
|
2021-08-22 00:13:00 +08:00
|
|
|
"goweb/core"
|
|
|
|
. "goweb/global"
|
2021-08-20 14:59:13 +08:00
|
|
|
"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()
|
|
|
|
}
|
|
|
|
}
|