Shield: Country Rules (#3828)
* Migration: add country rules * Add CountryRule schema * Implement CountryRule cache * Add country rules context interface * Start country rules cache * Lookup country rules on ingestion * Remove :shields feature flag from test helpers * Add nested sidebar menu for Shields * Fix typo * IP Rules: hide description on mobile view * Prepare SiteController to handle multiple shield types * Seed some country shield * Implement LV for country rules * Remove "YOU" indicator from country rules * Fix small build * Format * Update typespecs * Make docs link point at /countries * Fix flash on top of modal for Safari * Build the rule struct with site_id provided up-front * Clarify why we're messaging the ComboBox component * Re-open combobox suggestions after pressing Escape * Update changelog * Fix font size in country table cells * Pass `added_by` via rule add options * Display site's timezone timestamps in rule tooltips * Display formatted timestamps in site's timezone And simplify+test Timezone module; an input timestamp converted to UTC can never be ambiguous. * Remove no-op atom * Display the maximum number of rules when reached * Improve readability of remove button tests * Credo --------- Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>pull/3835/head r2024.02.27-374
parent
b7b5dcf4c9
commit
518cdb3307
@ -0,0 +1,38 @@
|
||||
defmodule Plausible.Shield.CountryRule do
|
||||
@moduledoc """
|
||||
Schema for Country Block List
|
||||
"""
|
||||
use Ecto.Schema
|
||||
import Ecto.Changeset
|
||||
|
||||
@type t() :: %__MODULE__{}
|
||||
|
||||
@primary_key {:id, :binary_id, autogenerate: true}
|
||||
schema "shield_rules_country" do
|
||||
belongs_to :site, Plausible.Site
|
||||
field :country_code, :string
|
||||
field :action, Ecto.Enum, values: [:deny, :allow], default: :deny
|
||||
field :added_by, :string
|
||||
|
||||
# If `from_cache?` is set, the struct might be incomplete - see `Plausible.Site.Shield.Rules.Country.Cache`
|
||||
field :from_cache?, :boolean, virtual: true, default: false
|
||||
timestamps()
|
||||
end
|
||||
|
||||
def changeset(rule, attrs) do
|
||||
rule
|
||||
|> cast(attrs, [:site_id, :country_code])
|
||||
|> validate_required([:site_id, :country_code])
|
||||
|> validate_length(:country_code, is: 2)
|
||||
|> Ecto.Changeset.validate_change(:country_code, fn :country_code, cc ->
|
||||
if cc in Enum.map(Location.Country.all(), & &1.alpha_2) do
|
||||
[]
|
||||
else
|
||||
[country_code: "is invalid"]
|
||||
end
|
||||
end)
|
||||
|> unique_constraint(:country_code,
|
||||
name: :shield_rules_country_site_id_country_code_index
|
||||
)
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,65 @@
|
||||
defmodule Plausible.Shield.CountryRuleCache do
|
||||
@moduledoc """
|
||||
Allows retrieving Country Rules by domain and country code
|
||||
"""
|
||||
alias Plausible.Shield.CountryRule
|
||||
|
||||
import Ecto.Query
|
||||
use Plausible.Cache
|
||||
|
||||
@cache_name :country_blocklist_by_domain
|
||||
|
||||
@cached_schema_fields ~w(
|
||||
id
|
||||
country_code
|
||||
action
|
||||
)a
|
||||
|
||||
@impl true
|
||||
def name(), do: @cache_name
|
||||
|
||||
@impl true
|
||||
def child_id(), do: :cachex_country_blocklist
|
||||
|
||||
@impl true
|
||||
def count_all() do
|
||||
Plausible.Repo.aggregate(CountryRule, :count)
|
||||
end
|
||||
|
||||
@impl true
|
||||
def base_db_query() do
|
||||
from rule in CountryRule,
|
||||
inner_join: s in assoc(rule, :site),
|
||||
select: {
|
||||
s.domain,
|
||||
s.domain_changed_from,
|
||||
%{struct(rule, ^@cached_schema_fields) | from_cache?: true}
|
||||
}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def get_from_source({domain, country_code}) do
|
||||
query =
|
||||
base_db_query()
|
||||
|> where([rule, site], rule.country_code == ^country_code and site.domain == ^domain)
|
||||
|
||||
case Plausible.Repo.one(query) do
|
||||
{_, _, rule} -> %CountryRule{rule | from_cache?: false}
|
||||
_any -> nil
|
||||
end
|
||||
end
|
||||
|
||||
@impl true
|
||||
def unwrap_cache_keys(items) do
|
||||
Enum.reduce(items, [], fn
|
||||
{domain, nil, object}, acc ->
|
||||
[{{domain, String.upcase(object.country_code)}, object} | acc]
|
||||
|
||||
{domain, domain_changed_from, object}, acc ->
|
||||
[
|
||||
{{domain, String.upcase(object.country_code)}, object},
|
||||
{{domain_changed_from, String.upcase(object.country_code)}, object} | acc
|
||||
]
|
||||
end)
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,53 @@
|
||||
defmodule PlausibleWeb.Live.Shields.Countries do
|
||||
@moduledoc """
|
||||
LiveView for IP Addresses Shield
|
||||
"""
|
||||
use PlausibleWeb, :live_view
|
||||
use Phoenix.HTML
|
||||
|
||||
alias Plausible.Shields
|
||||
alias Plausible.Sites
|
||||
|
||||
def mount(
|
||||
_params,
|
||||
%{
|
||||
"domain" => domain,
|
||||
"current_user_id" => user_id
|
||||
},
|
||||
socket
|
||||
) do
|
||||
socket =
|
||||
socket
|
||||
|> assign_new(:site, fn ->
|
||||
Sites.get_for_user!(user_id, domain, [:owner, :admin, :super_admin])
|
||||
end)
|
||||
|> assign_new(:country_rules_count, fn %{site: site} ->
|
||||
Shields.count_country_rules(site)
|
||||
end)
|
||||
|> assign_new(:current_user, fn ->
|
||||
Plausible.Repo.get(Plausible.Auth.User, user_id)
|
||||
end)
|
||||
|
||||
{:ok, socket}
|
||||
end
|
||||
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<div>
|
||||
<.flash_messages flash={@flash} />
|
||||
<.live_component
|
||||
module={PlausibleWeb.Live.Shields.CountryRules}
|
||||
current_user={@current_user}
|
||||
country_rules_count={@country_rules_count}
|
||||
site={@site}
|
||||
id="country-rules-#{@current_user.id}"
|
||||
/>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
def handle_info({:flash, kind, message}, socket) do
|
||||
socket = put_live_flash(socket, kind, message)
|
||||
{:noreply, socket}
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,251 @@
|
||||
defmodule PlausibleWeb.Live.Shields.CountryRules do
|
||||
@moduledoc """
|
||||
LiveView allowing Country Rules management
|
||||
"""
|
||||
|
||||
use Phoenix.LiveComponent, global_prefixes: ~w(x-)
|
||||
use Phoenix.HTML
|
||||
|
||||
alias PlausibleWeb.Live.Components.Modal
|
||||
alias Plausible.Shields
|
||||
alias Plausible.Shield
|
||||
|
||||
def update(assigns, socket) do
|
||||
socket =
|
||||
socket
|
||||
|> assign(
|
||||
country_rules_count: assigns.country_rules_count,
|
||||
site: assigns.site,
|
||||
current_user: assigns.current_user,
|
||||
form: new_form()
|
||||
)
|
||||
|> assign_new(:country_rules, fn %{site: site} ->
|
||||
Shields.list_country_rules(site)
|
||||
end)
|
||||
|
||||
{:ok, socket}
|
||||
end
|
||||
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<section class="shadow bg-white dark:bg-gray-800 sm:rounded-md sm:overflow-hidden">
|
||||
<div class="py-6 px-4 sm:p-6">
|
||||
<header class="relative">
|
||||
<h2 class="text-lg leading-6 font-medium text-gray-900 dark:text-gray-100">
|
||||
Country Block List
|
||||
</h2>
|
||||
<p class="mt-1 mb-4 text-sm leading-5 text-gray-500 dark:text-gray-200">
|
||||
Reject incoming traffic from specific countries
|
||||
</p>
|
||||
|
||||
<PlausibleWeb.Components.Generic.docs_info slug="countries" />
|
||||
</header>
|
||||
<div class="border-t border-gray-200 pt-4 grid">
|
||||
<div
|
||||
:if={@country_rules_count < Shields.maximum_country_rules()}
|
||||
class="mt-4 sm:ml-4 sm:mt-0 justify-self-end"
|
||||
>
|
||||
<PlausibleWeb.Components.Generic.button
|
||||
id="add-country-rule"
|
||||
x-data
|
||||
x-on:click={Modal.JS.open("country-rule-form-modal")}
|
||||
>
|
||||
+ Add Country
|
||||
</PlausibleWeb.Components.Generic.button>
|
||||
</div>
|
||||
<PlausibleWeb.Components.Generic.notice
|
||||
:if={@country_rules_count >= Shields.maximum_country_rules()}
|
||||
class="mt-4"
|
||||
title="Maximum number of countries reached"
|
||||
>
|
||||
<p>
|
||||
You've reached the maximum number of countries you can block (<%= Shields.maximum_country_rules() %>). Please remove one before adding another.
|
||||
</p>
|
||||
</PlausibleWeb.Components.Generic.notice>
|
||||
</div>
|
||||
|
||||
<.live_component module={Modal} id="country-rule-form-modal">
|
||||
<.form
|
||||
:let={f}
|
||||
for={@form}
|
||||
phx-submit="save-country-rule"
|
||||
phx-target={@myself}
|
||||
class="max-w-md w-full mx-auto bg-white dark:bg-gray-800"
|
||||
>
|
||||
<h2 class="text-xl font-black dark:text-gray-100 mb-8">Add Country to Block List</h2>
|
||||
|
||||
<.live_component
|
||||
submit_name="country_rule[country_code]"
|
||||
submit_value={f[:country_code].value}
|
||||
display_value=""
|
||||
module={PlausibleWeb.Live.Components.ComboBox}
|
||||
suggest_fun={&PlausibleWeb.Live.Components.ComboBox.StaticSearch.suggest/2}
|
||||
id={f[:country_code].id}
|
||||
suggestions_limit={300}
|
||||
options={options(@country_rules)}
|
||||
/>
|
||||
|
||||
<p class="text-sm mt-2 text-gray-500 dark:text-gray-200">
|
||||
Once added, we will start rejecting traffic from this country within a few minutes.
|
||||
</p>
|
||||
<div class="py-4 mt-8">
|
||||
<PlausibleWeb.Components.Generic.button type="submit" class="w-full">
|
||||
Add Country →
|
||||
</PlausibleWeb.Components.Generic.button>
|
||||
</div>
|
||||
</.form>
|
||||
</.live_component>
|
||||
|
||||
<p
|
||||
:if={Enum.empty?(@country_rules)}
|
||||
class="text-sm text-gray-800 dark:text-gray-200 mt-12 mb-8 text-center"
|
||||
>
|
||||
No Country Rules configured for this Site.
|
||||
</p>
|
||||
<div
|
||||
:if={not Enum.empty?(@country_rules)}
|
||||
class="mt-8 overflow-hidden border-b border-gray-200 shadow dark:border-gray-900 sm:rounded-lg"
|
||||
>
|
||||
<table class="min-w-full divide-y divide-gray-200 dark:divide-gray-900">
|
||||
<thead class="bg-gray-50 dark:bg-gray-900">
|
||||
<tr>
|
||||
<th
|
||||
scope="col"
|
||||
class="px-6 py-3 text-xs font-medium text-left text-gray-500 uppercase dark:text-gray-100"
|
||||
>
|
||||
Country
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
class="px-6 py-3 text-xs font-medium text-left text-gray-500 uppercase dark:text-gray-100"
|
||||
>
|
||||
Status
|
||||
</th>
|
||||
<th scope="col" class="px-6 py-3">
|
||||
<span class="sr-only">Remove</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<%= for rule <- @country_rules do %>
|
||||
<% country = Location.Country.get_country(rule.country_code) %>
|
||||
<tr class="text-gray-900 dark:text-gray-100">
|
||||
<td class="px-6 py-4 text-sm font-medium">
|
||||
<div class="flex items-center">
|
||||
<span
|
||||
id={"country-#{rule.id}"}
|
||||
class="mr-4 cursor-help border-b border-dotted border-gray-400"
|
||||
title={"Added at #{format_added_at(rule.inserted_at, @site.timezone)} by #{rule.added_by}"}
|
||||
>
|
||||
<%= country.flag %> <%= country.name %>
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm text-gray-500">
|
||||
<span :if={rule.action == :deny}>
|
||||
Blocked
|
||||
</span>
|
||||
<span :if={rule.action == :allow}>
|
||||
Allowed
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-6 py-4 text-sm font-medium text-right">
|
||||
<button
|
||||
id={"remove-country-rule-#{rule.id}"}
|
||||
phx-target={@myself}
|
||||
phx-click="remove-country-rule"
|
||||
phx-value-rule-id={rule.id}
|
||||
class="text-sm text-red-600"
|
||||
data-confirm="Are you sure you want to revoke this rule?"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
"""
|
||||
end
|
||||
|
||||
def handle_event("save-country-rule", %{"country_rule" => params}, socket) do
|
||||
user = socket.assigns.current_user
|
||||
|
||||
case Shields.add_country_rule(
|
||||
socket.assigns.site.id,
|
||||
Map.put(params, "added_by", "#{user.name} <#{user.email}>")
|
||||
) do
|
||||
{:ok, rule} ->
|
||||
country_rules = [rule | socket.assigns.country_rules]
|
||||
|
||||
socket =
|
||||
socket
|
||||
|> Modal.close("country-rule-form-modal")
|
||||
|> assign(
|
||||
form: new_form(),
|
||||
country_rules: country_rules,
|
||||
country_rules_count: socket.assigns.country_rules_count + 1
|
||||
)
|
||||
|
||||
# Make sure to clear the combobox input after adding a country rule, on subsequent modal reopening
|
||||
send_update(PlausibleWeb.Live.Components.ComboBox,
|
||||
id: "country_rule_country_code",
|
||||
display_value: ""
|
||||
)
|
||||
|
||||
send_flash(
|
||||
:success,
|
||||
"Country rule added successfully. Traffic will be rejected within a few minutes."
|
||||
)
|
||||
|
||||
{:noreply, socket}
|
||||
|
||||
{:error, %Ecto.Changeset{} = changeset} ->
|
||||
{:noreply, assign(socket, form: to_form(changeset))}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("remove-country-rule", %{"rule-id" => rule_id}, socket) do
|
||||
Shields.remove_country_rule(socket.assigns.site.id, rule_id)
|
||||
|
||||
send_flash(
|
||||
:success,
|
||||
"Country rule removed successfully. Traffic will be resumed within a few minutes."
|
||||
)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(
|
||||
country_rules_count: socket.assigns.country_rules_count - 1,
|
||||
country_rules: Enum.reject(socket.assigns.country_rules, &(&1.id == rule_id))
|
||||
)}
|
||||
end
|
||||
|
||||
def send_flash(kind, message) do
|
||||
send(self(), {:flash, kind, message})
|
||||
end
|
||||
|
||||
defp new_form() do
|
||||
%Shield.CountryRule{}
|
||||
|> Shield.CountryRule.changeset(%{})
|
||||
|> to_form()
|
||||
end
|
||||
|
||||
defp options(country_rules) do
|
||||
Location.Country.all()
|
||||
|> Enum.sort_by(& &1.name)
|
||||
|> Enum.map(fn c -> {c.alpha_2, c.flag <> " " <> c.name} end)
|
||||
|> Enum.reject(fn {country_code, _} ->
|
||||
country_code in Enum.map(country_rules, & &1.country_code)
|
||||
end)
|
||||
end
|
||||
|
||||
defp format_added_at(dt, tz) do
|
||||
dt
|
||||
|> Plausible.Timezones.to_datetime_in_timezone(tz)
|
||||
|> Timex.format!("{YYYY}-{0M}-{0D} {h24}:{m}:{s}")
|
||||
end
|
||||
end
|
||||
@ -1,13 +1,23 @@
|
||||
<a
|
||||
href={"/" <> URI.encode_www_form(@site.domain) <> "/settings/" <> @this_tab}
|
||||
href={@this_tab && "/" <> URI.encode_www_form(@site.domain) <> "/settings/" <> @this_tab}
|
||||
class={[
|
||||
"flex items-center px-3 py-2 text-sm leading-5 font-medium rounded-md outline-none focus:outline-none transition ease-in-out duration-150 cursor-default",
|
||||
is_current_tab(@conn, @this_tab) &&
|
||||
"cursor-default text-gray-900 dark:text-gray-100 bg-gray-100 dark:bg-gray-900 hover:text-gray-900 hover:bg-gray-100 focus:bg-gray-200 dark:focus:bg-gray-800",
|
||||
not is_current_tab(@conn, @this_tab) &&
|
||||
"cursor-pointer text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 hover:bg-gray-50 dark:hover:bg-gray-800 focus:text-gray-900 focus:bg-gray-50 dark:focus:text-gray-100 dark:focus:bg-gray-800"
|
||||
@this_tab && not is_current_tab(@conn, @this_tab) &&
|
||||
"cursor-pointer text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 hover:bg-gray-50 dark:hover:bg-gray-800 focus:text-gray-900 focus:bg-gray-50 dark:focus:text-gray-100 dark:focus:bg-gray-800",
|
||||
!@this_tab && "text-gray-600 dark:text-gray-400",
|
||||
@submenu? && "text-xs"
|
||||
]}
|
||||
>
|
||||
<PlausibleWeb.Components.Generic.dynamic_icon name={@icon} class="h-4 w-4 mr-2" />
|
||||
<PlausibleWeb.Components.Generic.dynamic_icon
|
||||
:if={not @submenu? && @icon}
|
||||
name={@icon}
|
||||
class="h-4 w-4 mr-2"
|
||||
/>
|
||||
<%= @text %>
|
||||
<Heroicons.chevron_down
|
||||
:if={is_nil(@this_tab)}
|
||||
class="h-3 w-3 ml-2 text-gray-400 dark:text-gray-500"
|
||||
/>
|
||||
</a>
|
||||
|
||||
@ -1,26 +0,0 @@
|
||||
<%= render_layout "app.html", assigns do %>
|
||||
<div class="container pt-6">
|
||||
<%= link("← Back to Stats", to: "/#{URI.encode_www_form(@site.domain)}", class: "text-sm text-indigo-600 font-bold") %>
|
||||
<div class="pb-5 border-b border-gray-200 dark:border-gray-500">
|
||||
<h2 class="text-2xl font-bold leading-7 text-gray-900 dark:text-gray-100 sm:text-3xl sm:leading-9 sm:truncate">
|
||||
Settings for <%= @site.domain %>
|
||||
</h2>
|
||||
</div>
|
||||
<div class="lg:grid lg:grid-cols-12 lg:gap-x-5 lg:mt-4">
|
||||
<div class="py-4 g:py-0 lg:col-span-3">
|
||||
<%= form_for @conn, "/sites/#{URI.encode_www_form(@site.domain)}/monthly-report/recipients", [class: "lg:hidden"], fn f -> %>
|
||||
<%= select f, :tab, settings_tabs(@conn), class: "dark:bg-gray-800 mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 dark:border-gray-500 outline-none focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md dark:text-gray-100", onchange: "location.href = location.href.replace(/[^\/\/]*$/, event.target.value)", selected: List.last(@conn.path_info) %>
|
||||
<% end %>
|
||||
<div class="hidden lg:block">
|
||||
<%= for [key: key, value: val, icon: icon] <- settings_tabs(@conn) do %>
|
||||
<%= render("_settings_tab.html", icon: icon, this_tab: val, text: key, site: @site, conn: @conn) %>
|
||||
<% end %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-6 lg:col-span-9 lg:mt-4">
|
||||
<%= @inner_content %>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<% end %>
|
||||
@ -0,0 +1,64 @@
|
||||
<%= render_layout "app.html", assigns do %>
|
||||
<div class="container pt-6">
|
||||
<%= link("← Back to Stats",
|
||||
to: "/#{URI.encode_www_form(@site.domain)}",
|
||||
class: "text-sm text-indigo-600 font-bold"
|
||||
) %>
|
||||
<div class="pb-5 border-b border-gray-200 dark:border-gray-500">
|
||||
<h2 class="text-2xl font-bold leading-7 text-gray-900 dark:text-gray-100 sm:text-3xl sm:leading-9 sm:truncate">
|
||||
Settings for <%= @site.domain %>
|
||||
</h2>
|
||||
</div>
|
||||
<div class="lg:grid lg:grid-cols-12 lg:gap-x-5 lg:mt-4">
|
||||
<div class="py-4 g:py-0 lg:col-span-3">
|
||||
<%= form_for @conn, "/sites/#{URI.encode_www_form(@site.domain)}/monthly-report/recipients", [class: "lg:hidden"], fn f -> %>
|
||||
<%= select(f, :tab, flat_settings_options(@conn),
|
||||
class:
|
||||
"dark:bg-gray-800 mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 dark:border-gray-500 outline-none focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md dark:text-gray-100",
|
||||
onchange: "location.href = location.href.replace(/[^\/\/]*$/, event.target.value)",
|
||||
selected: List.last(@conn.path_info)
|
||||
) %>
|
||||
<% end %>
|
||||
<div class="hidden lg:block">
|
||||
<%= for %{key: key, value: value, icon: icon} <- settings_tabs(@conn) do %>
|
||||
<%= if is_binary(value) do %>
|
||||
<%= render("_settings_tab.html",
|
||||
icon: icon,
|
||||
this_tab: value,
|
||||
text: key,
|
||||
site: @site,
|
||||
conn: @conn,
|
||||
submenu?: false
|
||||
) %>
|
||||
<% else %>
|
||||
<%= render("_settings_tab.html",
|
||||
icon: icon,
|
||||
this_tab: nil,
|
||||
text: key,
|
||||
site: @site,
|
||||
conn: @conn,
|
||||
submenu?: false
|
||||
) %>
|
||||
<div class="ml-8">
|
||||
<%= for %{key: key, value: val} <- value do %>
|
||||
<%= render("_settings_tab.html",
|
||||
icon: nil,
|
||||
this_tab: val,
|
||||
text: key,
|
||||
site: @site,
|
||||
conn: @conn,
|
||||
submenu?: true
|
||||
) %>
|
||||
<% end %>
|
||||
</div>
|
||||
<% end %>
|
||||
<% end %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-6 lg:col-span-9 lg:mt-4">
|
||||
<%= @inner_content %>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<% end %>
|
||||
@ -1,7 +1,17 @@
|
||||
<%= live_render(@conn, PlausibleWeb.Live.Shields.Tabs,
|
||||
session: %{
|
||||
"site_id" => @site.id,
|
||||
"domain" => @site.domain,
|
||||
"remote_ip" => PlausibleWeb.RemoteIP.get(@conn)
|
||||
}
|
||||
) %>
|
||||
<%= case @shield do %>
|
||||
<% "ip_addresses" -> %>
|
||||
<%= live_render(@conn, PlausibleWeb.Live.Shields.IPAddresses,
|
||||
session: %{
|
||||
"site_id" => @site.id,
|
||||
"domain" => @site.domain,
|
||||
"remote_ip" => PlausibleWeb.RemoteIP.get(@conn)
|
||||
}
|
||||
) %>
|
||||
<% "countries" -> %>
|
||||
<%= live_render(@conn, PlausibleWeb.Live.Shields.Countries,
|
||||
session: %{
|
||||
"site_id" => @site.id,
|
||||
"domain" => @site.domain
|
||||
}
|
||||
) %>
|
||||
<% end %>
|
||||
|
||||
@ -0,0 +1,81 @@
|
||||
defmodule Plausible.Shield.CountryRuleCacheTest do
|
||||
use Plausible.DataCase, async: true
|
||||
|
||||
alias Plausible.Shield.CountryRule
|
||||
alias Plausible.Shield.CountryRuleCache
|
||||
alias Plausible.Shields
|
||||
|
||||
describe "public cache interface" do
|
||||
test "cache caches country rules", %{test: test} do
|
||||
{:ok, _} =
|
||||
Supervisor.start_link(
|
||||
[{CountryRuleCache, [cache_name: test, child_id: :country_rules_cache_id]}],
|
||||
strategy: :one_for_one,
|
||||
name: :"cache_supervisor_#{test}"
|
||||
)
|
||||
|
||||
site = insert(:site, domain: "site1.example.com")
|
||||
|
||||
{:ok, %{id: rid1}} = Shields.add_country_rule(site, %{"country_code" => "EE"})
|
||||
{:ok, %{id: rid2}} = Shields.add_country_rule(site, %{"country_code" => "PL"})
|
||||
|
||||
:ok = CountryRuleCache.refresh_all(cache_name: test)
|
||||
|
||||
:ok = Shields.remove_country_rule(site, rid1)
|
||||
|
||||
assert CountryRuleCache.size(test) == 2
|
||||
|
||||
assert %CountryRule{from_cache?: true, id: ^rid1} =
|
||||
CountryRuleCache.get({site.domain, "EE"}, force?: true, cache_name: test)
|
||||
|
||||
assert %CountryRule{from_cache?: true, id: ^rid2} =
|
||||
CountryRuleCache.get({site.domain, "PL"}, force?: true, cache_name: test)
|
||||
|
||||
refute CountryRuleCache.get({site.domain, "RO"}, cache_name: test, force?: true)
|
||||
end
|
||||
|
||||
test "cache allows lookups for countries on sites with changed domain", %{test: test} do
|
||||
{:ok, _} = start_test_cache(test)
|
||||
site = insert(:site, domain: "new.example.com", domain_changed_from: "old.example.com")
|
||||
|
||||
{:ok, _} = Shields.add_country_rule(site, %{"country_code" => "EE"})
|
||||
:ok = CountryRuleCache.refresh_all(cache_name: test)
|
||||
|
||||
assert CountryRuleCache.get({"old.example.com", "EE"}, force?: true, cache_name: test)
|
||||
assert CountryRuleCache.get({"new.example.com", "EE"}, force?: true, cache_name: test)
|
||||
end
|
||||
|
||||
test "refreshes only recently added country rules", %{test: test} do
|
||||
{:ok, _} = start_test_cache(test)
|
||||
|
||||
domain = "site1.example.com"
|
||||
site = insert(:site, domain: domain)
|
||||
|
||||
cache_opts = [cache_name: test, force?: true]
|
||||
|
||||
yesterday = DateTime.utc_now() |> DateTime.add(-1 * 60 * 60 * 24)
|
||||
|
||||
insert(:country_rule,
|
||||
site: site,
|
||||
inserted_at: yesterday,
|
||||
updated_at: yesterday,
|
||||
country_code: "EE"
|
||||
)
|
||||
|
||||
insert(:country_rule, site: site, country_code: "PL")
|
||||
|
||||
assert CountryRuleCache.get({domain, "EE"}, cache_opts) == nil
|
||||
assert CountryRuleCache.get({domain, "PL"}, cache_opts) == nil
|
||||
|
||||
assert :ok = CountryRuleCache.refresh_updated_recently(cache_opts)
|
||||
|
||||
refute CountryRuleCache.get({domain, "EE"}, cache_opts)
|
||||
assert %CountryRule{} = CountryRuleCache.get({domain, "PL"}, cache_opts)
|
||||
end
|
||||
end
|
||||
|
||||
defp start_test_cache(cache_name) do
|
||||
%{start: {m, f, a}} = CountryRuleCache.child_spec(cache_name: cache_name)
|
||||
apply(m, f, a)
|
||||
end
|
||||
end
|
||||
@ -0,0 +1,126 @@
|
||||
defmodule PlausibleWeb.Live.Shields.CountriesTest do
|
||||
use PlausibleWeb.ConnCase, async: true
|
||||
|
||||
import Phoenix.LiveViewTest
|
||||
import Plausible.Test.Support.HTML
|
||||
|
||||
alias Plausible.Shields
|
||||
|
||||
setup [:create_user, :create_site, :log_in]
|
||||
|
||||
describe "Country Rules - static" do
|
||||
test "renders country rules page with empty list", %{conn: conn, site: site} do
|
||||
conn = get(conn, "/#{site.domain}/settings/shields/countries")
|
||||
resp = html_response(conn, 200)
|
||||
|
||||
assert resp =~ "No Country Rules configured for this Site"
|
||||
assert resp =~ "Country Block List"
|
||||
end
|
||||
|
||||
test "lists country rules with remove actions", %{conn: conn, site: site} do
|
||||
{:ok, r1} =
|
||||
Shields.add_country_rule(site, %{"country_code" => "PL"})
|
||||
|
||||
{:ok, r2} =
|
||||
Shields.add_country_rule(site, %{"country_code" => "EE"})
|
||||
|
||||
conn = get(conn, "/#{site.domain}/settings/shields/countries")
|
||||
resp = html_response(conn, 200)
|
||||
|
||||
assert resp =~ "Poland"
|
||||
assert resp =~ "Estonia"
|
||||
|
||||
assert remove_button_1 = find(resp, "#remove-country-rule-#{r1.id}")
|
||||
assert remove_button_2 = find(resp, "#remove-country-rule-#{r2.id}")
|
||||
|
||||
assert text_of_attr(remove_button_1, "phx-click" == "remove-country-rule")
|
||||
assert text_of_attr(remove_button_1, "phx-value-rule-id" == r1.id)
|
||||
assert text_of_attr(remove_button_2, "phx-click" == "remove-country-rule")
|
||||
assert text_of_attr(remove_button_2, "phx-value-rule-id" == r2.id)
|
||||
end
|
||||
|
||||
test "add rule button is rendered", %{conn: conn, site: site} do
|
||||
conn = get(conn, "/#{site.domain}/settings/shields/countries")
|
||||
resp = html_response(conn, 200)
|
||||
|
||||
assert element_exists?(resp, ~s/button#add-country-rule[x-data]/)
|
||||
attr = text_of_attr(resp, ~s/button#add-country-rule/, "x-on:click")
|
||||
|
||||
assert attr =~ "open-modal"
|
||||
assert attr =~ "country-rule-form-modal"
|
||||
end
|
||||
|
||||
test "add rule button is not rendered when maximum reached", %{conn: conn, site: site} do
|
||||
country_codes =
|
||||
Location.Country.all()
|
||||
|> Enum.take(Shields.maximum_country_rules())
|
||||
|> Enum.map(& &1.alpha_2)
|
||||
|
||||
for cc <- country_codes do
|
||||
assert {:ok, _} =
|
||||
Shields.add_country_rule(site, %{"country_code" => "#{cc}"})
|
||||
end
|
||||
|
||||
conn = get(conn, "/#{site.domain}/settings/shields/countries")
|
||||
resp = html_response(conn, 200)
|
||||
|
||||
refute element_exists?(resp, ~s/button#add-country-rule[x-data]/)
|
||||
assert resp =~ "Maximum number of countries reached"
|
||||
assert resp =~ "You've reached the maximum number of countries you can block (30)"
|
||||
end
|
||||
end
|
||||
|
||||
describe "Country Rules - LiveView" do
|
||||
test "modal contains form", %{site: site, conn: conn} do
|
||||
lv = get_liveview(conn, site)
|
||||
html = render(lv)
|
||||
|
||||
assert element_exists?(
|
||||
html,
|
||||
~s/form[phx-submit="save-country-rule"] input[name="country_rule\[country_code\]"]/
|
||||
)
|
||||
|
||||
assert submit_button(html, ~s/form[phx-submit="save-country-rule"]/)
|
||||
end
|
||||
|
||||
test "submitting a valid country saves it", %{conn: conn, site: site} do
|
||||
lv = get_liveview(conn, site)
|
||||
|
||||
lv
|
||||
|> element("form")
|
||||
|> render_submit(%{
|
||||
"country_rule[country_code]" => "EE"
|
||||
})
|
||||
|
||||
html = render(lv)
|
||||
|
||||
assert html =~ "Estonia"
|
||||
|
||||
assert [%{country_code: "EE"}] = Shields.list_country_rules(site)
|
||||
end
|
||||
|
||||
test "clicking Remove deletes the rule", %{conn: conn, site: site} do
|
||||
{:ok, _} =
|
||||
Shields.add_country_rule(site, %{"country_code" => "EE"})
|
||||
|
||||
lv = get_liveview(conn, site)
|
||||
|
||||
html = render(lv)
|
||||
assert text_of_element(html, "table tbody td") =~ "Estonia"
|
||||
|
||||
lv |> element(~s/button[phx-click="remove-country-rule"]/) |> render_click()
|
||||
|
||||
html = render(lv)
|
||||
refute text_of_element(html, "table tbody td") =~ "Estonia"
|
||||
|
||||
assert Shields.count_country_rules(site) == 0
|
||||
end
|
||||
|
||||
defp get_liveview(conn, site) do
|
||||
conn = assign(conn, :live_module, PlausibleWeb.Live.Shields)
|
||||
{:ok, lv, _html} = live(conn, "/#{site.domain}/settings/shields/countries")
|
||||
|
||||
lv
|
||||
end
|
||||
end
|
||||
end
|
||||
Loading…
Reference in New Issue