2021-06-16 15:00:07 +03:00
|
|
|
defmodule PlausibleWeb.AuthorizeSiteAccess do
|
|
|
|
import Plug.Conn
|
|
|
|
use Plausible.Repo
|
|
|
|
|
2022-02-23 22:48:33 +03:00
|
|
|
def init([]), do: [:public, :viewer, :admin, :super_admin, :owner]
|
2021-06-16 15:00:07 +03:00
|
|
|
def init(allowed_roles), do: allowed_roles
|
|
|
|
|
|
|
|
def call(conn, allowed_roles) do
|
2022-08-05 10:24:24 +03:00
|
|
|
site =
|
|
|
|
Repo.get_by(Plausible.Site,
|
|
|
|
domain: conn.path_params["domain"] || conn.path_params["website"]
|
|
|
|
)
|
|
|
|
|
2021-06-16 15:00:07 +03:00
|
|
|
shared_link_auth = conn.params["auth"]
|
|
|
|
|
|
|
|
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
|
2021-09-30 10:45:58 +03:00
|
|
|
user_id = get_session(conn, :current_user_id)
|
|
|
|
membership_role = user_id && Plausible.Sites.role(user_id, site)
|
|
|
|
|
2021-06-16 15:00:07 +03:00
|
|
|
role =
|
|
|
|
cond do
|
2021-06-16 15:33:37 +03:00
|
|
|
user_id && membership_role ->
|
2021-06-16 15:00:07 +03:00
|
|
|
membership_role
|
|
|
|
|
2022-02-23 22:48:33 +03:00
|
|
|
Plausible.Auth.is_super_admin?(user_id) ->
|
|
|
|
:super_admin
|
|
|
|
|
2021-06-16 15:00:07 +03:00
|
|
|
site.public ->
|
|
|
|
:public
|
|
|
|
|
|
|
|
shared_link_record && shared_link_record.site_id == site.id ->
|
|
|
|
:public
|
|
|
|
|
|
|
|
true ->
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
|
|
|
|
if role in allowed_roles do
|
2022-10-18 18:11:30 +03:00
|
|
|
Sentry.Context.set_user_context(%{id: user_id})
|
|
|
|
Plausible.OpenTelemetry.add_user_attributes(user_id)
|
|
|
|
|
|
|
|
Sentry.Context.set_extra_context(%{site_id: site.id, domain: site.domain})
|
|
|
|
Plausible.OpenTelemetry.add_site_attributes(site)
|
|
|
|
|
2024-02-14 11:32:36 +03:00
|
|
|
site = Plausible.Imported.load_import_data(site)
|
|
|
|
|
2021-06-16 15:00:07 +03:00
|
|
|
merge_assigns(conn, site: site, current_user_role: role)
|
|
|
|
else
|
|
|
|
PlausibleWeb.ControllerHelpers.render_error(conn, 404) |> halt
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|