mirror of
https://github.com/plausible/analytics.git
synced 2024-12-01 03:48:35 +03:00
5acb5b7039
* WIP * Add ability to filter by anything * Add API keys * Add version to api endpoint * Fix API test route * Fix API tests * Allow 'date' parameter in '6mo' and '12mo' * Rename session -> visit in API filters * Filter expressions in the API * Implement filters in aggregate call * Add `compare` option to aggregate call * Add way to manage API keys through the UI * Authenticate with API key * Use API key in tests
47 lines
1.0 KiB
Elixir
47 lines
1.0 KiB
Elixir
defmodule PlausibleWeb.AuthorizeApiStatsPlug do
|
|
import Plug.Conn
|
|
use Plausible.Repo
|
|
alias Plausible.Auth.ApiKey
|
|
|
|
def init(options) do
|
|
options
|
|
end
|
|
|
|
def call(conn, _opts) do
|
|
site = Repo.get_by(Plausible.Site, domain: conn.params["site_id"])
|
|
api_key = get_bearer_token(conn)
|
|
|
|
if !(site && api_key) do
|
|
not_found(conn)
|
|
else
|
|
hashed_key = ApiKey.do_hash(api_key)
|
|
found_key = Repo.get_by(ApiKey, key_hash: hashed_key)
|
|
can_access = found_key && Plausible.Sites.is_owner?(found_key.user_id, site)
|
|
|
|
if !can_access do
|
|
not_found(conn)
|
|
else
|
|
assign(conn, :site, site)
|
|
end
|
|
end
|
|
end
|
|
|
|
defp get_bearer_token(conn) do
|
|
authorization_header =
|
|
Plug.Conn.get_req_header(conn, "authorization")
|
|
|> List.first()
|
|
|
|
case authorization_header do
|
|
"Bearer " <> token -> String.trim(token)
|
|
_ -> nil
|
|
end
|
|
end
|
|
|
|
defp not_found(conn) do
|
|
conn
|
|
|> put_status(404)
|
|
|> Phoenix.Controller.json(%{error: "Not found"})
|
|
|> halt()
|
|
end
|
|
end
|