analytics/lib/plausible_web/plugs/authorize_api_stats.ex
Uku Taht 5acb5b7039
Stats API (#679)
* 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
2021-02-05 11:23:30 +02:00

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