Add ability to block certain IP addresses

This commit is contained in:
Uku Taht 2020-08-11 11:04:26 +03:00
parent 42ea7fe682
commit 3a1c9e67cd
6 changed files with 43 additions and 14 deletions

View File

@ -181,6 +181,9 @@ config :plausible, :custom_domain_server,
password: System.get_env("CUSTOM_DOMAIN_SERVER_PASSWORD"),
ip: System.get_env("CUSTOM_DOMAIN_SERVER_IP")
config :plausible, PlausibleWeb.Firewall,
blocklist: System.get_env("IP_BLOCKLIST", "")
config :geolix,
databases: [
%{

View File

@ -147,6 +147,9 @@ config :plausible, :custom_domain_server,
password: custom_domain_server_password,
ip: custom_domain_server_ip
config :plausible, PlausibleWeb.Firewall,
blocklist: System.get_env("IP_BLOCKLIST", "")
base_cron = [
# Daily at midnight
{"0 0 * * *", Plausible.Workers.RotateSalts}

View File

@ -100,21 +100,9 @@ defmodule PlausibleWeb.Api.ExternalController do
end
end
defp get_ip(conn) do
forwarded_for = List.first(Plug.Conn.get_req_header(conn, "x-forwarded-for"))
if forwarded_for do
String.split(forwarded_for, ",")
|> Enum.map(&String.trim/1)
|> List.first()
else
to_string(:inet_parse.ntoa(conn.remote_ip))
end
end
defp visitor_country(conn) do
result =
get_ip(conn)
PlausibleWeb.RemoteIp.get(conn)
|> Geolix.lookup()
|> Map.get(:country)
@ -135,7 +123,7 @@ defmodule PlausibleWeb.Api.ExternalController do
defp generate_user_id(conn, params, salt) do
user_agent = List.first(Plug.Conn.get_req_header(conn, "user-agent")) || ""
ip_address = get_ip(conn)
ip_address = PlausibleWeb.RemoteIp.get(conn)
domain = strip_www(params["domain"]) || ""
SipHash.hash!(salt, user_agent <> ip_address <> domain)

View File

@ -0,0 +1,19 @@
defmodule PlausibleWeb.Firewall do
import Plug.Conn
def init(options) do
blocklist = Keyword.fetch!(Application.get_env(:plausible, __MODULE__), :blocklist)
|> String.split(",")
|> Enum.map(&String.trim/1)
Keyword.merge(options, blocklist: blocklist)
end
def call(conn, opts) do
if PlausibleWeb.RemoteIp.get(conn) in opts[:blocklist] do
send_resp(conn, 404, "Not found") |> halt
else
conn
end
end
end

View File

@ -0,0 +1,13 @@
defmodule PlausibleWeb.RemoteIp do
def get(conn) do
forwarded_for = List.first(Plug.Conn.get_req_header(conn, "x-forwarded-for"))
if forwarded_for do
String.split(forwarded_for, ",")
|> Enum.map(&String.trim/1)
|> List.first()
else
to_string(:inet_parse.ntoa(conn.remote_ip))
end
end
end

View File

@ -6,6 +6,7 @@ defmodule PlausibleWeb.Router do
pipeline :browser do
plug :accepts, ["html"]
plug PlausibleWeb.Firewall
plug :fetch_session
plug :fetch_flash
plug :put_secure_browser_headers
@ -20,12 +21,14 @@ defmodule PlausibleWeb.Router do
pipeline :api do
plug :accepts, ["json"]
plug PlausibleWeb.Firewall
plug :fetch_session
plug PlausibleWeb.AuthPlug
end
pipeline :stats_api do
plug :accepts, ["json"]
plug PlausibleWeb.Firewall
plug :fetch_session
end