Skip to content

Commit

Permalink
Add geopositioning user ips rake task
Browse files Browse the repository at this point in the history
  • Loading branch information
laurajaime committed Feb 8, 2023
1 parent 9714b47 commit 6c1b6a2
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ gem "delayed_job_active_record"
gem "whenever", require: false

gem "recaptcha"
gem 'ipaddr'

group :development, :test do
gem "bootsnap"
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

0 comments on commit 6c1b6a2

Please sign in to comment.