Skip to content

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

Account for multiple team ownerships in HS integration (#5184)

Adrian Gruntkowski3ce5f5a36282
diff --git a/extra/lib/plausible/help_scout.ex b/extra/lib/plausible/help_scout.ex
index 8362efb023..f0e7b7db5a 100644
--- a/extra/lib/plausible/help_scout.ex
+++ b/extra/lib/plausible/help_scout.ex
@@ -9,6 +9,7 @@ defmodule Plausible.HelpScout do
alias Plausible.Billing.Subscription
alias Plausible.HelpScout.Vault
alias Plausible.Repo
+ alias Plausible.Teams
alias PlausibleWeb.Router.Helpers, as: Routes
@@ -78,58 +79,87 @@ defmodule Plausible.HelpScout do
end
end
- @spec get_details_for_emails([String.t()], String.t()) :: {:ok, map()} | {:error, any()}
- def get_details_for_emails(emails, customer_id) do
+ @spec get_details_for_emails([String.t()], String.t(), String.t() | nil) ::
+ {:ok, map()} | {:error, any()}
+ def get_details_for_emails(emails, customer_id, team_identifier \\ nil) do
with {:ok, user} <- get_user(emails) do
set_mapping(customer_id, user.email)
- {team, subscription, plan} =
- case Plausible.Teams.get_by_owner(user) do
- {:ok, team} ->
- team = Plausible.Teams.with_subscription(team)
- plan = Billing.Plans.get_subscription_plan(team.subscription)
- {team, team.subscription, plan}
-
- {:error, :multiple_teams} ->
- # NOTE: We might consider exposing the other teams later on
- [team | _] = Plausible.Teams.Users.owned_teams(user)
- team = Plausible.Teams.with_subscription(team)
- plan = Billing.Plans.get_subscription_plan(team.subscription)
- {team, team.subscription, plan}
-
- {:error, :no_team} ->
- {nil, nil, nil}
- end
+ teams = Teams.Users.owned_teams(user)
- status_link =
- if team do
- Routes.kaffy_resource_url(PlausibleWeb.Endpoint, :show, :teams, :team, team.id)
+ teams =
+ if team_identifier do
+ Enum.filter(teams, &(&1.identifier == team_identifier))
else
- Routes.kaffy_resource_url(PlausibleWeb.Endpoint, :show, :auth, :user, user.id)
+ teams
end
- sites_link =
- if team do
- Routes.kaffy_resource_url(PlausibleWeb.Endpoint, :index, :sites, :site,
- custom_search: team.identifier
- )
- else
- Routes.kaffy_resource_url(PlausibleWeb.Endpoint, :index, :sites, :site,
- custom_search: user.email
- )
- end
+ if length(teams) > 1 do
+ teams =
+ teams
+ |> Enum.map(fn team ->
+ %{
+ name: Teams.name(team),
+ identifier: team.identifier,
+ sites_count: Teams.owned_sites_count(team)
+ }
+ end)
+
+ user_link = Routes.kaffy_resource_url(PlausibleWeb.Endpoint, :show, :auth, :user, user.id)
+
+ {:ok,
+ %{
+ multiple_teams?: true,
+ email: user.email,
+ notes: notes(user, nil),
+ teams: teams,
+ user_link: user_link
+ }}
+ else
+ team = List.first(teams)
- {:ok,
- %{
- email: user.email,
- notes: notes(user, team),
- status_label: status_label(team, subscription),
- status_link: status_link,
- plan_label: plan_label(subscription, plan),
- plan_link: plan_link(subscription),
- sites_count: Plausible.Teams.owned_sites_count(team),
- sites_link: sites_link
- }}
+ {subscription, plan} =
+ if team do
+ team = Teams.with_subscription(team)
+ plan = Billing.Plans.get_subscription_plan(team.subscription)
+ {team.subscription, plan}
+ else
+ {nil, nil}
+ end
+
+ status_link =
+ if team do
+ Routes.kaffy_resource_url(PlausibleWeb.Endpoint, :show, :teams, :team, team.id)
+ else
+ Routes.kaffy_resource_url(PlausibleWeb.Endpoint, :show, :auth, :user, user.id)
+ end
+
+ sites_link =
+ if team do
+ Routes.kaffy_resource_url(PlausibleWeb.Endpoint, :index, :sites, :site,
+ custom_search: team.identifier
+ )
+ else
+ Routes.kaffy_resource_url(PlausibleWeb.Endpoint, :index, :sites, :site,
+ custom_search: user.email
+ )
+ end
+
+ {:ok,
+ %{
+ multiple_teams?: false,
+ team_setup?: Plausible.Teams.setup?(team),
+ team_name: Plausible.Teams.name(team),
+ email: user.email,
+ notes: notes(user, team),
+ status_label: status_label(team, subscription),
+ status_link: status_link,
+ plan_label: plan_label(subscription, plan),
+ plan_link: plan_link(subscription),
+ sites_count: Teams.owned_sites_count(team),
+ sites_link: sites_link
+ }}
+ end
end
end
@@ -170,7 +200,7 @@ defmodule Plausible.HelpScout do
defp status_label(team, subscription) do
subscription_active? = Billing.Subscriptions.active?(subscription)
- trial? = Plausible.Teams.on_trial?(team)
+ trial? = Teams.on_trial?(team)
cond do
not subscription_active? and not trial? and (is_nil(team) or is_nil(team.trial_expiry_date)) ->
@@ -192,7 +222,7 @@ defmodule Plausible.HelpScout do
subscription.status == Subscription.Status.paused() ->
"Paused"
- Plausible.Teams.owned_sites_locked?(team) ->
+ Teams.owned_sites_locked?(team) ->
"Dashboard locked"
subscription_active? ->
diff --git a/extra/lib/plausible_web/controllers/help_scout_controller.ex b/extra/lib/plausible_web/controllers/help_scout_controller.ex
index 16b457706d..5fb68287fd 100644
--- a/extra/lib/plausible_web/controllers/help_scout_controller.ex
+++ b/extra/lib/plausible_web/controllers/help_scout_controller.ex
@@ -3,29 +3,25 @@ defmodule PlausibleWeb.HelpScoutController do
alias Plausible.HelpScout
- @conversation_cookie "helpscout_conversation"
- @conversation_cookie_seconds 8 * 60 * 60
- @signature_errors HelpScout.signature_errors()
+ @conversation_token_seconds 8 * 60 * 60
plug :make_iframe_friendly
def callback(conn, %{"customer-id" => customer_id, "conversation-id" => conversation_id}) do
- assigns = %{conversation_id: conversation_id, customer_id: customer_id}
+ token = sign_token(conversation_id)
+ assigns = %{conversation_id: conversation_id, customer_id: customer_id, token: token}
with :ok <- HelpScout.validate_signature(conn),
{:ok, details} <- HelpScout.get_details_for_customer(customer_id) do
conn
- |> set_cookie(conversation_id)
|> render("callback.html", Map.merge(assigns, details))
else
{:error, {:user_not_found, [email | _]}} ->
conn
- |> set_cookie(conversation_id)
|> render("callback.html", Map.merge(assigns, %{error: ":user_not_found", email: email}))
{:error, error} ->
conn
- |> maybe_set_cookie(error, conversation_id)
|> render("callback.html", Map.put(assigns, :error, inspect(error)))
end
end
@@ -36,24 +32,26 @@ defmodule PlausibleWeb.HelpScoutController do
def show(
conn,
- %{"email" => email, "conversation_id" => conversation_id, "customer_id" => customer_id} =
+ %{
+ "email" => email,
+ "token" => token,
+ "conversation_id" => conversation_id,
+ "customer_id" => customer_id
+ } =
params
) do
assigns = %{
xhr?: params["xhr"] == "true",
conversation_id: conversation_id,
- customer_id: customer_id
+ customer_id: customer_id,
+ token: token
}
- with :ok <- match_conversation(conn, conversation_id),
- {:ok, details} <- HelpScout.get_details_for_emails([email], customer_id) do
+ with :ok <- match_conversation(token, conversation_id),
+ {:ok, details} <-
+ HelpScout.get_details_for_emails([email], customer_id, params["team_identifier"]) do
render(conn, "callback.html", Map.merge(assigns, details))
else
- {:error, :invalid_conversation = error} ->
- conn
- |> clear_cookie()
- |> render("callback.html", Map.put(assigns, :error, inspect(error)))
-
{:error, error} ->
render(conn, "callback.html", Map.put(assigns, :error, inspect(error)))
end
@@ -61,65 +59,51 @@ defmodule PlausibleWeb.HelpScoutController do
def search(conn, %{
"term" => term,
+ "token" => token,
"conversation_id" => conversation_id,
"customer_id" => customer_id
}) do
assigns = %{
conversation_id: conversation_id,
- customer_id: customer_id
+ customer_id: customer_id,
+ token: token
}
- case match_conversation(conn, conversation_id) do
+ case match_conversation(token, conversation_id) do
:ok ->
users = HelpScout.search_users(term, customer_id)
render(conn, "search.html", Map.merge(assigns, %{users: users, term: term}))
- {:error, :invalid_conversation = error} ->
- conn
- |> clear_cookie()
- |> render("search.html", Map.put(assigns, :error, inspect(error)))
+ {:error, error} ->
+ render(conn, "search.html", Map.put(assigns, :error, inspect(error)))
end
end
- defp match_conversation(conn, conversation_id) do
- conn = fetch_cookies(conn, encrypted: [@conversation_cookie])
- cookie_conversation = conn.cookies[@conversation_cookie][:conversation_id]
-
- if cookie_conversation && conversation_id == cookie_conversation do
- :ok
- else
- {:error, :invalid_conversation}
+ defp match_conversation(token, conversation_id) do
+ case verify_token(token) do
+ {:ok, token_data} ->
+ if token_data.conversation_id == conversation_id do
+ :ok
+ else
+ {:error, :invalid_conversation}
+ end
+
+ {:error, _error} ->
+ {:error, :invalid_token}
end
end
- defp maybe_set_cookie(conn, error, conversation_id)
- when error not in @signature_errors do
- set_cookie(conn, conversation_id)
- end
-
- defp maybe_set_cookie(conn, _error, _conversation_id) do
- clear_cookie(conn)
- end
-
# Exposed for testing
@doc false
- def set_cookie(conn, conversation_id) do
- put_resp_cookie(conn, @conversation_cookie, %{conversation_id: conversation_id},
- domain: PlausibleWeb.Endpoint.host(),
- secure: true,
- encrypt: true,
- max_age: @conversation_cookie_seconds,
- same_site: "None"
- )
+ def sign_token(conversation_id) do
+ Phoenix.Token.sign(PlausibleWeb.Endpoint, "hs-conversation", %{
+ conversation_id: conversation_id
+ })
end
- defp clear_cookie(conn) do
- delete_resp_cookie(conn, @conversation_cookie,
- domain: PlausibleWeb.Endpoint.host(),
- secure: true,
- encrypt: true,
- max_age: @conversation_cookie_seconds,
- same_site: "None"
+ defp verify_token(token) do
+ Phoenix.Token.verify(PlausibleWeb.Endpoint, "hs-conversation", token,
+ max_age: @conversation_token_seconds
)
end
diff --git a/extra/lib/plausible_web/views/help_scout_view.ex b/extra/lib/plausible_web/views/help_scout_view.ex
index 5c5674b53b..3215c76402 100644
--- a/extra/lib/plausible_web/views/help_scout_view.ex
+++ b/extra/lib/plausible_web/views/help_scout_view.ex
@@ -10,50 +10,95 @@ defmodule PlausibleWeb.HelpScoutView do
<input type="text" name="term" value={assigns[:email]} />
<input type="submit" name="search" value="&nbsp;&#x1F50E;&nbsp;" />
</p>
+ <input type="hidden" name="token" value={@token} />
<input type="hidden" name="conversation_id" value={@conversation_id} />
<input type="hidden" name="customer_id" value={@customer_id} />
</form>
</div>
- <%= if @conn.assigns[:error] do %>
- <p>
- Failed to get details: {@error}
- </p>
- <% else %>
- <div class="status">
- <p class="label">
- Status
- </p>
- <p class="value">
- <a href={@status_link} target="_blank">{@status_label}</a>
+ <%= cond do %>
+ <% @conn.assigns[:error] -> %>
+ <p>
+ Failed to get details: {@error}
</p>
- </div>
+ <% @multiple_teams? -> %>
+ <div class="teams">
+ <p class="label">
+ <a href={@user_link} target="_blank">Owner</a> of teams:
+ </p>
- <div class="plan">
- <p class="label">
- Plan
- </p>
- <p class="value">
- <a href={@plan_link} target="_blank">{@plan_label}</a>
- </p>
- </div>
+ <div class="value">
+ <ul>
+ <li :for={team <- @teams}>
+ <a
+ onclick={"loadContent('/helpscout/show?#{URI.encode_query(
+ email: @email,
+ conversation_id: @conversation_id,
+ customer_id: @customer_id,
+ team_identifier: team.identifier,
+ token: @token)}')"}
+ href="#"
+ >
+ {team.name} ({team.sites_count} sites)
+ </a>
+ </li>
+ </ul>
+ </div>
+ </div>
- <div class="sites">
- <p class="label">
- Owner of <b><a href={@sites_link} target="_blank">{@sites_count} sites</a></b>
- </p>
- <p class="value"></p>
- </div>
+ <div :if={@notes} class="notes">
+ <p class="label">
+ <b>User notes</b>
+ </p>
- <div :if={@notes} class="notes">
- <p class="label">
- <b>Notes</b>
- </p>
+ <div class="value">
+ {PhoenixHTMLHelpers.Format.text_to_html(@notes, escape: true)}
+ </div>
+ </div>
+ <% true -> %>
+ <div :if={@team_setup?} class="team-name">
+ <p class="label">
+ Team name
+ </p>
+ <p class="value">
+ <a href={@status_link} target="_blank">{@team_name}</a>
+ </p>
+ </div>
+
+ <div class="status">
+ <p class="label">
+ Status
+ </p>
+ <p class="value">
+ <a href={@status_link} target="_blank">{@status_label}</a>
+ </p>
+ </div>
+
+ <div class="plan">
+ <p class="label">
+ Plan
+ </p>
+ <p class="value">
+ <a href={@plan_link} target="_blank">{@plan_label}</a>
+ </p>
+ </div>
- <div class="value">
- {PhoenixHTMLHelpers.Format.text_to_html(@notes, escape: true)}
+ <div class="sites">
+ <p class="label">
+ Owner of <b><a href={@sites_link} target="_blank">{@sites_count} sites</a></b>
+ </p>
+ <p class="value"></p>
+ </div>
+
+ <div :if={@notes} class="notes">
+ <p class="label">
+ <b>Notes</b>
+ </p>
+
+ <div class="value">
+ {PhoenixHTMLHelpers.Format.text_to_html(@notes, escape: true)}
+ </div>
</div>
- </div>
<% end %>
</.layout>
"""
@@ -73,13 +118,14 @@ defmodule PlausibleWeb.HelpScoutView do
<input type="text" name="term" value={@term} />
<input type="submit" name="search" value="&nbsp;&#x1F50E;&nbsp;" />
</p>
+ <input type="hidden" name="token" value={@token} />
<input type="hidden" name="conversation_id" value={@conversation_id} />
<input type="hidden" name="customer_id" value={@customer_id} />
</form>
<ul :if={length(@users) > 0}>
<li :for={user <- @users}>
<a
- onclick={"loadContent('/helpscout/show?#{URI.encode_query(email: user.email, conversation_id: @conversation_id, customer_id: @customer_id)}')"}
+ onclick={"loadContent('/helpscout/show?#{URI.encode_query(email: user.email, conversation_id: @conversation_id, customer_id: @customer_id, token: @token)}')"}
href="#"
>
{user.email} ({user.sites_count} sites)
@@ -147,6 +193,10 @@ defmodule PlausibleWeb.HelpScoutView do
margin-bottom: 1.25em;
}
+ .teams .label {
+ margin-bottom: 1em;
+ }
+
.value {
margin-bottom: 1.25em;
font-weight: bold;
@@ -183,37 +233,6 @@ defmodule PlausibleWeb.HelpScoutView do
const appContainer = document.getElementById("content")
- const isSafari = !!(
- navigator.vendor &&
- navigator.vendor.indexOf('Apple') > -1 &&
- navigator.userAgent &&
- navigator.userAgent.indexOf('CriOS') == -1 &&
- navigator.userAgent.indexOf('FxiOS') == -1
- )
-
- /*
- * Using cookies within iframe requires requesting storage access
- * in Safari. Unfortunately, the storage access check sometimes
- * falsely returns true in FireFox and requesting storage access
- * in FF seems to break the cookies. That's why there's an extra
- * check for Safari.
- */
- window.addEventListener('load', async () => {
- const hasStorageAccess = await document.hasStorageAccess()
- if (isSafari && !hasStorageAccess) {
- const paragraph = document.createElement('p')
- paragraph.style = "text-align: center; margin-bottom: 0.4em;"
- const button = document.createElement('button')
- button.innerHTML = 'Grant cookie access'
- button.onclick = async (e) => {
- await document.requestStorageAccess()
- paragraph.remove()
- }
- paragraph.append(button)
- appContainer.prepend(paragraph)
- }
- })
-
async function loadContent(uri) {
const response = await fetch(uri)
const html = await response.text()
diff --git a/test/plausible_web/controllers/help_scout_controller_test.exs b/test/plausible_web/controllers/help_scout_controller_test.exs
index cda615f6cb..dd5713384e 100644
--- a/test/plausible_web/controllers/help_scout_controller_test.exs
+++ b/test/plausible_web/controllers/help_scout_controller_test.exs
@@ -5,6 +5,8 @@ defmodule PlausibleWeb.HelpScoutControllerTest do
@moduletag :ee_only
on_ee do
+ import Plausible.Teams.Test
+
alias Plausible.HelpScout
describe "callback/2" do
@@ -77,10 +79,13 @@ defmodule PlausibleWeb.HelpScoutControllerTest do
insert(:user, email: "[email protected]")
insert(:user, email: "[email protected]")
+ token = sign_conversation_token("123")
+
conn =
conn
- |> set_conversation_cookie("123")
- |> get("/helpscout/search?conversation_id=123&customer_id=500&term=hs.match")
+ |> get(
+ "/helpscout/search?conversation_id=123&customer_id=500&term=hs.match&token=#{token}"
+ )
html = html_response(conn, 200)
@@ -88,17 +93,24 @@ defmodule PlausibleWeb.HelpScoutControllerTest do
refute html =~ "[email protected]"
end
- test "returns error when cookie is missing", %{conn: conn} do
- conn = get(conn, "/helpscout/search?conversation_id=123&customer_id=500&term=hs.match")
+ test "returns error when token is invalid", %{conn: conn} do
+ conn =
+ get(
+ conn,
+ "/helpscout/search?conversation_id=123&customer_id=500&term=hs.match&token=invalid"
+ )
- assert html_response(conn, 200) =~ "invalid_conversation"
+ assert html_response(conn, 200) =~ "invalid_token"
end
- test "returns error when cookie does not match", %{conn: conn} do
+ test "returns error when token does not match", %{conn: conn} do
+ token = sign_conversation_token("456")
+
conn =
conn
- |> set_conversation_cookie("456")
- |> get("/helpscout/search?conversation_id=123&customer_id=500&term=hs.match")
+ |> get(
+ "/helpscout/search?conversation_id=123&customer_id=500&term=hs.match&token=#{token}"
+ )
assert html_response(conn, 200) =~ "invalid_conversation"
end
@@ -108,11 +120,12 @@ defmodule PlausibleWeb.HelpScoutControllerTest do
test "returns details on success", %{conn: conn} do
user = insert(:user, email: "[email protected]", notes: "Some note\nwith new line")
+ token = sign_conversation_token("123")
+
conn =
conn
- |> set_conversation_cookie("123")
|> get(
- "/helpscout/show?conversation_id=123&customer_id=500&[email protected]"
+ "/helpscout/show?conversation_id=123&customer_id=500&[email protected]&token=#{token}"
)
assert html = html_response(conn, 200)
@@ -120,40 +133,122 @@ defmodule PlausibleWeb.HelpScoutControllerTest do
assert html =~ "Some note<br>\nwith new line"
end
- test "returns error when cookie is missing", %{conn: conn} do
+ test "returns teams list when the match is an owner in multiple teams", %{conn: conn} do
+ user = new_user(email: "[email protected]", notes: "Some user notes")
+ other_user = new_user()
+ _site1 = new_site(owner: user)
+ _site2 = new_site(owner: other_user)
+ _team1 = team_of(user)
+ team2 = team_of(other_user)
+
+ team2 =
+ team2
+ |> Plausible.Teams.complete_setup()
+ |> Ecto.Changeset.change(name: "HS Integration Test Team")
+ |> Plausible.Repo.update!()
+
+ add_member(team2, user: user, role: :owner)
+
+ token = sign_conversation_token("123")
+
+ conn =
+ conn
+ |> get(
+ "/helpscout/show?conversation_id=123&customer_id=500&[email protected]&token=#{token}"
+ )
+
+ assert html = html_response(conn, 200)
+ assert html =~ "/crm/auth/user/#{user.id}"
+ assert html =~ "Some user notes"
+ assert html =~ "My Personal Sites"
+ assert html =~ "HS Integration Test Team"
+ end
+
+ test "returns personal team details when identifier passed explicitly", %{conn: conn} do
+ user = new_user(email: "[email protected]", notes: "Some user notes")
+ other_user = new_user()
+ _site1 = new_site(owner: user)
+ _site2 = new_site(owner: other_user)
+ team1 = team_of(user)
+ team2 = team_of(other_user)
+
+ team2 =
+ team2
+ |> Plausible.Teams.complete_setup()
+ |> Ecto.Changeset.change(name: "HS Integration Test Team")
+ |> Plausible.Repo.update!()
+
+ add_member(team2, user: user, role: :owner)
+
+ token = sign_conversation_token("123")
+
+ conn =
+ conn
+ |> get(
+ "/helpscout/show?conversation_id=123&customer_id=500&[email protected]&team_identifier=#{team1.identifier}&token=#{token}"
+ )
+
+ assert html = html_response(conn, 200)
+ refute html =~ "HS Integration Test Team"
+ refute html =~ "My Personal Sites"
+ assert html =~ "Some user notes"
+ end
+
+ test "returns setup team details when identifier passed explicitly", %{conn: conn} do
+ user = new_user(email: "[email protected]", notes: "Some user notes")
+ other_user = new_user()
+ _site1 = new_site(owner: user)
+ _site2 = new_site(owner: other_user)
+ _team1 = team_of(user)
+ team2 = team_of(other_user)
+
+ team2 =
+ team2
+ |> Plausible.Teams.complete_setup()
+ |> Ecto.Changeset.change(name: "HS Integration Test Team")
+ |> Plausible.Repo.update!()
+
+ add_member(team2, user: user, role: :owner)
+
+ token = sign_conversation_token("123")
+
+ conn =
+ conn
+ |> get(
+ "/helpscout/show?conversation_id=123&customer_id=500&[email protected]&team_identifier=#{team2.identifier}&token=#{token}"
+ )
+
+ assert html = html_response(conn, 200)
+ assert html =~ "HS Integration Test Team"
+ refute html =~ "My Personal Sites"
+ assert html =~ "Some user notes"
+ end
+
+ test "returns error when token is invalid", %{conn: conn} do
conn =
get(
conn,
- "/helpscout/show?conversation_id=123&customer_id=500&[email protected]"
+ "/helpscout/show?conversation_id=123&customer_id=500&[email protected]&token=invalid"
)
- assert html_response(conn, 200) =~ "invalid_conversation"
+ assert html_response(conn, 200) =~ "invalid_token"
end
- test "returns error when cookie does not match", %{conn: conn} do
+ test "returns error when token does not match", %{conn: conn} do
+ token = sign_conversation_token("456")
+
conn =
conn
- |> set_conversation_cookie("456")
|> get(
- "/helpscout/show?conversation_id=123&customer_id=500&[email protected]"
+ "/helpscout/show?conversation_id=123&customer_id=500&[email protected]&token=#{token}"
)
assert html_response(conn, 200) =~ "invalid_conversation"
end
end
- defp set_conversation_cookie(conn, conversation_id) do
- conn
- |> PlausibleWeb.HelpScoutController.set_cookie(conversation_id)
- |> recycle()
- |> Map.put(:secret_key_base, secret_key_base())
- |> Plug.Conn.put_req_header("x-forwarded-for", Plausible.TestUtils.random_ip())
- end
-
- defp secret_key_base() do
- :plausible
- |> Application.fetch_env!(PlausibleWeb.Endpoint)
- |> Keyword.fetch!(:secret_key_base)
+ defp sign_conversation_token(conversation_id) do
+ PlausibleWeb.HelpScoutController.sign_token(conversation_id)
end
end
end