analytics/lib/plausible_web/plugs/authorize_plugins_api.ex
hq1 19b2239eb9
Track tokens usage (#3438)
* Migration: track last seen usage for Plugins API Tokens

* Track and interpret Token.last_seen_at

* Display last used

* Order tokens by inserted date, rather than UUID :clown:

* s/Last seen/Last used in the UI

* Test for "Last used" column presence

* Fix table layout for very long descriptions

* Update lib/plausible/plugins/api/tokens.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update lib/plausible/plugins/api/token.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* Update test/plausible/plugins/api/token_test.exs

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* s/last_seen_at/last_used_at

* Update lib/plausible_web/live/plugins/api/settings.ex

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>

* fixup

* Document reasoning behind 5m windows

* s/last_seen/last_used

* Mute credo

---------

Co-authored-by: Adrian Gruntkowski <adrian.gruntkowski@gmail.com>
2023-10-18 14:14:30 +02:00

44 lines
1.1 KiB
Elixir

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
import Plug.Conn
def init(opts), do: opts
def call(conn, _opts \\ []) do
with {:ok, token} <- extract_token(conn),
{:ok, conn} <- authorize(conn, token) do
conn
end
end
defp authorize(conn, token_value) do
case Tokens.find(token_value) do
{:ok, token} ->
{:ok, token} = Tokens.update_last_seen(token)
{:ok, Plug.Conn.assign(conn, :authorized_site, token.site)}
{:error, :not_found} ->
Errors.unauthorized(conn)
end
end
defp extract_token(conn) do
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
_ ->
Errors.unauthorized(conn)
end
end
end