logo

pleroma

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

scopes.ex (1889B)


  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.Scopes do
  5. @moduledoc """
  6. Functions for dealing with scopes.
  7. """
  8. alias Pleroma.Web.Plugs.OAuthScopesPlug
  9. @doc """
  10. Fetch scopes from request params.
  11. Note: `scopes` is used by Mastodon — supporting it but sticking to
  12. OAuth's standard `scope` wherever we control it
  13. """
  14. @spec fetch_scopes(map() | struct(), list()) :: list()
  15. def fetch_scopes(params, default) do
  16. parse_scopes(params["scope"] || params["scopes"] || params[:scopes], default)
  17. end
  18. def parse_scopes(scopes, _default) when is_list(scopes) do
  19. Enum.filter(scopes, &(&1 not in [nil, ""]))
  20. end
  21. def parse_scopes(scopes, default) when is_binary(scopes) do
  22. scopes
  23. |> to_list
  24. |> parse_scopes(default)
  25. end
  26. def parse_scopes(_, default) do
  27. default
  28. end
  29. @doc """
  30. Convert scopes string to list
  31. """
  32. @spec to_list(binary()) :: [binary()]
  33. def to_list(nil), do: []
  34. def to_list(str) do
  35. str
  36. |> String.trim()
  37. |> String.split(~r/[\s,]+/)
  38. end
  39. @doc """
  40. Convert scopes list to string
  41. """
  42. @spec to_string(list()) :: binary()
  43. def to_string(scopes), do: Enum.join(scopes, " ")
  44. @doc """
  45. Validates scopes.
  46. """
  47. @spec validate(list() | nil, list()) ::
  48. {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
  49. def validate(blank_scopes, _app_scopes) when blank_scopes in [nil, []],
  50. do: {:error, :missing_scopes}
  51. def validate(scopes, app_scopes) do
  52. case OAuthScopesPlug.filter_descendants(scopes, app_scopes) do
  53. ^scopes -> {:ok, scopes}
  54. _ -> {:error, :unsupported_scopes}
  55. end
  56. end
  57. def contains_admin_scopes?(scopes) do
  58. scopes
  59. |> OAuthScopesPlug.filter_descendants(["admin"])
  60. |> Enum.any?()
  61. end
  62. end