Merge branch 'fix/minor-doc-fix' into 'develop'
[akkoma] / lib / pleroma / config.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Config do
6 @behaviour Pleroma.Config.Getting
7 defmodule Error do
8 defexception [:message]
9 end
10
11 @impl true
12 def get(key), do: get(key, nil)
13
14 @impl true
15 def get([key], default), do: get(key, default)
16
17 @impl true
18 def get([_ | _] = path, default) do
19 case fetch(path) do
20 {:ok, value} -> value
21 :error -> default
22 end
23 end
24
25 @impl true
26 def get(key, default) do
27 Application.get_env(:pleroma, key, default)
28 end
29
30 def get!(key) do
31 value = get(key, nil)
32
33 if value == nil do
34 raise(Error, message: "Missing configuration value: #{inspect(key)}")
35 else
36 value
37 end
38 end
39
40 def fetch(key) when is_atom(key), do: fetch([key])
41
42 def fetch([root_key | keys]) do
43 Enum.reduce_while(keys, Application.fetch_env(:pleroma, root_key), fn
44 key, {:ok, config} when is_map(config) or is_list(config) ->
45 case Access.fetch(config, key) do
46 :error ->
47 {:halt, :error}
48
49 value ->
50 {:cont, value}
51 end
52
53 _key, _config ->
54 {:halt, :error}
55 end)
56 end
57
58 def put([key], value), do: put(key, value)
59
60 def put([parent_key | keys], value) do
61 parent =
62 Application.get_env(:pleroma, parent_key, [])
63 |> put_in(keys, value)
64
65 Application.put_env(:pleroma, parent_key, parent)
66 end
67
68 def put(key, value) do
69 Application.put_env(:pleroma, key, value)
70 end
71
72 def delete([key]), do: delete(key)
73
74 def delete([parent_key | keys] = path) do
75 with {:ok, _} <- fetch(path) do
76 {_, parent} =
77 parent_key
78 |> get()
79 |> get_and_update_in(keys, fn _ -> :pop end)
80
81 Application.put_env(:pleroma, parent_key, parent)
82 end
83 end
84
85 def delete(key) do
86 Application.delete_env(:pleroma, key)
87 end
88
89 def restrict_unauthenticated_access?(resource, kind) do
90 setting = get([:restrict_unauthenticated, resource, kind])
91
92 if setting in [nil, :if_instance_is_private] do
93 !get!([:instance, :public])
94 else
95 setting
96 end
97 end
98
99 def oauth_consumer_strategies, do: get([:auth, :oauth_consumer_strategies], [])
100
101 def oauth_consumer_enabled?, do: oauth_consumer_strategies() != []
102
103 def enforce_oauth_admin_scope_usage?, do: !!get([:auth, :enforce_oauth_admin_scope_usage])
104
105 def oauth_admin_scopes(scopes) when is_list(scopes) do
106 Enum.flat_map(
107 scopes,
108 fn scope ->
109 ["admin:#{scope}"] ++
110 if enforce_oauth_admin_scope_usage?(), do: [], else: [scope]
111 end
112 )
113 end
114 end