Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Geopositioning user ips with rake task #407

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ gem "delayed_job_active_record"

gem "whenever", require: false

gem "ipaddr"
gem "recaptcha"

group :development, :test do
Expand Down
2 changes: 2 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,7 @@ GEM
ruby-vips (>= 2.0.17, < 3)
invisible_captcha (0.13.0)
rails (>= 3.2.0)
ipaddr (1.2.3)
json (2.6.2)
jwt (2.5.0)
kaminari (1.2.2)
Expand Down Expand Up @@ -904,6 +905,7 @@ DEPENDENCIES
delayed_job_active_record
faker
figaro (>= 1.1.1)
ipaddr
letter_opener_web
listen (~> 3.1.0)
puma (< 6)
Expand Down
40 changes: 40 additions & 0 deletions lib/tasks/geopositioning_users.rake
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# frozen_string_literal: true

require "csv"
require "ipaddr"

namespace :geopositioning_users do
# This task extracts a csv file with the IPs of the users and their location.
desc "Generate a CSV with the users IP information"
task generate_csv: :environment do
headers = %w(email IP IP_location last_sign_in)
# VPN IP, blank or nils
invalid_ips = ["10.2.1.52", "", nil]
users_with_valid_ip = Decidim::User.where.not(last_sign_in_ip: invalid_ips)

CSV.open("users_ip_locations.csv", "w") do |csv|
csv << headers

users_with_valid_ip.each_with_index do |user, index|
user_ip = user.last_sign_in_ip
puts "User #{index}/#{users_with_valid_ip.count}"

if IPAddr.new(user_ip).private?
csv << [user.email, user_ip, "Private IP", user.last_sign_in_at]
else
# Delay to wait between requests to Geocoder API
sleep 0.5
csv << [user.email, user_ip, ip_location(user_ip), user.last_sign_in_at]
end
end
end
end

private

def ip_location(ip)
results = Geocoder.search(ip).first

results.present? ? results.address : nil
end
end