2023-09-26 14:13:08 +03:00
|
|
|
defmodule PlausibleWeb.Plugs.AuthorizePluginsAPI do
|
|
|
|
@moduledoc """
|
|
|
|
Plug for Basic HTTP Authentication using
|
|
|
|
Plugins API Tokens lookup.
|
|
|
|
"""
|
|
|
|
|
|
|
|
alias PlausibleWeb.Plugins.API.Errors
|
|
|
|
alias Plausible.Plugins.API.Tokens
|
2023-10-16 14:22:09 +03:00
|
|
|
import Plug.Conn
|
2023-09-26 14:13:08 +03:00
|
|
|
|
|
|
|
def init(opts), do: opts
|
|
|
|
|
|
|
|
def call(conn, _opts \\ []) do
|
2023-10-16 14:22:09 +03:00
|
|
|
with {:ok, token} <- extract_token(conn),
|
|
|
|
{:ok, conn} <- authorize(conn, token) do
|
2023-09-26 14:13:08 +03:00
|
|
|
conn
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-10-16 14:22:09 +03:00
|
|
|
defp authorize(conn, token_value) do
|
|
|
|
case Tokens.find(token_value) do
|
2023-09-26 14:13:08 +03:00
|
|
|
{:ok, token} ->
|
2023-10-18 15:14:30 +03:00
|
|
|
{:ok, token} = Tokens.update_last_seen(token)
|
2023-09-26 14:13:08 +03:00
|
|
|
{:ok, Plug.Conn.assign(conn, :authorized_site, token.site)}
|
|
|
|
|
|
|
|
{:error, :not_found} ->
|
|
|
|
Errors.unauthorized(conn)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
defp extract_token(conn) do
|
2023-10-16 14:22:09 +03:00
|
|
|
with ["Basic " <> encoded_user_and_pass] <- get_req_header(conn, "authorization"),
|
|
|
|
{:ok, decoded_user_and_pass} <- Base.decode64(encoded_user_and_pass) do
|
|
|
|
case :binary.split(decoded_user_and_pass, ":") do
|
|
|
|
[_user, token_value] -> {:ok, token_value}
|
|
|
|
[token_value] -> {:ok, token_value}
|
|
|
|
end
|
|
|
|
else
|
|
|
|
_ ->
|
2023-09-26 14:13:08 +03:00
|
|
|
Errors.unauthorized(conn)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|