Skip to content

Commit

Permalink
support cloudflare
Browse files Browse the repository at this point in the history
  • Loading branch information
loftwah committed Sep 14, 2024
1 parent 21dc783 commit 8063fa2
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions app/middleware/page_view_tracker.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,18 @@ 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,
path: request.path,
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],
Expand All @@ -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

0 comments on commit 8063fa2

Please sign in to comment.