From 98c04eac15d8e1d7add84e08855a0385c9c2edbe Mon Sep 17 00:00:00 2001 From: Pete Matsyburka Date: Mon, 3 Jun 2024 08:57:14 +0300 Subject: [PATCH] normalize client ip --- config/application.rb | 2 ++ lib/normalize_client_ip_middleware.rb | 16 ++++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 lib/normalize_client_ip_middleware.rb diff --git a/config/application.rb b/config/application.rb index ed01a7622..ffb886f89 100644 --- a/config/application.rb +++ b/config/application.rb @@ -11,6 +11,7 @@ require 'rails/health_controller' require_relative '../lib/api_path_consider_json_middleware' +require_relative '../lib/normalize_client_ip_middleware' Bundler.require(*Rails.groups) @@ -32,6 +33,7 @@ class Application < Rails::Application config.action_view.frozen_string_literal = true config.middleware.insert_before ActionDispatch::Static, Rack::Deflater + config.middleware.insert_before ActionDispatch::Static, NormalizeClientIpMiddleware config.middleware.insert_before ActionDispatch::Static, ApiPathConsiderJsonMiddleware config.generators.system_tests = nil diff --git a/lib/normalize_client_ip_middleware.rb b/lib/normalize_client_ip_middleware.rb new file mode 100644 index 000000000..41be33776 --- /dev/null +++ b/lib/normalize_client_ip_middleware.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +class NormalizeClientIpMiddleware + def initialize(app) + @app = app + end + + def call(env) + if env['HTTP_CLIENT_IP'].present? && env['HTTP_X_CLIENT_IP'].present? && + env['HTTP_CLIENT_IP'].starts_with?("#{env['HTTP_X_CLIENT_IP']}:") + env['HTTP_CLIENT_IP'] = env['HTTP_X_CLIENT_IP'] + end + + @app.call(env) + end +end