Files
apocapoc-api/internal/infrastructure/http/auth_middleware.go
T
david 29f0f9b468 Add structured logging with zerolog
- Implement zerolog logger package with configurable levels
- Add contextual logging middleware (request_id, user_id, method, path, status, duration)
- Support both JSON (production) and human-readable (development) formats
- Add LOG_LEVEL and ENVIRONMENT configuration variables
- Replace standard log calls with structured logger throughout application
- Integrate logger in HTTP router and auth middleware
2025-12-04 23:22:05 +01:00

49 lines
1.2 KiB
Go

package http
import (
"context"
"net/http"
"strings"
"apocapoc-api/internal/infrastructure/auth"
"apocapoc-api/internal/infrastructure/logger"
)
type contextKey string
const UserIDKey contextKey = "userID"
func AuthMiddleware(jwtService *auth.JWTService) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
respondError(w, http.StatusUnauthorized, "Missing authorization header")
return
}
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || parts[0] != "Bearer" {
respondError(w, http.StatusUnauthorized, "Invalid authorization header format")
return
}
tokenString := parts[1]
claims, err := jwtService.ValidateToken(tokenString)
if err != nil {
respondError(w, http.StatusUnauthorized, "Invalid or expired token")
return
}
ctx := context.WithValue(r.Context(), UserIDKey, claims.UserID)
ctx = logger.AddUserID(ctx, claims.UserID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func GetUserIDFromContext(ctx context.Context) (string, bool) {
userID, ok := ctx.Value(UserIDKey).(string)
return userID, ok
}