Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Track tokens usage (#3438)
hq119b2239eb9c9
diff --git a/lib/plausible/plugins/api/token.ex b/lib/plausible/plugins/api/token.exindex aac7f14e09..010cb83dba 100644--- a/lib/plausible/plugins/api/token.ex+++ b/lib/plausible/plugins/api/token.ex@@ -23,6 +23,7 @@ defmodule Plausible.Plugins.API.Token dofield(:token_hash, :binary)field(:description, :string)field(:hint, :string)+ field(:last_used_at, :naive_datetime)belongs_to(:site, Site)end@@ -69,6 +70,27 @@ defmodule Plausible.Plugins.API.Token doendend+ @spec last_used_humanize(t()) :: String.t()+ # credo:disable-for-next-line Credo.Check.Refactor.CyclomaticComplexity+ def last_used_humanize(token) do+ diff =+ if token.last_used_at do+ now = NaiveDateTime.utc_now()+ Timex.diff(now, token.last_used_at, :minutes)+ end++ cond do+ is_nil(diff) -> "Not yet"+ diff < 5 -> "Just recently"+ diff < 30 -> "Several minutes ago"+ diff < 70 -> "An hour ago"+ diff < 24 * 60 -> "Hours ago"+ diff < 24 * 60 * 2 -> "Yesterday"+ diff < 24 * 60 * 7 -> "Sometime this week"+ true -> "Long time ago"+ end+ end+defp prefixed(random_bytes) doEnum.join([prefix(), random_bytes], "-")enddiff --git a/lib/plausible/plugins/api/tokens.ex b/lib/plausible/plugins/api/tokens.exindex 42f3e0bb49..d325599667 100644--- a/lib/plausible/plugins/api/tokens.ex+++ b/lib/plausible/plugins/api/tokens.ex@@ -39,17 +39,36 @@ defmodule Plausible.Plugins.API.Tokens do@spec delete(Site.t(), String.t()) :: :okdef delete(site, token_id) do- Repo.delete_all(from t in Token, where: t.site_id == ^site.id and t.id == ^token_id)+ Repo.delete_all(from(t in Token, where: t.site_id == ^site.id and t.id == ^token_id)):okend@spec list(Site.t()) :: {:ok, [Token.t()]}def list(site) do- Repo.all(from t in Token, where: t.site_id == ^site.id, order_by: [desc: t.id])+ Repo.all(+ from(t in Token, where: t.site_id == ^site.id, order_by: [desc: t.inserted_at, desc: t.id])+ )end@spec any?(Site.t()) :: boolean()def any?(site) doRepo.exists?(from(t in Token, where: t.site_id == ^site.id))end++ @spec update_last_seen(Token.t(), NaiveDateTime.t()) :: {:ok, Token.t()}+ def update_last_seen(token, now \\ NaiveDateTime.utc_now()) do+ # we don't need very precise timestamp tracking, and to spare postgres we only+ # update that timestamp in 5m windows - this is mostly to help users reason+ # about what token they have, in case of rotations+ now = NaiveDateTime.truncate(now, :second)+ last_used = token.last_used_at++ if is_nil(last_used) or Timex.diff(now, last_used, :minutes) > 5 do+ token+ |> Ecto.Changeset.change(%{last_used_at: now})+ |> Repo.update()+ else+ {:ok, token}+ end+ endenddiff --git a/lib/plausible_web/live/plugins/api/settings.ex b/lib/plausible_web/live/plugins/api/settings.exindex 40c2b82802..4fa466b3e1 100644--- a/lib/plausible_web/live/plugins/api/settings.ex+++ b/lib/plausible_web/live/plugins/api/settings.ex@@ -67,17 +67,23 @@ defmodule PlausibleWeb.Live.Plugins.API.Settings do<tr><thscope="col"- class="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase dark:text-gray-100"+ class="px-6 py-3 text-xs font-medium text-left text-gray-500 uppercase dark:text-gray-100">Description</th><thscope="col"- class="px-6 py-3 text-xs font-medium tracking-wider text-left text-gray-500 uppercase dark:text-gray-100"+ class="px-6 py-3 text-xs font-medium text-left text-gray-500 uppercase dark:text-gray-100">Hint</th>- <th scope="col" class="relative px-6 py-3">+ <th+ scope="col"+ class="px-6 py-3 text-xs font-medium text-left text-gray-500 uppercase dark:text-gray-100"+ >+ Last used+ </th>+ <th scope="col" class="px-6 py-3"><span class="sr-only">Revoke</span></th></tr>@@ -85,13 +91,18 @@ defmodule PlausibleWeb.Live.Plugins.API.Settings do<tbody><%= for token <- @displayed_tokens do %><tr class="bg-white dark:bg-gray-800">- <td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-gray-100 whitespace-nowrap">- <span class="token-description"><%= token.description %></span>+ <td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-gray-100">+ <span class="token-description">+ <%= token.description %>+ </span></td>- <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-100 whitespace-nowrap font-mono">+ <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-100 font-mono">**********<%= token.hint %></td>- <td class="px-6 py-4 text-sm font-medium text-right whitespace-nowrap">+ <td class="px-6 py-4 text-sm font-normal whitespace-nowrap">+ <%= Plausible.Plugins.API.Token.last_used_humanize(token) %>+ </td>+ <td class="px-6 py-4 text-sm font-medium text-right"><buttonid={"revoke-token-#{token.id}"}phx-click="revoke-token"diff --git a/lib/plausible_web/plugs/authorize_plugins_api.ex b/lib/plausible_web/plugs/authorize_plugins_api.exindex 07460f5434..f693a7fc02 100644--- a/lib/plausible_web/plugs/authorize_plugins_api.ex+++ b/lib/plausible_web/plugs/authorize_plugins_api.ex@@ -20,6 +20,7 @@ defmodule PlausibleWeb.Plugs.AuthorizePluginsAPI dodefp authorize(conn, token_value) docase Tokens.find(token_value) do{:ok, token} ->+ {:ok, token} = Tokens.update_last_seen(token){:ok, Plug.Conn.assign(conn, :authorized_site, token.site)}{:error, :not_found} ->diff --git a/priv/repo/migrations/20231018081657_add_last_used_at_to_plugins_api_tokens.exs b/priv/repo/migrations/20231018081657_add_last_used_at_to_plugins_api_tokens.exsnew file mode 100644index 0000000000..c4cb200bad--- /dev/null+++ b/priv/repo/migrations/20231018081657_add_last_used_at_to_plugins_api_tokens.exs@@ -0,0 +1,9 @@+defmodule Plausible.Repo.Migrations.AddLastUsedAtToPluginsApiTokens do+ use Ecto.Migration++ def change do+ alter table("plugins_api_tokens") do+ add(:last_used_at, :naive_datetime)+ end+ end+enddiff --git a/test/plausible/plugins/api/token_test.exs b/test/plausible/plugins/api/token_test.exsindex 94b2887b0c..57c848f5d4 100644--- a/test/plausible/plugins/api/token_test.exs+++ b/test/plausible/plugins/api/token_test.exs@@ -70,4 +70,23 @@ defmodule Plausible.Plugins.API.TokenTest doassert Ecto.Changeset.get_field(changeset, :site).id == 1_892_787endend++ test "last_used_humanize/1" do+ now = NaiveDateTime.utc_now()++ last_seen = fn shift ->+ Token.last_used_humanize(%Token{last_used_at: Timex.shift(now, shift)})+ end++ assert Token.last_used_humanize(%Token{}) == "Not yet"++ assert last_seen.(minutes: -1) == "Just recently"+ assert last_seen.(minutes: -4) == "Just recently"+ assert last_seen.(minutes: -6) == "Several minutes ago"+ assert last_seen.(hours: -1) == "An hour ago"+ assert last_seen.(hours: -7) == "Hours ago"+ assert last_seen.(days: -1) == "Yesterday"+ assert last_seen.(days: -3) == "Sometime this week"+ assert last_seen.(months: -1) == "Long time ago"+ endenddiff --git a/test/plausible/plugins/api/tokens_test.exs b/test/plausible/plugins/api/tokens_test.exsindex c085a324e0..43538f7f67 100644--- a/test/plausible/plugins/api/tokens_test.exs+++ b/test/plausible/plugins/api/tokens_test.exs@@ -73,4 +73,22 @@ defmodule Plausible.Plugins.API.TokensTest doassert Tokens.any?(site2)endend++ describe "update_last_seen/1" do+ test "updates in 5m window" do+ site = insert(:site)+ assert {:ok, token0, _} = Tokens.create(site, "My test token")++ now = NaiveDateTime.utc_now()++ {:ok, token1} = Tokens.update_last_seen(token0, now)+ {:ok, token2} = Tokens.update_last_seen(token1, Timex.shift(now, minutes: 2))++ assert token1.last_used_at == token2.last_used_at++ {:ok, token3} = Tokens.update_last_seen(token2, Timex.shift(now, minutes: 6))++ assert NaiveDateTime.compare(token3.last_used_at, token2.last_used_at) == :gt+ end+ endenddiff --git a/test/plausible_web/live/plugins_api_tokens_test.exs b/test/plausible_web/live/plugins_api_tokens_test.exsindex 9a509ae337..a2f2333c4f 100644--- a/test/plausible_web/live/plugins_api_tokens_test.exs+++ b/test/plausible_web/live/plugins_api_tokens_test.exs@@ -46,6 +46,10 @@ defmodule PlausibleWeb.Live.PluginsAPISettingsTest doassert resp =~ "test-token-1"assert resp =~ "test-token-2"++ assert resp =~ "Last used"+ assert resp =~ "Not yet"+assert resp =~ "**********" <> t1.hintassert resp =~ "**********" <> t2.hintrefute resp =~ "test-token-3"diff --git a/test/plausible_web/plugs/authorize_plugins_api_test.exs b/test/plausible_web/plugs/authorize_plugins_api_test.exsindex e1914043f9..30d5f329b0 100644--- a/test/plausible_web/plugs/authorize_plugins_api_test.exs+++ b/test/plausible_web/plugs/authorize_plugins_api_test.exs@@ -1,8 +1,9 @@defmodule PlausibleWeb.Plugs.AuthorizePluginsAPITest douse PlausibleWeb.ConnCase, async: true- alias Plausible.Plugins.API.Tokens+ alias Plausible.Plugins.API.{Token, Tokens}alias PlausibleWeb.Plugs.AuthorizePluginsAPI+ alias Plausible.Repoimport Plug.Conn@@ -68,4 +69,22 @@ defmodule PlausibleWeb.Plugs.AuthorizePluginsAPITest do]}end++ test "plug updates last seen timestamp" do+ site = insert(:site, domain: "pass.example.com")+ {:ok, token, raw} = Tokens.create(site, "Some token")++ refute token.last_used_at+ assert Token.last_used_humanize(token) == "Not yet"++ credentials = "Basic " <> Base.encode64(raw)++ build_conn()+ |> put_req_header("authorization", credentials)+ |> AuthorizePluginsAPI.call()++ token = Repo.reload!(token)+ assert token.last_used_at+ assert Token.last_used_humanize(token) == "Just recently"+ endend