1.0
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"awesomeProject/internal/common"
|
||||
jwtutil "awesomeProject/pkg/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Whitelist 白名单路径(支持通配符)
|
||||
var Whitelist = []string{
|
||||
"/back/file/**",
|
||||
"/back/login",
|
||||
}
|
||||
|
||||
func CORSMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Access-Control-Allow-Methods", "*")
|
||||
c.Header("Access-Control-Allow-Headers", "*")
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func JWTMiddleware(c *gin.Context) {
|
||||
// ✅ 1. 获取请求路径
|
||||
path := c.Request.URL.Path
|
||||
if !strings.HasPrefix(path, "/back") {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
// ✅ 2. 检查是否在白名单中
|
||||
for _, rule := range Whitelist {
|
||||
if PathMatch(rule, path) {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// ✅ 3. 从 Header 中提取 Token
|
||||
tokenString := c.GetHeader("token")
|
||||
if tokenString == "" {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(401, "token无效"))
|
||||
return
|
||||
}
|
||||
|
||||
// ✅ 4. 解析并验证 Token
|
||||
claims, err := jwtutil.ParseTokenToMap(tokenString)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(401, "token无效"))
|
||||
return
|
||||
}
|
||||
|
||||
// ✅ 5. Token 有效,继续处理
|
||||
c.Set("tokenMap", claims)
|
||||
c.Next()
|
||||
}
|
||||
|
||||
// PathMatch 判断请求路径是否匹配白名单中的通配符规则
|
||||
func PathMatch(pattern, path string) bool {
|
||||
if pattern == path {
|
||||
return true
|
||||
}
|
||||
|
||||
if len(pattern) > 0 && pattern[0] == '/' {
|
||||
pattern = pattern[1:]
|
||||
}
|
||||
if len(path) > 0 && path[0] == '/' {
|
||||
path = path[1:]
|
||||
}
|
||||
|
||||
patternParts := strings.Split(pattern, "/")
|
||||
pathParts := strings.Split(path, "/")
|
||||
|
||||
if len(patternParts) > len(pathParts) {
|
||||
return false
|
||||
}
|
||||
|
||||
for i := 0; i < len(patternParts); i++ {
|
||||
p := patternParts[i]
|
||||
if p == "**" {
|
||||
// 匹配任意多级路径
|
||||
return true
|
||||
} else if p == "*" {
|
||||
// 匹配单级路径
|
||||
if i == len(patternParts)-1 {
|
||||
return true
|
||||
}
|
||||
continue
|
||||
} else if p != pathParts[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// 如果模式完全匹配路径的前缀
|
||||
return len(patternParts) == len(pathParts)
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"awesomeProject/internal/common"
|
||||
"awesomeProject/internal/models"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// AdminRoleMiddleware 管理员权限中间件
|
||||
func AdminRoleMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 获取token中的用户信息
|
||||
tokenMap, exists := c.Get("tokenMap")
|
||||
if !exists {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(401, "未授权访问"))
|
||||
return
|
||||
}
|
||||
|
||||
claims := tokenMap.(map[string]interface{})
|
||||
userIDFloat, ok := claims["user_id"].(float64)
|
||||
if !ok {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(401, "用户信息无效"))
|
||||
return
|
||||
}
|
||||
|
||||
userID := uint(userIDFloat)
|
||||
|
||||
// 查询用户信息
|
||||
var user models.User
|
||||
if err := common.GetDB().First(&user, userID).Error; err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(401, "用户不存在"))
|
||||
return
|
||||
}
|
||||
|
||||
// 检查用户角色:0管理员,1代理商,2普通用户
|
||||
if user.SystemRole != 0 {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(403, "权限不足,仅管理员可访问"))
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("current_user", user)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// AgentRoleMiddleware 代理商权限中间件
|
||||
func AgentRoleMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 获取token中的用户信息
|
||||
tokenMap, exists := c.Get("tokenMap")
|
||||
if !exists {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(401, "未授权访问"))
|
||||
return
|
||||
}
|
||||
|
||||
claims := tokenMap.(map[string]interface{})
|
||||
userIDFloat, ok := claims["user_id"].(float64)
|
||||
if !ok {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(401, "用户信息无效"))
|
||||
return
|
||||
}
|
||||
|
||||
userID := uint(userIDFloat)
|
||||
|
||||
// 查询用户信息
|
||||
var user models.User
|
||||
if err := common.GetDB().First(&user, userID).Error; err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(401, "用户不存在"))
|
||||
return
|
||||
}
|
||||
|
||||
// 检查用户角色:0管理员,1代理商
|
||||
if user.SystemRole != 0 && user.SystemRole != 1 {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(403, "权限不足,仅管理员和代理商可访问"))
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("current_user", user)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
func UserRoleMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
|
||||
// 获取token中的用户信息
|
||||
tokenMap, exists := c.Get("tokenMap")
|
||||
if !exists {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(401, "未授权访问"))
|
||||
return
|
||||
}
|
||||
|
||||
claims := tokenMap.(map[string]interface{})
|
||||
userIDFloat, ok := claims["user_id"].(float64)
|
||||
if !ok {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(401, "用户信息无效"))
|
||||
return
|
||||
}
|
||||
|
||||
userID := uint(userIDFloat)
|
||||
|
||||
// 查询用户信息
|
||||
var user models.User
|
||||
if err := common.GetDB().First(&user, userID).Error; err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(401, "用户不存在"))
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("current_user", user)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// CheckUserPermission 检查用户权限(代理商只能查看自己邀请的用户)
|
||||
func CheckUserPermission() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
currentUser, exists := c.Get("current_user")
|
||||
if !exists {
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(401, "用户信息获取失败"))
|
||||
return
|
||||
}
|
||||
|
||||
user := currentUser.(models.User)
|
||||
|
||||
// 如果是管理员,拥有所有权限
|
||||
if user.SystemRole == 0 {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
// 如果是代理商,需要检查权限
|
||||
if user.SystemRole == 1 {
|
||||
// 获取请求路径
|
||||
//path := c.Request.URL.Path
|
||||
method := c.Request.Method
|
||||
|
||||
//// 代理商权限限制
|
||||
//allowedPaths := []string{
|
||||
// "/back/admin/users", // 查看用户列表
|
||||
// "/back/admin/purchase-orders", // 查看买单
|
||||
// "/back/admin/sales-orders", // 查看卖单
|
||||
// "/back/admin/score-records", // 查看积分记录
|
||||
//}
|
||||
//
|
||||
//// 检查是否为允许的路径
|
||||
//pathAllowed := false
|
||||
//for _, allowedPath := range allowedPaths {
|
||||
// if strings.HasPrefix(path, allowedPath) {
|
||||
// pathAllowed = true
|
||||
// break
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//if !pathAllowed {
|
||||
// c.AbortWithStatusJSON(http.StatusOK, common.Error(403, "代理商权限不足"))
|
||||
// return
|
||||
//}
|
||||
|
||||
// 对于GET请求,添加查询过滤条件
|
||||
if method == "GET" {
|
||||
// 设置代理商身份码,用于数据过滤
|
||||
c.Set("agent_identity_code", user.IdentityCode)
|
||||
} else {
|
||||
// 非GET请求,代理商不允许
|
||||
c.AbortWithStatusJSON(http.StatusOK, common.Error(403, "代理商只能查看数据,不能进行修改操作"))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// GetUserIDFromParam 从URL参数中获取用户ID并检查权限
|
||||
func GetUserIDFromParam(c *gin.Context, paramName string) (uint, error) {
|
||||
currentUser, exists := c.Get("current_user")
|
||||
if !exists {
|
||||
return 0, fmt.Errorf("用户信息获取失败")
|
||||
}
|
||||
|
||||
user := currentUser.(models.User)
|
||||
userIDStr := c.Param(paramName)
|
||||
userID, err := strconv.ParseUint(userIDStr, 10, 32)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("用户ID无效")
|
||||
}
|
||||
|
||||
targetUserID := uint(userID)
|
||||
|
||||
// 如果是管理员,可以查看所有用户
|
||||
if user.SystemRole == 0 {
|
||||
return targetUserID, nil
|
||||
}
|
||||
|
||||
// 如果是代理商,只能查看自己邀请的用户
|
||||
if user.SystemRole == 1 {
|
||||
var targetUser models.User
|
||||
if err := common.GetDB().First(&targetUser, targetUserID).Error; err != nil {
|
||||
return 0, fmt.Errorf("目标用户不存在")
|
||||
}
|
||||
|
||||
// 检查是否为代理商邀请的用户
|
||||
if targetUser.ReferrerIdentityCode != user.IdentityCode {
|
||||
return 0, fmt.Errorf("权限不足,只能查看您邀请的用户")
|
||||
}
|
||||
|
||||
return targetUserID, nil
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("权限不足")
|
||||
}
|
||||
Reference in New Issue
Block a user