Files
warehouse-management-BE/internal/middlewares/auth_middleware.go

55 lines
1.3 KiB
Go

package middlewares
import (
"net/http"
"strings"
"wm-backend/pkg/helper"
"wm-backend/response"
"github.com/gin-gonic/gin"
"github.com/rs/zerolog/log"
)
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 1. Get the Authorization header
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
response.UnauthorizedError(c, http.StatusUnauthorized, "Missing Authorization header")
c.Abort()
return
}
// 2. Extract Bearer token
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
response.UnauthorizedError(c, http.StatusUnauthorized, "Invalid Authorization header format")
c.Abort()
return
}
tokenString := parts[1]
// 3. Parse JWT token
claims, err := helper.ParseToken(tokenString)
if err != nil {
log.Error().Err(err).Msg("Failed to parse JWT token")
response.UnauthorizedError(c, http.StatusUnauthorized, "Invalid or expired token")
c.Abort()
return
}
// 4. Extract user_id from claims
userID, ok := claims["user_id"].(string)
if !ok || userID == "" {
response.UnauthorizedError(c, http.StatusUnauthorized, "Invalid token: missing user_id")
c.Abort()
return
}
// 5. Set user_id in gin context for downstream handlers
c.Set("user_id", userID)
c.Next()
}
}