logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://hacktivis.me/git/pleroma.git

utils.ex (2038B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Web.OAuth.Token.Utils do
  5. @moduledoc """
  6. Auxiliary functions for dealing with tokens.
  7. """
  8. alias Pleroma.Repo
  9. alias Pleroma.Web.OAuth.App
  10. @doc "Fetch app by client credentials from request"
  11. @spec fetch_app(Plug.Conn.t()) :: {:ok, App.t()} | {:error, :not_found}
  12. def fetch_app(conn) do
  13. res =
  14. conn
  15. |> fetch_client_credentials()
  16. |> fetch_client
  17. case res do
  18. %App{} = app -> {:ok, app}
  19. _ -> {:error, :not_found}
  20. end
  21. end
  22. defp fetch_client({id, secret}) when is_binary(id) and is_binary(secret) do
  23. Repo.get_by(App, client_id: id, client_secret: secret)
  24. end
  25. defp fetch_client({_id, _secret}), do: nil
  26. defp fetch_client_credentials(conn) do
  27. # Per RFC 6749, HTTP Basic is preferred to body params
  28. with ["Basic " <> encoded] <- Plug.Conn.get_req_header(conn, "authorization"),
  29. {:ok, decoded} <- Base.decode64(encoded),
  30. [id, secret] <-
  31. Enum.map(
  32. String.split(decoded, ":"),
  33. fn s -> URI.decode_www_form(s) end
  34. ) do
  35. {id, secret}
  36. else
  37. _ -> {conn.params["client_id"], conn.params["client_secret"]}
  38. end
  39. end
  40. @doc "convert token inserted_at to unix timestamp"
  41. def format_created_at(%{inserted_at: inserted_at} = _token) do
  42. inserted_at
  43. |> DateTime.from_naive!("Etc/UTC")
  44. |> DateTime.to_unix()
  45. end
  46. @doc false
  47. @spec generate_token(keyword()) :: binary()
  48. def generate_token(opts \\ []) do
  49. opts
  50. |> Keyword.get(:size, 32)
  51. |> :crypto.strong_rand_bytes()
  52. |> Base.url_encode64(padding: false)
  53. end
  54. # XXX - for whatever reason our token arrives urlencoded, but Plug.Conn should be
  55. # decoding it. Investigate sometime.
  56. def fix_padding(token) do
  57. token
  58. |> URI.decode()
  59. |> Base.url_decode64!(padding: false)
  60. |> Base.url_encode64(padding: false)
  61. end
  62. end