geoip.lua

Mon, 04 Jan 2016 17:08:27 +0000

author
Matthew Wild <mwild1@gmail.com>
date
Mon, 04 Jan 2016 17:08:27 +0000
changeset 23
aeaef24372ef
parent 22
67c2b47a00c7
permissions
-rw-r--r--

geoip: Use IP from X-Forwarded-For if it exists

local log = require "util.logger".init("geoip");

local ok, err = pcall(function ()
	local city_db_path = os.getenv("GEOIP_CITY_DB");
	if not city_db_path then
		log("debug", "GEOIP_CITY_DB not set");
		return;
	end
	
	log("debug", "Loading geoip database");
	local city_db = assert(require "geoip.city".open(city_db_path));
	log("debug", "Loaded geoip database successfully");

	events.add_handler("new-client", function (info)
		local ip = info.request.headers.x_forwarded_for or info.conn:ip();
		log("debug", "GeoIP query for %s", tostring(ip));
		local location, err = city_db:query_by_addr(ip);
		if location then
			local l = {};
			if location.city_name then
				table.insert(l, location.city_name);
			end
			if location.region then
				table.insert(l, location.region);
			end
			if location.country_name then
				table.insert(l, location.country_name);
			end
			info.conn.location = table.concat(l, ", ");
		else
			log("debug", "Failed to find location for IP %q: %s", tostring(ip), tostring(err));
		end
	end);
end)

if not ok then
	log("warn", "GeoIP loading failed: %s", tostring(err));
end

mercurial