1 defmodule Pleroma.Web.OAuth.Token.Utils do
3 Auxiliary functions for dealing with tokens.
7 alias Pleroma.Web.OAuth.App
9 @doc "Fetch app by client credentials from request"
10 @spec fetch_app(Plug.Conn.t()) :: {:ok, App.t()} | {:error, :not_found}
11 def fetch_app(conn) do
14 |> fetch_client_credentials()
18 %App{} = app -> {:ok, app}
19 _ -> {:error, :not_found}
23 defp fetch_client({id, secret}) when is_binary(id) and is_binary(secret) do
24 Repo.get_by(App, client_id: id, client_secret: secret)
27 defp fetch_client({_id, _secret}), do: nil
29 defp fetch_client_credentials(conn) do
30 # Per RFC 6749, HTTP Basic is preferred to body params
31 with ["Basic " <> encoded] <- Plug.Conn.get_req_header(conn, "authorization"),
32 {:ok, decoded} <- Base.decode64(encoded),
35 String.split(decoded, ":"),
36 fn s -> URI.decode_www_form(s) end
40 _ -> {conn.params["client_id"], conn.params["client_secret"]}
44 @doc "convert token inserted_at to unix timestamp"
45 def format_created_at(%{inserted_at: inserted_at} = _token) do
47 |> DateTime.from_naive!("Etc/UTC")
52 @spec generate_token(keyword()) :: binary()
53 def generate_token(opts \\ []) do
55 |> Keyword.get(:size, 32)
56 |> :crypto.strong_rand_bytes()
57 |> Base.url_encode64(padding: false)
60 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
61 # decoding it. Investigate sometime.
62 def fix_padding(token) do
65 |> Base.url_decode64!(padding: false)
66 |> Base.url_encode64(padding: false)