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 }