From cda031d4535bbc17a0740d7ed271ddaf093d5617 Mon Sep 17 00:00:00 2001 From: Uku Taht Date: Tue, 2 Mar 2021 11:15:43 +0200 Subject: [PATCH] Bookmarkable shared links (#752) * Implement shared links with a static URL * Separate sessio cookie from shared link cookie --- assets/js/dashboard/api.js | 8 ++- assets/js/dashboard/mount.js | 5 ++ lib/plausible/auth/token.ex | 10 +++ .../controllers/stats_controller.ex | 61 +++++++++++++------ .../plugs/authorize_stats_plug.ex | 8 ++- lib/plausible_web/router.ex | 14 ++++- .../templates/layout/app.html.eex | 48 ++++++++------- .../templates/layout/focus.html.eex | 7 ++- .../site/settings_visibility.html.eex | 2 +- .../templates/stats/stats.html.eex | 2 +- lib/plausible_web/views/site_view.ex | 5 +- .../controllers/stats_controller_test.exs | 19 ++---- 12 files changed, 121 insertions(+), 68 deletions(-) diff --git a/assets/js/dashboard/api.js b/assets/js/dashboard/api.js index d6fca56a2..d8114f1f8 100644 --- a/assets/js/dashboard/api.js +++ b/assets/js/dashboard/api.js @@ -1,6 +1,7 @@ import {formatISO} from './date' let abortController = new AbortController() +let SHARED_LINK_AUTH = null function serialize(obj) { var str = []; @@ -11,6 +12,10 @@ function serialize(obj) { return str.join("&"); } +export function setSharedLinkAuth(auth) { + SHARED_LINK_AUTH = auth +} + export function cancelAll() { abortController.abort() abortController = new AbortController() @@ -35,8 +40,9 @@ export function serializeQuery(query, extraQuery=[]) { } export function get(url, query, ...extraQuery) { + const headers = SHARED_LINK_AUTH ? {'X-Shared-Link-Auth': SHARED_LINK_AUTH} : {} url = url + serializeQuery(query, extraQuery) - return fetch(url, {signal: abortController.signal}) + return fetch(url, {signal: abortController.signal, headers: headers}) .then( response => { if (!response.ok) { throw response } return response.json() diff --git a/assets/js/dashboard/mount.js b/assets/js/dashboard/mount.js index 2b93c539e..a7b1e154b 100644 --- a/assets/js/dashboard/mount.js +++ b/assets/js/dashboard/mount.js @@ -4,6 +4,7 @@ import 'url-search-params-polyfill'; import Router from './router' import ErrorBoundary from './error-boundary' +import * as api from './api' const container = document.getElementById('stats-react-container') @@ -16,6 +17,10 @@ if (container) { } const loggedIn = container.dataset.loggedIn === 'true' + const sharedLinkAuth = container.dataset.sharedLinkAuth + if (sharedLinkAuth) { + api.setSharedLinkAuth(sharedLinkAuth) + } const app = ( diff --git a/lib/plausible/auth/token.ex b/lib/plausible/auth/token.ex index f53123f8c..01b818e46 100644 --- a/lib/plausible/auth/token.ex +++ b/lib/plausible/auth/token.ex @@ -1,6 +1,16 @@ defmodule Plausible.Auth.Token do @one_hour_in_seconds 30 * 60 + def sign_shared_link(slug) do + Phoenix.Token.sign(PlausibleWeb.Endpoint, "shared-link", %{slug: slug}) + end + + def verify_shared_link(token) do + Phoenix.Token.verify(PlausibleWeb.Endpoint, "shared-link", token, + max_age: @one_hour_in_seconds * 24 + ) + end + def sign_password_reset(email) do Phoenix.Token.sign(PlausibleWeb.Endpoint, "password-reset", %{email: email}) end diff --git a/lib/plausible_web/controllers/stats_controller.ex b/lib/plausible_web/controllers/stats_controller.ex index 8b298ccdb..1559dfd5e 100644 --- a/lib/plausible_web/controllers/stats_controller.ex +++ b/lib/plausible_web/controllers/stats_controller.ex @@ -59,22 +59,39 @@ defmodule PlausibleWeb.StatsController do |> send_resp(200, csv_content) end - def shared_link(conn, %{"slug" => slug}) do + def shared_link(conn, %{"slug" => domain, "auth" => auth}) do shared_link = - Repo.get_by(Plausible.Site.SharedLink, slug: slug) + Repo.get_by(Plausible.Site.SharedLink, slug: auth) |> Repo.preload(:site) - if shared_link do + if shared_link && shared_link.site.domain == domain do if shared_link.password_hash do - conn - |> assign(:skip_plausible_tracking, true) - |> render("shared_link_password.html", - link: shared_link, - layout: {PlausibleWeb.LayoutView, "focus.html"} - ) + with conn <- Plug.Conn.fetch_cookies(conn), + {:ok, token} <- Map.fetch(conn.req_cookies, "shared-link-token"), + {:ok, _} <- Plausible.Auth.Token.verify_shared_link(token) do + render_shared_link(conn, shared_link) + else + _e -> + conn + |> assign(:skip_plausible_tracking, true) + |> render("shared_link_password.html", + link: shared_link, + layout: {PlausibleWeb.LayoutView, "focus.html"} + ) + end else - shared_link_auth_success(conn, shared_link) + render_shared_link(conn, shared_link) end + end + end + + def shared_link(conn, %{"slug" => slug}) do + shared_link = + Repo.get_by(Plausible.Site.SharedLink, slug: slug) + |> Repo.preload(:site) + + if shared_link do + redirect(conn, to: "/share/#{URI.encode_www_form(shared_link.site.domain)}?auth=#{slug}") else render_error(conn, 404) end @@ -87,7 +104,11 @@ defmodule PlausibleWeb.StatsController do if shared_link do if Plausible.Auth.Password.match?(password, shared_link.password_hash) do - shared_link_auth_success(conn, shared_link) + token = Plausible.Auth.Token.sign_shared_link(slug) + + conn + |> put_resp_cookie("shared-link-token", token) + |> redirect(to: "/share/#{URI.encode_www_form(shared_link.site.domain)}?auth=#{slug}") else conn |> assign(:skip_plausible_tracking, true) @@ -102,14 +123,18 @@ defmodule PlausibleWeb.StatsController do end end - defp shared_link_auth_success(conn, shared_link) do - shared_link_key = "shared_link_auth_" <> shared_link.site.domain - + defp render_shared_link(conn, shared_link) do conn - |> put_session(shared_link_key, %{ - valid_until: Timex.now() |> Timex.shift(hours: 1) |> DateTime.to_unix() - }) - |> redirect(to: "/#{URI.encode_www_form(shared_link.site.domain)}") + |> assign(:skip_plausible_tracking, true) + |> put_resp_header("x-robots-tag", "noindex") + |> render("stats.html", + site: shared_link.site, + has_goals: Plausible.Sites.has_goals?(shared_link.site), + title: "Plausible · " <> shared_link.site.domain, + offer_email_report: false, + demo: false, + shared_link_auth: shared_link.slug + ) end defp remove_email_report_banner(conn, site) do diff --git a/lib/plausible_web/plugs/authorize_stats_plug.ex b/lib/plausible_web/plugs/authorize_stats_plug.ex index 21f45dc8c..4732fbe73 100644 --- a/lib/plausible_web/plugs/authorize_stats_plug.ex +++ b/lib/plausible_web/plugs/authorize_stats_plug.ex @@ -8,18 +8,20 @@ defmodule PlausibleWeb.AuthorizeStatsPlug do def call(conn, _opts) do site = Repo.get_by(Plausible.Site, domain: conn.params["domain"]) + shared_link_auth = get_req_header(conn, "x-shared-link-auth") |> List.first() + # SHOULD GENERATE A NEW PHOENIX TOKEN WHEN MOUNTING THE STATS + shared_link_record = + shared_link_auth && Repo.get_by(Plausible.Site.SharedLink, slug: shared_link_auth) if !site do PlausibleWeb.ControllerHelpers.render_error(conn, 404) |> halt else user_id = get_session(conn, :current_user_id) - shared_link_key = "shared_link_auth_" <> site.domain - shared_link_auth = get_session(conn, shared_link_key) can_access = site.public || (user_id && Plausible.Sites.is_owner?(user_id, site)) || - (shared_link_auth && shared_link_auth[:valid_until] > DateTime.to_unix(Timex.now())) + (shared_link_auth && shared_link_record && shared_link_record.site_id == site.id) if !can_access do PlausibleWeb.ControllerHelpers.render_error(conn, 404) |> halt diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.ex index 93be81db3..73d2447ef 100644 --- a/lib/plausible_web/router.ex +++ b/lib/plausible_web/router.ex @@ -15,6 +15,11 @@ defmodule PlausibleWeb.Router do plug PlausibleWeb.LastSeenPlug end + pipeline :shared_link do + plug :accepts, ["html"] + plug :put_secure_browser_headers + end + pipeline :csrf do plug :protect_from_forgery end @@ -107,6 +112,13 @@ defmodule PlausibleWeb.Router do post "/password/reset", AuthController, :password_reset end + scope "/", PlausibleWeb do + pipe_through [:shared_link] + + get "/share/:slug", StatsController, :shared_link + post "/share/:slug/authenticate", StatsController, :authenticate_shared_link + end + scope "/", PlausibleWeb do pipe_through [:browser, :csrf] @@ -197,8 +209,6 @@ defmodule PlausibleWeb.Router do delete "/:website", SiteController, :delete_site delete "/:website/stats", SiteController, :reset_stats - get "/share/:slug", StatsController, :shared_link - post "/share/:slug/authenticate", StatsController, :authenticate_shared_link get "/:domain/visitors.csv", StatsController, :csv_export get "/:domain/*path", StatsController, :stats end diff --git a/lib/plausible_web/templates/layout/app.html.eex b/lib/plausible_web/templates/layout/app.html.eex index f7ce51ff3..40568bb46 100644 --- a/lib/plausible_web/templates/layout/app.html.eex +++ b/lib/plausible_web/templates/layout/app.html.eex @@ -13,7 +13,7 @@ -