2023-08-30 09:28:21 +08:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2023-10-12 10:10:23 +08:00
|
|
|
"log/slog"
|
2023-08-30 15:37:44 +08:00
|
|
|
"regexp"
|
2023-08-31 11:07:22 +08:00
|
|
|
"strings"
|
2023-08-30 09:28:21 +08:00
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"joylink.club/bj-rtsts-server/db/model"
|
|
|
|
"joylink.club/bj-rtsts-server/dto"
|
|
|
|
"joylink.club/bj-rtsts-server/service"
|
2023-10-20 15:08:47 +08:00
|
|
|
"joylink.club/bj-rtsts-server/sys_error"
|
2023-08-30 09:28:21 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
// 用户权限缓存
|
|
|
|
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()
|
2023-08-31 16:16:18 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
uid := user.(*model.User).ID
|
|
|
|
userAuth := userAuthPathMap[uid]
|
|
|
|
if userAuth == nil {
|
|
|
|
userAuthPathMap[uid] = service.QueryUserAuthApiPath(uid)
|
|
|
|
userAuth = userAuthPathMap[uid]
|
|
|
|
}
|
|
|
|
if userAuth.IsAdmin { // 用户是超级管理员
|
|
|
|
c.Next()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
path, method := c.Request.URL.Path, c.Request.Method
|
|
|
|
if validateUserPath(path, method, userAuth.AuthPaths) { // 用户有权限
|
|
|
|
c.Next()
|
|
|
|
return
|
2023-08-30 09:28:21 +08:00
|
|
|
}
|
2023-10-12 10:10:23 +08:00
|
|
|
slog.Error("无权限操作请求路径", "path", path, "method", method)
|
2023-10-20 15:08:47 +08:00
|
|
|
panic(sys_error.New("权限不足"))
|
2023-08-30 09:28:21 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// 验证路径
|
|
|
|
func validateUserPath(path, method string, paths []*dto.AuthPath) bool {
|
|
|
|
for _, p := range paths {
|
2023-08-31 16:16:18 +08:00
|
|
|
if p.Method != "*" && !strings.Contains(p.Method, method) { // 判断方法是否匹配
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if p.Path == path {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
authReg, _ := regexp.Compile(p.Path)
|
|
|
|
if authReg.MatchString(path) { // 匹配路径
|
|
|
|
return true
|
2023-08-30 09:28:21 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
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) {
|
2023-08-31 16:16:18 +08:00
|
|
|
var uids []int32
|
2023-08-30 13:25:57 +08:00
|
|
|
for uid, u := range userAuthPathMap {
|
|
|
|
for _, r := range u.RoleIds {
|
|
|
|
if r == roleId {
|
|
|
|
uids = append(uids, uid)
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-08-31 16:16:18 +08:00
|
|
|
if len(uids) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
for _, uid := range uids {
|
|
|
|
ClearUserPermission(uid)
|
2023-08-30 13:25:57 +08:00
|
|
|
}
|
|
|
|
}
|