78 lines
1.9 KiB
Go
78 lines
1.9 KiB
Go
package middleware
|
|
|
|
import (
|
|
services "api-service/internal/services/auth"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// JWTAuthMiddleware validates JWT tokens generated by our auth service
|
|
func JWTAuthMiddleware(authService *services.AuthService) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header missing"})
|
|
return
|
|
}
|
|
|
|
parts := strings.SplitN(authHeader, " ", 2)
|
|
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header format must be Bearer {token}"})
|
|
return
|
|
}
|
|
|
|
tokenString := parts[1]
|
|
|
|
// Validate token
|
|
claims, err := authService.ValidateToken(tokenString)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
// Set user info in context
|
|
c.Set("user_id", claims.UserID)
|
|
c.Set("username", claims.Username)
|
|
c.Set("email", claims.Email)
|
|
c.Set("role", claims.Role)
|
|
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// OptionalAuthMiddleware allows both authenticated and unauthenticated requests
|
|
func OptionalAuthMiddleware(authService *services.AuthService) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
authHeader := c.GetHeader("Authorization")
|
|
if authHeader == "" {
|
|
// No token provided, but continue
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
parts := strings.SplitN(authHeader, " ", 2)
|
|
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
tokenString := parts[1]
|
|
claims, err := authService.ValidateToken(tokenString)
|
|
if err != nil {
|
|
// Invalid token, but continue (don't abort)
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
// Set user info in context
|
|
c.Set("user_id", claims.UserID)
|
|
c.Set("username", claims.Username)
|
|
c.Set("email", claims.Email)
|
|
c.Set("role", claims.Role)
|
|
|
|
c.Next()
|
|
}
|
|
}
|