2023-08-30 09:28:21 +08:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
"joylink.club/bj-rtsts-server/db/model"
|
|
|
|
"joylink.club/bj-rtsts-server/dto"
|
|
|
|
"joylink.club/bj-rtsts-server/service"
|
|
|
|
)
|
|
|
|
|
|
|
|
// 用户权限缓存
|
|
|
|
var userAuthPathMap = make(map[int32]*dto.AuthUserStorageDto)
|
|
|
|
|
|
|
|
var PermissMiddleware = permissionMiddleware()
|
|
|
|
|
|
|
|
// 权限验证信息0
|
|
|
|
func permissionMiddleware() gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
user, _ := c.Get(IdentityKey)
|
|
|
|
if user == nil { // 用户未登录
|
|
|
|
c.Next()
|
|
|
|
} else {
|
|
|
|
uid := user.(*model.User).ID
|
|
|
|
zap.S().Debugf("获取用户ID:%d", uid)
|
|
|
|
userAuth := userAuthPathMap[uid]
|
|
|
|
if userAuth == nil {
|
|
|
|
userAuthPathMap[uid] = service.QueryUserAuthApiPath(uid)
|
|
|
|
userAuth = userAuthPathMap[uid]
|
|
|
|
}
|
|
|
|
if userAuth.IsAdmin { // 用户是超级管理员
|
|
|
|
c.Next()
|
|
|
|
} else {
|
|
|
|
path, method := c.Request.URL.Path, c.Request.Method
|
|
|
|
zap.S().Debugf("获取请求路径:%s, 方法:%s", path, method)
|
|
|
|
isVaild := validateUserPath(path, method, userAuth.AuthPaths)
|
|
|
|
if isVaild { // 用户有权限
|
|
|
|
c.Next()
|
|
|
|
} else {
|
|
|
|
c.JSON(http.StatusUnauthorized, "无权限访问")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 验证路径
|
|
|
|
func validateUserPath(path, method string, paths []*dto.AuthPath) bool {
|
|
|
|
reqPathArr := strings.Split(path, "/")
|
|
|
|
for _, p := range paths {
|
|
|
|
if p.Method == "*" || p.Method == method {
|
|
|
|
authPathArr := strings.Split(p.Path, "/")
|
|
|
|
isValid := true
|
|
|
|
for i, p := range reqPathArr {
|
|
|
|
if p == "{id}" || p == ":id" || p == authPathArr[i] {
|
|
|
|
continue
|
|
|
|
} else if authPathArr[i] == "*" {
|
|
|
|
isValid = true
|
|
|
|
break
|
|
|
|
} else {
|
|
|
|
isValid = false
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if isValid {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// 重新登录时移除权限
|
2023-08-30 13:25:57 +08:00
|
|
|
func ClearUserPermission(userId int32) {
|
2023-08-30 09:28:21 +08:00
|
|
|
delete(userAuthPathMap, userId)
|
|
|
|
}
|
2023-08-30 13:25:57 +08:00
|
|
|
|
|
|
|
// 修改角色后清理用户权限
|
|
|
|
func ClearUserPermissionByRid(roleId int32) {
|
|
|
|
uids := []int32{}
|
|
|
|
for uid, u := range userAuthPathMap {
|
|
|
|
for _, r := range u.RoleIds {
|
|
|
|
if r == roleId {
|
|
|
|
uids = append(uids, uid)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(uids) > 0 {
|
|
|
|
for _, uid := range uids {
|
|
|
|
ClearUserPermission(uid)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|