2021-04-09 10:30:51 +03:00
|
|
|
defmodule PlausibleWeb.AuthorizeSitesApiPlug do
|
2021-02-05 12:23:30 +03:00
|
|
|
import Plug.Conn
|
|
|
|
use Plausible.Repo
|
|
|
|
alias Plausible.Auth.ApiKey
|
2021-04-15 11:38:44 +03:00
|
|
|
alias PlausibleWeb.Api.Helpers, as: H
|
2021-02-05 12:23:30 +03:00
|
|
|
|
|
|
|
def init(options) do
|
|
|
|
options
|
|
|
|
end
|
|
|
|
|
|
|
|
def call(conn, _opts) do
|
2021-04-09 10:30:51 +03:00
|
|
|
with {:ok, raw_api_key} <- get_bearer_token(conn),
|
|
|
|
{:ok, api_key} <- verify_access(raw_api_key) do
|
|
|
|
assign(conn, :current_user_id, api_key.user_id)
|
2021-02-05 12:23:30 +03:00
|
|
|
else
|
2021-02-22 11:21:25 +03:00
|
|
|
{:error, :missing_api_key} ->
|
2021-04-15 11:38:44 +03:00
|
|
|
H.unauthorized(
|
2021-02-22 11:21:25 +03:00
|
|
|
conn,
|
|
|
|
"Missing API key. Please use a valid Plausible API key as a Bearer Token."
|
|
|
|
)
|
|
|
|
|
|
|
|
{:error, :invalid_api_key} ->
|
2021-04-15 11:38:44 +03:00
|
|
|
H.unauthorized(
|
2021-02-22 11:21:25 +03:00
|
|
|
conn,
|
2021-04-09 11:53:41 +03:00
|
|
|
"Invalid API key. Please make sure you're using a valid API key with access to the resource you've requested."
|
2021-02-22 11:21:25 +03:00
|
|
|
)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2021-04-09 10:30:51 +03:00
|
|
|
defp verify_access(api_key) do
|
2021-02-22 11:21:25 +03:00
|
|
|
hashed_key = ApiKey.do_hash(api_key)
|
2021-04-09 11:53:41 +03:00
|
|
|
|
|
|
|
found_key =
|
|
|
|
Repo.one(
|
|
|
|
from a in ApiKey,
|
|
|
|
where: a.key_hash == ^hashed_key,
|
|
|
|
where: fragment("? @> ?", a.scopes, ["sites:provision:*"])
|
|
|
|
)
|
2021-02-22 11:21:25 +03:00
|
|
|
|
|
|
|
cond do
|
2021-04-09 10:30:51 +03:00
|
|
|
found_key -> {:ok, found_key}
|
2021-02-22 11:21:25 +03:00
|
|
|
true -> {:error, :invalid_api_key}
|
2021-02-05 12:23:30 +03:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
defp get_bearer_token(conn) do
|
|
|
|
authorization_header =
|
|
|
|
Plug.Conn.get_req_header(conn, "authorization")
|
|
|
|
|> List.first()
|
|
|
|
|
|
|
|
case authorization_header do
|
2021-02-22 11:21:25 +03:00
|
|
|
"Bearer " <> token -> {:ok, String.trim(token)}
|
|
|
|
_ -> {:error, :missing_api_key}
|
2021-02-05 12:23:30 +03:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|