48 lines
946 B
Go
48 lines
946 B
Go
|
package middleware
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"github.com/gin-gonic/gin"
|
||
|
"go_api_tmpl/core"
|
||
|
. "go_api_tmpl/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()
|
||
|
}
|
||
|
}
|