Change user.discoverable field to user.is_discoverable
[akkoma] / lib / pleroma / web / plugs / o_auth_scopes_plug.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.Plugs.OAuthScopesPlug do
6 import Plug.Conn
7 import Pleroma.Web.Gettext
8
9 alias Pleroma.Config
10
11 use Pleroma.Web, :plug
12
13 def init(%{scopes: _} = options), do: options
14
15 @impl true
16 def perform(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
17 op = options[:op] || :|
18 token = assigns[:token]
19
20 scopes = transform_scopes(scopes, options)
21 matched_scopes = (token && filter_descendants(scopes, token.scopes)) || []
22
23 cond do
24 token && op == :| && Enum.any?(matched_scopes) ->
25 conn
26
27 token && op == :& && matched_scopes == scopes ->
28 conn
29
30 options[:fallback] == :proceed_unauthenticated ->
31 drop_auth_info(conn)
32
33 true ->
34 missing_scopes = scopes -- matched_scopes
35 permissions = Enum.join(missing_scopes, " #{op} ")
36
37 error_message =
38 dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
39
40 conn
41 |> put_resp_content_type("application/json")
42 |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
43 |> halt()
44 end
45 end
46
47 @doc "Drops authentication info from connection"
48 def drop_auth_info(conn) do
49 # To simplify debugging, setting a private variable on `conn` if auth info is dropped
50 conn
51 |> put_private(:authentication_ignored, true)
52 |> assign(:user, nil)
53 |> assign(:token, nil)
54 end
55
56 @doc "Keeps those of `scopes` which are descendants of `supported_scopes`"
57 def filter_descendants(scopes, supported_scopes) do
58 Enum.filter(
59 scopes,
60 fn scope ->
61 Enum.find(
62 supported_scopes,
63 &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
64 )
65 end
66 )
67 end
68
69 @doc "Transforms scopes by applying supported options (e.g. :admin)"
70 def transform_scopes(scopes, options) do
71 if options[:admin] do
72 Config.oauth_admin_scopes(scopes)
73 else
74 scopes
75 end
76 end
77 end