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
Add new actions to CRM (#4030)
Adrian Gruntkowskia8ea4ce54bdc
diff --git a/config/runtime.exs b/config/runtime.exsindex 5b7c8d852e..2f43f0b48b 100644--- a/config/runtime.exs+++ b/config/runtime.exs@@ -596,7 +596,7 @@ config :ref_inspector,config :ua_inspector,init: {Plausible.Release, :configure_ua_inspector}-if config_env() in [:dev, :staging, :prod] do+if config_env() in [:dev, :staging, :prod, :test] doconfig :kaffy,otp_app: :plausible,ecto_repo: Plausible.Repo,diff --git a/lib/plausible/auth/totp.ex b/lib/plausible/auth/totp.exindex 5854edb2f7..23529faadd 100644--- a/lib/plausible/auth/totp.ex+++ b/lib/plausible/auth/totp.ex@@ -12,11 +12,11 @@ defmodule Plausible.Auth.TOTP dovault for safe storage is configured in `Plausible.Auth.TOTP.Vault` viaa dedicated `Ecto` type defined in `Plausible.Auth.TOTP.EncryptedBinary`.The function returns updated user along with TOTP URI and a readable form- of secret. Both - the URI and readable secret - are meant for exposure+ of secret. Both - the URI and readable secret - are meant for exposurein the user's setup screen. The URI should be encoded as a QR code.After initiation, user is expected to confirm valid setup with `enable/2`,- providing TOTP code from their authenticator app. After code validation+ providing TOTP code from their authenticator app. After code validationpasses successfully, the `User.totp_enabled` flag is set to `true`.Finally, the user must be immediately presented with a list of recovery codesreturned by the same call of `enable/2`. The codes should be presented@@ -33,7 +33,10 @@ defmodule Plausible.Auth.TOTP doTOTP can be disabled with `disable/2`. User is expected to provide theircurrent password for safety. Once disabled, all TOTP user settings arecleared and any remaining generated recovery codes are removed. The function- can be safely run more than once.+ can be safely run more than once. There's also alternative call for forced+ disabling of TOTP for a given user without sending any notification,+ `force_disable/1`. It's meant for use in situation where user lost both,+ 2FA device and recovery codes and their identity is verified independently.If the user needs to regenerate the recovery codes outside of setup procedure,they must do it via `generate_recovery_codes/2`, providing their current@@ -54,7 +57,7 @@ defmodule Plausible.Auth.TOTP doIn case of TOTP codes, a grace period of 30 seconds is applied, whichallows user to use their current and previous TOTP code, assuming 30- second validity window of each. This allows user to use code that was+ second validity window of each. This allows user to use code that wasabout to expire before the submission. Regardless of that, each TOTPcode can be used only once. Validation procedure rejects repeat useof the same code for safety. It's done by tracking last time a TOTP@@ -67,7 +70,7 @@ defmodule Plausible.Auth.TOTP doTOTP token is an alternate method of authenticating user session.It's main use case is "trust this device" functionality, where user- can decide to skip 2FA verification for a particular browser session+ can decide to skip 2FA verification for a particular browser sessionfor next N days. The token should then be stored in an encrypted,signed cookie with a proper expiration timestamp.@@ -169,22 +172,7 @@ defmodule Plausible.Auth.TOTP do@spec disable(Auth.User.t(), String.t()) :: {:ok, Auth.User.t()} | {:error, :invalid_password}def disable(user, password) doif Auth.Password.match?(password, user.password_hash) do- {:ok, user} =- Repo.transaction(fn ->- {_, _} =- user- |> recovery_codes_query()- |> Repo.delete_all()-- user- |> change(- totp_enabled: false,- totp_token: nil,- totp_secret: nil,- totp_last_used_at: nil- )- |> Repo.update!()- end)+ {:ok, user} = disable_for(user)user|> Email.two_factor_disabled_email()@@ -196,6 +184,11 @@ defmodule Plausible.Auth.TOTP doendend+ @spec force_disable(Auth.User.t()) :: {:ok, Auth.User.t()}+ def force_disable(user) do+ disable_for(user)+ end+@spec reset_token(Auth.User.t()) :: Auth.User.t()def reset_token(user) donew_token =@@ -286,6 +279,24 @@ defmodule Plausible.Auth.TOTP doendend+ defp disable_for(user) do+ Repo.transaction(fn ->+ {_, _} =+ user+ |> recovery_codes_query()+ |> Repo.delete_all()++ user+ |> change(+ totp_enabled: false,+ totp_token: nil,+ totp_secret: nil,+ totp_last_used_at: nil+ )+ |> Repo.update!()+ end)+ end+defp totp_uri(user) doNimbleTOTP.otpauth_uri("#{@issuer_name}:#{user.email}", user.totp_secret,issuer: @issuer_namediff --git a/lib/plausible/auth/user_admin.ex b/lib/plausible/auth/user_admin.exindex 19cdcdd5aa..e8173d2a3f 100644--- a/lib/plausible/auth/user_admin.ex+++ b/lib/plausible/auth/user_admin.ex@@ -54,6 +54,10 @@ defmodule Plausible.Auth.UserAdmin dolock: %{name: "Lock",action: fn _, user -> lock(user) end+ },+ reset_2fa: %{+ name: "Reset 2FA",+ action: fn _, user -> disable_2fa(user) end}]end@@ -77,6 +81,10 @@ defmodule Plausible.Auth.UserAdmin doendend+ def disable_2fa(user) do+ Plausible.Auth.TOTP.force_disable(user)+ end+defp grace_period_status(%{grace_period: grace_period}) docase grace_period donil ->diff --git a/lib/plausible/site.ex b/lib/plausible/site.exindex 45a5f47f79..6e88c2e9cb 100644--- a/lib/plausible/site.ex+++ b/lib/plausible/site.ex@@ -109,7 +109,7 @@ defmodule Plausible.Site do|> cast(attrs, [:timezone,:public,- :stats_start_date,+ :native_stats_start_at,:ingest_rate_limit_threshold,:ingest_rate_limit_scale_seconds])diff --git a/lib/plausible/site/admin.ex b/lib/plausible/site/admin.exindex 7bf3e0c031..bedd8456e4 100644--- a/lib/plausible/site/admin.ex+++ b/lib/plausible/site/admin.ex@@ -1,5 +1,6 @@defmodule Plausible.SiteAdmin douse Plausible.Repo+import Ecto.Querydef ordering(_schema) do@@ -21,12 +22,21 @@ defmodule Plausible.SiteAdmin do)end+ def before_update(_conn, changeset) do+ if Ecto.Changeset.get_change(changeset, :native_stats_start_at) do+ {:ok, Ecto.Changeset.put_change(changeset, :stats_start_date, nil)}+ else+ {:ok, changeset}+ end+ end+def form_fields(_) do[domain: %{update: :readonly},timezone: %{choices: Plausible.Timezones.options()},public: nil,- stats_start_date: nil,+ stats_start_date: %{update: :readonly},+ native_stats_start_at: nil,ingest_rate_limit_scale_seconds: %{help_text: "Time scale for which events rate-limiting is calculated. Default: 60"},diff --git a/test/plausible/auth/totp_test.exs b/test/plausible/auth/totp_test.exsindex 9efe5db244..6c1007f64c 100644--- a/test/plausible/auth/totp_test.exs+++ b/test/plausible/auth/totp_test.exs@@ -206,6 +206,40 @@ defmodule Plausible.Auth.TOTPTest doendend+ describe "force_disable/1" do+ test "disables TOTP for user who has it enabled" do+ user = insert(:user, password: "VeryStrongVerySecret")+ {:ok, user, _} = TOTP.initiate(user)+ code = NimbleTOTP.verification_code(user.totp_secret)+ {:ok, user, _} = TOTP.enable(user, code)++ assert_email_delivered_with(+ to: [{user.name, user.email}],+ subject: "Plausible Two-Factor Authentication enabled"+ )++ assert {:ok, updated_user} = TOTP.force_disable(user)++ assert updated_user.id == user.id+ refute updated_user.totp_enabled+ assert is_nil(updated_user.totp_token)+ assert is_nil(updated_user.totp_secret)++ assert Repo.all(RecoveryCode) == []+ end++ test "succeeds for user who does not have TOTP enabled" do+ user = insert(:user, password: "VeryStrongVerySecret")++ assert {:ok, updated_user} = TOTP.force_disable(user)++ assert updated_user.id == user.id+ refute updated_user.totp_enabled+ assert is_nil(updated_user.totp_token)+ assert is_nil(updated_user.totp_secret)+ end+ end+describe "reset_token/1" dotest "generates new token when TOTP enabled" douser = insert(:user, password: "VeryStrongVerySecret")diff --git a/test/plausible_web/controllers/admin_controller_test.exs b/test/plausible_web/controllers/admin_controller_test.exsindex 5f12cc18b1..4b6bccc655 100644--- a/test/plausible_web/controllers/admin_controller_test.exs+++ b/test/plausible_web/controllers/admin_controller_test.exs@@ -1,5 +1,7 @@defmodule PlausibleWeb.AdminControllerTest do- use PlausibleWeb.ConnCase+ use PlausibleWeb.ConnCase, async: false++ alias Plausible.Repodescribe "GET /crm/auth/user/:user_id/usage" dosetup [:create_user, :log_in]@@ -10,4 +12,40 @@ defmodule PlausibleWeb.AdminControllerTest doassert response(conn, 403) == "Not allowed"endend++ describe "POST /crm/sites/site/:site_id" do+ setup [:create_user, :log_in]++ @tag :full_build_only+ test "resets stats start date on native stats start time change", %{conn: conn, user: user} do+ patch_env(:super_admin_user_ids, [user.id])++ site =+ insert(:site,+ public: false,+ stats_start_date: ~D[2022-03-14],+ native_stats_start_at: ~N[2024-01-22 14:28:00]+ )++ params = %{+ "site" => %{+ "domain" => site.domain,+ "timezone" => site.timezone,+ "public" => "false",+ "native_stats_start_at" => "2024-02-12 12:00:00",+ "ingest_rate_limit_scale_seconds" => site.ingest_rate_limit_scale_seconds,+ "ingest_rate_limit_threshold" => site.ingest_rate_limit_threshold+ }+ }++ conn = put(conn, "/crm/sites/site/#{site.id}", params)+ assert redirected_to(conn, 302) == "/crm/sites/site"++ site = Repo.reload!(site)++ refute site.public+ assert site.native_stats_start_at == ~N[2024-02-12 12:00:00]+ assert site.stats_start_date == nil+ end+ endend