package middleware import ( "backend/model" "backend/store" "github.com/gin-gonic/gin" ) func ValidateToken() gin.HandlerFunc { return func(c *gin.Context) { token := c.GetHeader("Authorization") if len(token) > 7 && token[:7] == "Bearer " { token = token[7:] } if token == "" || !store.IsTokenValid(token) { c.JSON(401, gin.H{"error": "Authorization header is required"}) c.Abort() return } tokenInfo, _ := store.GetTokenInfo(token) if tokenInfo != nil { c.Set("admin", tokenInfo.UserName) } path := c.FullPath() if path == "" { path = c.Request.URL.Path } // 验证用户权限 if tokenInfo != nil { hasPermission := model.CheckUserPermission(tokenInfo.UserName, path, c.Request.Method) if !hasPermission { c.JSON(403, gin.H{"error": "Permission denied"}) c.Abort() return } } c.Next() } } // ValidateTokenOnly 只校验 token 有效性,不做权限校验 func ValidateTokenOnly() gin.HandlerFunc { return func(c *gin.Context) { token := c.GetHeader("Authorization") if len(token) > 7 && token[:7] == "Bearer " { token = token[7:] } if token == "" || !store.IsTokenValid(token) { c.JSON(401, gin.H{"error": "Authorization header is required"}) c.Abort() return } tokenInfo, _ := store.GetTokenInfo(token) if tokenInfo != nil { c.Set("admin", tokenInfo.UserName) } c.Next() } }