geolocation tweak

This commit is contained in:
Graham McIntire 2025-07-10 17:25:32 -05:00
parent 4b38c8f601
commit e6c0bb740b
No known key found for this signature in database

View file

@ -71,22 +71,36 @@ defmodule AprsmeWeb.Plugs.IPGeolocation do
# Check for forwarded IP first (when behind proxy/load balancer) # Check for forwarded IP first (when behind proxy/load balancer)
forwarded_for = get_req_header(conn, "x-forwarded-for") forwarded_for = get_req_header(conn, "x-forwarded-for")
case forwarded_for do ip =
[forwarded | _] -> case forwarded_for do
# Take the first IP from the X-Forwarded-For header [forwarded | _] ->
forwarded # Take the first IP from the X-Forwarded-For header
|> String.split(",") ip_from_header =
|> List.first() forwarded
|> String.trim() |> String.split(",")
|> List.first()
|> String.trim()
[] -> Logger.info("IP geolocation: Using forwarded IP from X-Forwarded-For header: #{ip_from_header}")
# Fall back to remote_ip ip_from_header
case conn.remote_ip do
{a, b, c, d} -> "#{a}.#{b}.#{c}.#{d}" [] ->
{a, b, c, d, e, f, g, h} -> "#{a}:#{b}:#{c}:#{d}:#{e}:#{f}:#{g}:#{h}" # Fall back to remote_ip
_ -> nil ip_from_remote =
end case conn.remote_ip do
end {a, b, c, d} -> "#{a}.#{b}.#{c}.#{d}"
{a, b, c, d, e, f, g, h} -> "#{a}:#{b}:#{c}:#{d}:#{e}:#{f}:#{g}:#{h}"
_ -> nil
end
if ip_from_remote do
Logger.info("IP geolocation: Using remote_ip: #{ip_from_remote}")
end
ip_from_remote
end
ip
end end
defp valid_ip_for_geolocation?(ip) when is_binary(ip) do defp valid_ip_for_geolocation?(ip) when is_binary(ip) do