Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Add ability to create Sites API keys from Account Settings (#5361)

Adrian Gruntkowskib942081f3083
diff --git a/lib/plausible/auth/api_key.ex b/lib/plausible/auth/api_key.ex
index 8b40f81470..77d0b75a81 100644
--- a/lib/plausible/auth/api_key.ex
+++ b/lib/plausible/auth/api_key.ex
@@ -14,6 +14,8 @@ defmodule Plausible.Auth.ApiKey do
field :name, :string
field :scopes, {:array, :string}, default: ["stats:read:*"]
+ field :type, :string, virtual: true
+
field :key, :string, virtual: true
field :key_hash, :string
field :key_prefix, :string
diff --git a/lib/plausible/auth/auth.ex b/lib/plausible/auth/auth.ex
index 4ab38c48fc..04f505b94b 100644
--- a/lib/plausible/auth/auth.ex
+++ b/lib/plausible/auth/auth.ex
@@ -163,16 +163,27 @@ defmodule Plausible.Auth do
query =
from(a in Auth.ApiKey,
where: a.user_id == ^user.id,
- order_by: [desc: a.id]
+ order_by: [desc: a.id],
+ select: %{
+ a
+ | type:
+ fragment(
+ "CASE WHEN ? = ANY(?) THEN ? ELSE ? END",
+ "sites:provision:*",
+ a.scopes,
+ "sites_api",
+ "stats_api"
+ )
+ }
)
|> scope_api_keys_by_team(team)
Repo.all(query)
end
- @spec create_api_key(Auth.User.t(), Teams.Team.t(), String.t(), String.t()) ::
+ @spec create_stats_api_key(Auth.User.t(), Teams.Team.t(), String.t(), String.t()) ::
{:ok, Auth.ApiKey.t()} | {:error, Ecto.Changeset.t() | :upgrade_required}
- def create_api_key(user, team, name, key) do
+ def create_stats_api_key(user, team, name, key) do
params = %{name: name, user_id: user.id, key: key}
changeset = Auth.ApiKey.changeset(%Auth.ApiKey{}, team, params)
@@ -181,6 +192,18 @@ defmodule Plausible.Auth do
end
end
+ @spec create_sites_api_key(Auth.User.t(), Teams.Team.t(), String.t(), String.t()) ::
+ {:ok, Auth.ApiKey.t()} | {:error, Ecto.Changeset.t() | :upgrade_required}
+ def create_sites_api_key(user, team, name, key) do
+ params = %{name: name, user_id: user.id, key: key, scopes: ["sites:provision:*"]}
+ changeset = Auth.ApiKey.changeset(%Auth.ApiKey{}, team, params)
+
+ with :ok <- Billing.Feature.StatsAPI.check_availability(team),
+ :ok <- Billing.Feature.SitesAPI.check_availability(team) do
+ Repo.insert(changeset)
+ end
+ end
+
@spec delete_api_key(Auth.User.t(), integer()) :: :ok | {:error, :not_found}
def delete_api_key(user, id) do
query = from(api_key in Auth.ApiKey, where: api_key.id == ^id and api_key.user_id == ^user.id)
diff --git a/lib/plausible/crm_extensions.ex b/lib/plausible/crm_extensions.ex
index 274b8508c3..8af88a20d4 100644
--- a/lib/plausible/crm_extensions.ex
+++ b/lib/plausible/crm_extensions.ex
@@ -71,6 +71,28 @@ defmodule Plausible.CrmExtensions do
assigns: %{context: "billing", resource: "enterprise_plan", changeset: %{}}
}) do
[
+ Phoenix.HTML.raw("""
+ <script type="text/javascript">
+ (() => {
+ const statsFeature = document.querySelector(`input[type=checkbox][value=stats_api]`)
+ const sitesFeature = document.querySelector(`input[type=checkbox][value=sites_api]`)
+
+ statsFeature.addEventListener("change", () => {
+ if (!statsFeature.checked) {
+ sitesFeature.checked = false
+ }
+ return true;
+ })
+
+ sitesFeature.addEventListener("change", () => {
+ if (sitesFeature.checked) {
+ statsFeature.checked = true
+ }
+ return true;
+ })
+ })()
+ </script>
+ """),
Phoenix.HTML.raw("""
<script type="text/javascript">
(async () => {
diff --git a/lib/plausible_web/controllers/settings_controller.ex b/lib/plausible_web/controllers/settings_controller.ex
index 0457d73bce..c1757eaaf5 100644
--- a/lib/plausible_web/controllers/settings_controller.ex
+++ b/lib/plausible_web/controllers/settings_controller.ex
@@ -102,23 +102,44 @@ defmodule PlausibleWeb.SettingsController do
def new_api_key(conn, _params) do
current_team = conn.assigns[:current_team]
- changeset = Auth.ApiKey.changeset(%Auth.ApiKey{}, current_team, %{})
+ sites_api_enabled? =
+ Plausible.Billing.Feature.SitesAPI.check_availability(current_team) == :ok
- render(conn, "new_api_key.html", changeset: changeset)
+ changeset = Auth.ApiKey.changeset(%Auth.ApiKey{type: "stats_api"}, current_team, %{})
+
+ render(conn, "new_api_key.html", changeset: changeset, sites_api_enabled?: sites_api_enabled?)
end
- def create_api_key(conn, %{"api_key" => %{"name" => name, "key" => key}}) do
+ def create_api_key(conn, %{"api_key" => %{"name" => name, "key" => key, "type" => type}}) do
current_user = conn.assigns.current_user
current_team = conn.assigns.current_team
- case Auth.create_api_key(current_user, current_team, name, key) do
+ sites_api_enabled? =
+ Plausible.Billing.Feature.SitesAPI.check_availability(current_team) == :ok
+
+ api_key_fn =
+ if type == "sites_api" do
+ &Auth.create_sites_api_key/4
+ else
+ &Auth.create_stats_api_key/4
+ end
+
+ case api_key_fn.(current_user, current_team, name, key) do
{:ok, _api_key} ->
conn
|> put_flash(:success, "API key created successfully")
|> redirect(to: Routes.settings_path(conn, :api_keys) <> "#api-keys")
+ {:error, :upgrade_required} ->
+ conn
+ |> put_flash(:error, "Your current subscription plan does not include Sites API access")
+ |> redirect(to: Routes.settings_path(conn, :new_api_key))
+
{:error, changeset} ->
- render(conn, "new_api_key.html", changeset: changeset)
+ render(conn, "new_api_key.html",
+ changeset: changeset,
+ sites_api_enabled?: sites_api_enabled?
+ )
end
end
diff --git a/lib/plausible_web/live/components/form.ex b/lib/plausible_web/live/components/form.ex
index dfcfd33359..2599ab2fd9 100644
--- a/lib/plausible_web/live/components/form.ex
+++ b/lib/plausible_web/live/components/form.ex
@@ -52,6 +52,7 @@ defmodule PlausibleWeb.Live.Components.Form do
attr(:mt?, :boolean, default: true)
attr(:max_one_error, :boolean, default: false)
+ slot(:help_content)
slot(:inner_block)
def input(%{field: %Phoenix.HTML.FormField{} = field} = assigns) do
@@ -106,6 +107,36 @@ defmodule PlausibleWeb.Live.Components.Form do
"""
end
+ def input(%{type: "radio"} = assigns) do
+ ~H"""
+ <div class={[
+ "flex flex-inline items-center justify-start gap-x-3",
+ @mt? && "mt-2"
+ ]}>
+ <input
+ type="radio"
+ value={@value}
+ id={@id}
+ name={@name}
+ checked={assigns[:checked]}
+ class="block dark:bg-gray-900 h-4 w-4 mt-0.5 cursor-pointer text-indigo-600 border-gray-300 dark:border-gray-500 focus:ring-indigo-500"
+ {@rest}
+ />
+ <.label :if={@label} class="flex flex-col flex-inline" for={@id}>
+ <span>{@label}</span>
+
+ <span
+ :if={@help_text || @help_content != []}
+ class="text-gray-500 dark:text-gray-400 mb-2 text-sm"
+ >
+ {@help_text}
+ {render_slot(@help_content)}
+ </span>
+ </.label>
+ </div>
+ """
+ end
+
# All other inputs text, datetime-local, url, password, etc. are handled here...
def input(assigns) do
errors =
diff --git a/lib/plausible_web/templates/settings/api_keys.html.heex b/lib/plausible_web/templates/settings/api_keys.html.heex
index 0b23c1b6cf..191aaddc8d 100644
--- a/lib/plausible_web/templates/settings/api_keys.html.heex
+++ b/lib/plausible_web/templates/settings/api_keys.html.heex
@@ -4,7 +4,7 @@
<a id="api-keys">API Keys</a>
</:title>
<:subtitle>
- Manage your Stats API keys
+ Manage your API keys
</:subtitle>
<PlausibleWeb.Components.Billing.Notice.premium_feature
@@ -30,6 +30,9 @@
<.th hide_on_mobile>
Key
</.th>
+ <.th :if={ee?()} hide_on_mobile>
+ Type
+ </.th>
<.th invisible>
Actions
</.th>
@@ -43,6 +46,10 @@
{api_key.key_prefix}
{String.duplicate("*", 32 - 6)}
</.td>
+ <.td :if={ee?()}>
+ <span :if={api_key.type == "stats_api"}>Stats API</span>
+ <span :if={api_key.type == "sites_api"}>Sites API</span>
+ </.td>
<.td actions>
<.delete_button
method="delete"
diff --git a/lib/plausible_web/templates/settings/new_api_key.html.heex b/lib/plausible_web/templates/settings/new_api_key.html.heex
index 96bcac8aaa..af41d5db63 100644
--- a/lib/plausible_web/templates/settings/new_api_key.html.heex
+++ b/lib/plausible_web/templates/settings/new_api_key.html.heex
@@ -4,6 +4,56 @@
<.form :let={f} for={@changeset} action={Routes.settings_path(@conn, :api_keys)}>
<.input type="text" field={f[:name]} label="Name" placeholder="Development" />
+ <input :if={ce?()} type="hidden" name={f[:type].name} value={f[:type].value} />
+
+ <div :if={ee?()} x-data="{ showNotice: false }" class="mt-4 flex flex-col gap-y-2">
+ <div>
+ <.label>Type</.label>
+ </div>
+
+ <.input
+ x-on:click="showNotice = false"
+ type="radio"
+ class="block h-5 w-5 dark:bg-gray-700 border-gray-300 text-indigo-600 focus:ring-indigo-600"
+ id={f[:type].id <> "_0"}
+ name={f[:type].name}
+ value="stats_api"
+ checked={f[:type].value == "stats_api"}
+ label="Stats API"
+ >
+ <:help_content>
+ Full access to
+ <.styled_link href="https://plausible.io/docs/stats-api">Stats API</.styled_link>
+ </:help_content>
+ </.input>
+
+ <.input
+ x-on:click={"showNotice = " <> if(@sites_api_enabled?, do: "false", else: "true")}
+ type="radio"
+ id={f[:type].id <> "_1"}
+ name={f[:type].name}
+ value="sites_api"
+ checked={f[:type].value == "sites_api"}
+ label="Sites API"
+ >
+ <:help_content>
+ Full access to
+ <.styled_link href="https://plausible.io/docs/stats-api">Stats API</.styled_link>
+ and
+ <.styled_link href="https://plausible.io/docs/sites-api">Sites API</.styled_link>
+ </:help_content>
+ </.input>
+
+ <div x-show="showNotice" class="flex gap-x-2 text-sm">
+ <Heroicons.exclamation_triangle class="mt-1 block w-4 h-4 shrink-0" />
+ <div>
+ Your current subscription plan does not include Sites API access.
+ <a href="https://plausible.io/contact" class="underline">Contact us</a>
+ if interested.
+ </div>
+ </div>
+ </div>
+
<div class="mt-4">
<.input_with_clipboard id="key-input" name="api_key[key]" label="Key" value={f[:key].value} />
@@ -18,7 +68,7 @@
</p>
</div>
<.button type="submit" class="w-full">
- Continue
+ Create API key
</.button>
</.form>
</.focus_box>
diff --git a/lib/plausible_web/views/settings_view.ex b/lib/plausible_web/views/settings_view.ex
index 95b23b6dad..2aea5f271d 100644
--- a/lib/plausible_web/views/settings_view.ex
+++ b/lib/plausible_web/views/settings_view.ex
@@ -1,6 +1,7 @@
defmodule PlausibleWeb.SettingsView do
use PlausibleWeb, :view
use Phoenix.Component, global_prefixes: ~w(x-)
+ use Plausible
require Plausible.Billing.Subscription.Status
alias Plausible.Billing.{Plans, Subscription}
diff --git a/test/plausible/auth/auth_test.exs b/test/plausible/auth/auth_test.exs
index f4834afc5c..a09e10c825 100644
--- a/test/plausible/auth/auth_test.exs
+++ b/test/plausible/auth/auth_test.exs
@@ -18,12 +18,15 @@ defmodule Plausible.AuthTest do
refute Plausible.Teams.Billing.enterprise_configured?(nil)
end
- describe "create_api_key/3" do
+ describe "create_stats_api_key/3" do
test "creates a new api key" do
user = new_user(trial_expiry_date: Date.utc_today())
team = team_of(user)
key = Ecto.UUID.generate()
- assert {:ok, %Auth.ApiKey{} = api_key} = Auth.create_api_key(user, team, "my new key", key)
+
+ assert {:ok, %Auth.ApiKey{} = api_key} =
+ Auth.create_stats_api_key(user, team, "my new key", key)
+
assert api_key.team_id == team.id
assert api_key.user_id == user.id
end
@@ -34,8 +37,8 @@ defmodule Plausible.AuthTest do
u2 = new_user(trial_expiry_date: Date.utc_today())
t2 = team_of(u2)
key = Ecto.UUID.generate()
- assert {:ok, %Auth.ApiKey{}} = Auth.create_api_key(u1, t1, "my new key", key)
- assert {:error, changeset} = Auth.create_api_key(u2, t2, "my other key", key)
+ assert {:ok, %Auth.ApiKey{}} = Auth.create_stats_api_key(u1, t1, "my new key", key)
+ assert {:error, changeset} = Auth.create_stats_api_key(u2, t2, "my other key", key)
assert changeset.errors[:key] ==
{"has already been taken",
@@ -48,7 +51,7 @@ defmodule Plausible.AuthTest do
team = team_of(user)
assert {:error, :upgrade_required} =
- Auth.create_api_key(user, team, "my new key", Ecto.UUID.generate())
+ Auth.create_stats_api_key(user, team, "my new key", Ecto.UUID.generate())
end
test "creates a key for user in a team with a bunsiness plan" do
@@ -58,7 +61,60 @@ defmodule Plausible.AuthTest do
add_member(another_site.team, user: user, role: :owner)
assert {:ok, %Auth.ApiKey{}} =
- Auth.create_api_key(user, team, "my new key", Ecto.UUID.generate())
+ Auth.create_stats_api_key(user, team, "my new key", Ecto.UUID.generate())
+ end
+ end
+
+ describe "create_sites_api_key/3" do
+ test "creates a new api key for user on enterprise plan with SitesAPI enabled" do
+ user =
+ new_user()
+ |> subscribe_to_enterprise_plan(
+ features: [Plausible.Billing.Feature.StatsAPI, Plausible.Billing.Feature.SitesAPI]
+ )
+
+ team = team_of(user)
+ key = Ecto.UUID.generate()
+
+ assert {:ok, %Auth.ApiKey{} = api_key} =
+ Auth.create_sites_api_key(user, team, "my new key", key)
+
+ assert api_key.team_id == team.id
+ assert api_key.user_id == user.id
+ end
+
+ test "errors when key already exists" do
+ u1 =
+ new_user()
+ |> subscribe_to_enterprise_plan(
+ features: [Plausible.Billing.Feature.StatsAPI, Plausible.Billing.Feature.SitesAPI]
+ )
+
+ t1 = team_of(u1)
+
+ u2 =
+ new_user()
+ |> subscribe_to_enterprise_plan(
+ features: [Plausible.Billing.Feature.StatsAPI, Plausible.Billing.Feature.SitesAPI]
+ )
+
+ t2 = team_of(u2)
+ key = Ecto.UUID.generate()
+ assert {:ok, %Auth.ApiKey{}} = Auth.create_sites_api_key(u1, t1, "my new key", key)
+ assert {:error, changeset} = Auth.create_sites_api_key(u2, t2, "my other key", key)
+
+ assert changeset.errors[:key] ==
+ {"has already been taken",
+ [constraint: :unique, constraint_name: "api_keys_key_hash_index"]}
+ end
+
+ @tag :ee_only
+ test "returns error when team is on a business plan" do
+ user = new_user() |> subscribe_to_business_plan()
+ team = team_of(user)
+
+ assert {:error, :upgrade_required} =
+ Auth.create_sites_api_key(user, team, "my new key", Ecto.UUID.generate())
end
end
@@ -66,7 +122,10 @@ defmodule Plausible.AuthTest do
test "deletes the record" do
user = new_user(trial_expiry_date: Date.utc_today())
team = team_of(user)
- assert {:ok, api_key} = Auth.create_api_key(user, team, "my new key", Ecto.UUID.generate())
+
+ assert {:ok, api_key} =
+ Auth.create_stats_api_key(user, team, "my new key", Ecto.UUID.generate())
+
assert :ok = Auth.delete_api_key(user, api_key.id)
refute Plausible.Repo.reload(api_key)
end
@@ -78,7 +137,7 @@ defmodule Plausible.AuthTest do
other_team = team_of(other_user)
{:ok, other_api_key} =
- Auth.create_api_key(other_user, other_team, "my new key", Ecto.UUID.generate())
+ Auth.create_stats_api_key(other_user, other_team, "my new key", Ecto.UUID.generate())
assert {:error, :not_found} = Auth.delete_api_key(me, other_api_key.id)
assert {:error, :not_found} = Auth.delete_api_key(me, -1)
diff --git a/test/plausible_web/controllers/settings_controller_test.exs b/test/plausible_web/controllers/settings_controller_test.exs
index 9eb1fef9eb..17f21607d1 100644
--- a/test/plausible_web/controllers/settings_controller_test.exs
+++ b/test/plausible_web/controllers/settings_controller_test.exs
@@ -1022,6 +1022,24 @@ defmodule PlausibleWeb.SettingsControllerTest do
assert html_response(conn, 200)
end
+
+ @tag :ee_only
+ test "lists types of keys", %{conn: conn, user: user} do
+ user
+ |> subscribe_to_enterprise_plan(
+ features: [Plausible.Billing.Feature.StatsAPI, Plausible.Billing.Feature.SitesAPI]
+ )
+
+ insert(:api_key, user: user)
+ insert(:api_key, user: user, scopes: ["sites:provision:*"])
+
+ conn = get(conn, Routes.settings_path(conn, :api_keys))
+
+ assert html = html_response(conn, 200)
+
+ assert html =~ "Stats API"
+ assert html =~ "Sites API"
+ end
end
describe "POST /settings/api-keys" do
@@ -1037,7 +1055,37 @@ defmodule PlausibleWeb.SettingsControllerTest do
"api_key" => %{
"user_id" => user.id,
"name" => "all your code are belong to us",
- "key" => "swordfish"
+ "key" => "swordfish",
+ "type" => "stats_api"
+ }
+ })
+
+ key = Plausible.Auth.ApiKey |> where(user_id: ^user.id) |> Repo.one()
+ assert conn.status == 302
+ assert key.name == "all your code are belong to us"
+ assert key.team_id == team.id
+ end
+
+ test "can create a Sites API key", %{conn: conn, user: user} do
+ user
+ |> subscribe_to_enterprise_plan(
+ features: [
+ Plausible.Billing.Feature.StatsAPI,
+ Plausible.Billing.Feature.SitesAPI
+ ]
+ )
+
+ new_site(owner: user)
+
+ team = team_of(user)
+
+ conn =
+ post(conn, Routes.settings_path(conn, :api_keys), %{
+ "api_key" => %{
+ "user_id" => user.id,
+ "name" => "all your code are belong to us",
+ "key" => "swordfish",
+ "type" => "sites_api"
}
})
@@ -1045,6 +1093,28 @@ defmodule PlausibleWeb.SettingsControllerTest do
assert conn.status == 302
assert key.name == "all your code are belong to us"
assert key.team_id == team.id
+ assert key.scopes == ["sites:provision:*"]
+ end
+
+ test "can't create a Sites API key without Sites API feature", %{conn: conn, user: user} do
+ user |> subscribe_to_business_plan()
+
+ new_site(owner: user)
+
+ conn =
+ post(conn, Routes.settings_path(conn, :api_keys), %{
+ "api_key" => %{
+ "user_id" => user.id,
+ "name" => "all your code are belong to us",
+ "key" => "swordfish",
+ "type" => "sites_api"
+ }
+ })
+
+ assert redirected_to(conn, 302) == Routes.settings_path(conn, :new_api_key)
+
+ assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
+ "Your current subscription plan does not include Sites API access"
end
test "can create an API key when switched to another team", %{conn: conn, user: user} do
@@ -1061,7 +1131,8 @@ defmodule PlausibleWeb.SettingsControllerTest do
"api_key" => %{
"user_id" => user.id,
"name" => "all your code are belong to us",
- "key" => "swordfish"
+ "key" => "swordfish",
+ "type" => "stats_api"
}
})
@@ -1079,7 +1150,8 @@ defmodule PlausibleWeb.SettingsControllerTest do
"api_key" => %{
"user_id" => user.id,
"name" => "all your code are belong to us",
- "key" => "swordfish"
+ "key" => "swordfish",
+ "type" => "stats_api"
}
})
@@ -1088,7 +1160,8 @@ defmodule PlausibleWeb.SettingsControllerTest do
"api_key" => %{
"user_id" => user.id,
"name" => "all your code are belong to us",
- "key" => "swordfish"
+ "key" => "swordfish",
+ "type" => "stats_api"
}
})
@@ -1105,7 +1178,8 @@ defmodule PlausibleWeb.SettingsControllerTest do
"api_key" => %{
"user_id" => other_user.id,
"name" => "all your code are belong to us",
- "key" => "swordfish"
+ "key" => "swordfish",
+ "type" => "stats_api"
}
})