2020-08-11 11:04:26 +03:00
|
|
|
defmodule PlausibleWeb.RemoteIp do
|
|
|
|
def get(conn) do
|
2021-05-03 17:30:54 +03:00
|
|
|
cf_connecting_ip = List.first(Plug.Conn.get_req_header(conn, "cf-connecting-ip"))
|
2020-08-11 11:04:26 +03:00
|
|
|
forwarded_for = List.first(Plug.Conn.get_req_header(conn, "x-forwarded-for"))
|
2021-05-21 14:57:00 +03:00
|
|
|
forwarded = List.first(Plug.Conn.get_req_header(conn, "forwarded"))
|
2020-08-11 11:04:26 +03:00
|
|
|
|
2021-05-03 17:30:54 +03:00
|
|
|
cond do
|
|
|
|
cf_connecting_ip ->
|
|
|
|
cf_connecting_ip
|
|
|
|
|
|
|
|
forwarded_for ->
|
|
|
|
String.split(forwarded_for, ",")
|
|
|
|
|> Enum.map(&String.trim/1)
|
|
|
|
|> List.first()
|
|
|
|
|
2021-05-21 14:57:00 +03:00
|
|
|
forwarded ->
|
|
|
|
Regex.named_captures(~r/for=(?<for>[^;,]+).*$/, forwarded)
|
|
|
|
|> Map.get("for")
|
|
|
|
# IPv6 addresses are enclosed in quote marks and square brackets: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
|
|
|
|
|> String.trim("\"")
|
|
|
|
|> String.trim_leading("[")
|
|
|
|
|> String.trim_trailing("]")
|
|
|
|
|
2021-05-03 17:30:54 +03:00
|
|
|
true ->
|
|
|
|
to_string(:inet_parse.ntoa(conn.remote_ip))
|
2020-08-11 11:04:26 +03:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|