Merge remote-tracking branch 'pleroma/develop' into feature/disable-account
[akkoma] / lib / pleroma / web / oauth / scopes.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.OAuth.Scopes do
6 @moduledoc """
7 Functions for dealing with scopes.
8 """
9
10 @doc """
11 Fetch scopes from requiest params.
12
13 Note: `scopes` is used by Mastodon — supporting it but sticking to
14 OAuth's standard `scope` wherever we control it
15 """
16 @spec fetch_scopes(map(), list()) :: list()
17 def fetch_scopes(params, default) do
18 parse_scopes(params["scope"] || params["scopes"], default)
19 end
20
21 def parse_scopes(scopes, _default) when is_list(scopes) do
22 Enum.filter(scopes, &(&1 not in [nil, ""]))
23 end
24
25 def parse_scopes(scopes, default) when is_binary(scopes) do
26 scopes
27 |> to_list
28 |> parse_scopes(default)
29 end
30
31 def parse_scopes(_, default) do
32 default
33 end
34
35 @doc """
36 Convert scopes string to list
37 """
38 @spec to_list(binary()) :: [binary()]
39 def to_list(nil), do: []
40
41 def to_list(str) do
42 str
43 |> String.trim()
44 |> String.split(~r/[\s,]+/)
45 end
46
47 @doc """
48 Convert scopes list to string
49 """
50 @spec to_string(list()) :: binary()
51 def to_string(scopes), do: Enum.join(scopes, " ")
52
53 @doc """
54 Validates scopes.
55 """
56 @spec validates(list() | nil, list()) ::
57 {:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
58 def validates([], _app_scopes), do: {:error, :missing_scopes}
59 def validates(nil, _app_scopes), do: {:error, :missing_scopes}
60
61 def validates(scopes, app_scopes) do
62 case scopes -- app_scopes do
63 [] -> {:ok, scopes}
64 _ -> {:error, :unsupported_scopes}
65 end
66 end
67 end