1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.OAuth.Token.Utils do
7 Auxiliary functions for dealing with tokens.
11 alias Pleroma.Web.OAuth.App
13 @doc "Fetch app by client credentials from request"
14 @spec fetch_app(Plug.Conn.t()) :: {:ok, App.t()} | {:error, :not_found}
15 def fetch_app(conn) do
18 |> fetch_client_credentials()
22 %App{} = app -> {:ok, app}
23 _ -> {:error, :not_found}
27 defp fetch_client({id, secret}) when is_binary(id) and is_binary(secret) do
28 Repo.get_by(App, client_id: id, client_secret: secret)
31 defp fetch_client({_id, _secret}), do: nil
33 defp fetch_client_credentials(conn) do
34 # Per RFC 6749, HTTP Basic is preferred to body params
35 with ["Basic " <> encoded] <- Plug.Conn.get_req_header(conn, "authorization"),
36 {:ok, decoded} <- Base.decode64(encoded),
39 String.split(decoded, ":"),
40 fn s -> URI.decode_www_form(s) end
44 _ -> {conn.params["client_id"], conn.params["client_secret"]}
48 @doc "convert token inserted_at to unix timestamp"
49 def format_created_at(%{inserted_at: inserted_at} = _token) do
51 |> DateTime.from_naive!("Etc/UTC")
56 @spec generate_token(keyword()) :: binary()
57 def generate_token(opts \\ []) do
59 |> Keyword.get(:size, 32)
60 |> :crypto.strong_rand_bytes()
61 |> Base.url_encode64(padding: false)
64 # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
65 # decoding it. Investigate sometime.
66 def fix_padding(token) do
69 |> Base.url_decode64!(padding: false)
70 |> Base.url_encode64(padding: false)