1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.OAuth.Scopes do
7 Functions for dealing with scopes.
10 alias Pleroma.Plugs.OAuthScopesPlug
14 Fetch scopes from request params.
16 Note: `scopes` is used by Mastodon — supporting it but sticking to
17 OAuth's standard `scope` wherever we control it
19 @spec fetch_scopes(map(), list()) :: list()
20 def fetch_scopes(params, default) do
21 parse_scopes(params["scope"] || params["scopes"], default)
24 def parse_scopes(scopes, _default) when is_list(scopes) do
25 Enum.filter(scopes, &(&1 not in [nil, ""]))
28 def parse_scopes(scopes, default) when is_binary(scopes) do
31 |> parse_scopes(default)
34 def parse_scopes(_, default) do
39 Convert scopes string to list
41 @spec to_list(binary()) :: [binary()]
42 def to_list(nil), do: []
47 |> String.split(~r/[\s,]+/)
51 Convert scopes list to string
53 @spec to_string(list()) :: binary()
54 def to_string(scopes), do: Enum.join(scopes, " ")
59 @spec validate(list() | nil, list(), User.t()) ::
60 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
61 def validate(blank_scopes, _app_scopes, _user) when blank_scopes in [nil, []],
62 do: {:error, :missing_scopes}
64 def validate(scopes, app_scopes, %User{} = user) do
65 with {:ok, _} <- ensure_scopes_support(scopes, app_scopes),
66 {:ok, scopes} <- authorize_admin_scopes(scopes, app_scopes, user) do
71 defp ensure_scopes_support(scopes, app_scopes) do
72 case OAuthScopesPlug.filter_descendants(scopes, app_scopes) do
73 ^scopes -> {:ok, scopes}
74 _ -> {:error, :unsupported_scopes}
78 defp authorize_admin_scopes(scopes, app_scopes, %User{} = user) do
79 if user.is_admin || !contains_admin_scopes?(scopes) || !contains_admin_scopes?(app_scopes) do
82 # Gracefully dropping admin scopes from requested scopes if user isn't an admin (not raising)
83 scopes = scopes -- OAuthScopesPlug.filter_descendants(scopes, ["admin"])
84 validate(scopes, app_scopes, user)
88 def contains_admin_scopes?(scopes) do
90 |> OAuthScopesPlug.filter_descendants(["admin"])