Automatic checks of authentication / instance publicity. Definition of missing OAuth...
[akkoma] / lib / pleroma / plugs / oauth_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.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 conn
32 |> assign(:user, nil)
33 |> assign(:token, nil)
34
35 true ->
36 missing_scopes = scopes -- matched_scopes
37 permissions = Enum.join(missing_scopes, " #{op} ")
38
39 error_message =
40 dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
41
42 conn
43 |> put_resp_content_type("application/json")
44 |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
45 |> halt()
46 end
47 end
48
49 @doc "Filters descendants of supported scopes"
50 def filter_descendants(scopes, supported_scopes) do
51 Enum.filter(
52 scopes,
53 fn scope ->
54 Enum.find(
55 supported_scopes,
56 &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
57 )
58 end
59 )
60 end
61
62 @doc "Transforms scopes by applying supported options (e.g. :admin)"
63 def transform_scopes(scopes, options) do
64 if options[:admin] do
65 Config.oauth_admin_scopes(scopes)
66 else
67 scopes
68 end
69 end
70 end