From 8063fa2ad99fc39b4a411a3079a1a283b35004db Mon Sep 17 00:00:00 2001 From: Dean Lofts Date: Sat, 14 Sep 2024 21:55:57 +1000 Subject: [PATCH] support cloudflare --- app/middleware/page_view_tracker.rb | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/app/middleware/page_view_tracker.rb b/app/middleware/page_view_tracker.rb index c26d7f5..78ecb9c 100644 --- a/app/middleware/page_view_tracker.rb +++ b/app/middleware/page_view_tracker.rb @@ -23,7 +23,10 @@ def html_response?(headers) def track_page_view(request) user = User.find_by(username: request.path.split('/').last) if user - location = OFFLINE_GEOCODER.search(request.ip) + # Extract the original IP from the Cloudflare headers if available + real_ip = request.headers['CF-Connecting-IP'] || request.headers['X-Forwarded-For']&.split(',')&.first || request.ip + + location = OFFLINE_GEOCODER.search(real_ip) PageView.create( user: user, @@ -31,7 +34,7 @@ def track_page_view(request) referrer: request.referrer, browser: request.user_agent, visited_at: Time.current, - ip_address: request.ip, + ip_address: real_ip, session_id: request.session[:session_id], country: location[:country], city: location[:name], @@ -46,5 +49,5 @@ def track_page_view(request) Rails.logger.info "Duplicate page view detected and ignored" rescue => e Rails.logger.error "Error tracking page view: #{e.message}" - end + end end \ No newline at end of file