Remove vapidPublicKey from Nodeinfo
[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 alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
11
12 @behaviour Plug
13
14 def init(%{scopes: _} = options), do: options
15
16 def call(%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 |> maybe_perform_instance_privacy_check(options)
35
36 true ->
37 missing_scopes = scopes -- matched_scopes
38 permissions = Enum.join(missing_scopes, " #{op} ")
39
40 error_message =
41 dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
42
43 conn
44 |> put_resp_content_type("application/json")
45 |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
46 |> halt()
47 end
48 end
49
50 @doc "Filters descendants of supported scopes"
51 def filter_descendants(scopes, supported_scopes) do
52 Enum.filter(
53 scopes,
54 fn scope ->
55 Enum.find(
56 supported_scopes,
57 &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
58 )
59 end
60 )
61 end
62
63 @doc "Transforms scopes by applying supported options (e.g. :admin)"
64 def transform_scopes(scopes, options) do
65 if options[:admin] do
66 Config.oauth_admin_scopes(scopes)
67 else
68 scopes
69 end
70 end
71
72 defp maybe_perform_instance_privacy_check(%Plug.Conn{} = conn, options) do
73 if options[:skip_instance_privacy_check] do
74 conn
75 else
76 EnsurePublicOrAuthenticatedPlug.call(conn, [])
77 end
78 end
79 end