45 lines
1022 B
Go
45 lines
1022 B
Go
|
|
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()
|
||
|
|
}
|
||
|
|
}
|