Merge remote-tracking branch 'origin/develop' into conversations-import
[akkoma] / lib / pleroma / web / oauth / token / utils.ex
1 defmodule Pleroma.Web.OAuth.Token.Utils do
2 @moduledoc """
3 Auxiliary functions for dealing with tokens.
4 """
5
6 alias Pleroma.Repo
7 alias Pleroma.Web.OAuth.App
8
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
12 res =
13 conn
14 |> fetch_client_credentials()
15 |> fetch_client
16
17 case res do
18 %App{} = app -> {:ok, app}
19 _ -> {:error, :not_found}
20 end
21 end
22
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)
25 end
26
27 defp fetch_client({_id, _secret}), do: nil
28
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),
33 [id, secret] <-
34 Enum.map(
35 String.split(decoded, ":"),
36 fn s -> URI.decode_www_form(s) end
37 ) do
38 {id, secret}
39 else
40 _ -> {conn.params["client_id"], conn.params["client_secret"]}
41 end
42 end
43
44 @doc "convert token inserted_at to unix timestamp"
45 def format_created_at(%{inserted_at: inserted_at} = _token) do
46 inserted_at
47 |> DateTime.from_naive!("Etc/UTC")
48 |> DateTime.to_unix()
49 end
50
51 @doc false
52 @spec generate_token(keyword()) :: binary()
53 def generate_token(opts \\ []) do
54 opts
55 |> Keyword.get(:size, 32)
56 |> :crypto.strong_rand_bytes()
57 |> Base.url_encode64(padding: false)
58 end
59
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
63 token
64 |> URI.decode()
65 |> Base.url_decode64!(padding: false)
66 |> Base.url_encode64(padding: false)
67 end
68 end