Multiple implementations of the same back-end application. The aim is to provide quick, side-by-side comparisons of different technologies (languages, frameworks, libraries) while preserving consistent business logic across all implementations.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

62 lines
1.5 KiB

package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"autostore/internal/application/interfaces"
"autostore/internal/application/dto"
)
type JWTMiddleware struct {
authService interfaces.IAuthService
logger interfaces.ILogger
}
func NewJWTMiddleware(
authService interfaces.IAuthService,
logger interfaces.ILogger,
) *JWTMiddleware {
return &JWTMiddleware{
authService: authService,
logger: logger,
}
}
func (m *JWTMiddleware) Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, dto.JSendError("Authorization header is required", http.StatusUnauthorized))
c.Abort()
return
}
parts := strings.SplitN(authHeader, " ", 2)
if !(len(parts) == 2 && parts[0] == "Bearer") {
c.JSON(http.StatusUnauthorized, dto.JSendError("Invalid authorization format", http.StatusUnauthorized))
c.Abort()
return
}
token := parts[1]
valid, err := m.authService.ValidateToken(c.Request.Context(), token)
if err != nil || !valid {
c.JSON(http.StatusUnauthorized, dto.JSendError("Invalid or expired token", http.StatusUnauthorized))
c.Abort()
return
}
userID, err := m.authService.GetUserIDFromToken(c.Request.Context(), token)
if err != nil {
c.JSON(http.StatusUnauthorized, dto.JSendError("Failed to get user ID from token", http.StatusUnauthorized))
c.Abort()
return
}
c.Set("userID", userID)
c.Next()
}
}