重构后端服务架构并优化前端错误处理

This commit is contained in:
ylweng
2025-09-12 01:21:43 +08:00
parent d550a8ed51
commit 3a48a67757
53 changed files with 3925 additions and 0 deletions

View File

@@ -0,0 +1,45 @@
package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"niumall-go/utils"
)
// AuthMiddleware authenticates requests using JWT
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Get authorization header
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
c.Abort()
return
}
// Check if header has Bearer prefix
if !strings.HasPrefix(authHeader, "Bearer ") {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid authorization header format"})
c.Abort()
return
}
// Extract token
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
// Parse and validate token
claims, err := utils.ParseJWT(tokenString)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired token"})
c.Abort()
return
}
// Set user UUID in context for use in handlers
c.Set("user_uuid", claims.UUID)
c.Next()
}
}