Merge branch 'develop' into issue/1411
[akkoma] / lib / pleroma / plugs / oauth_scopes_plug.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.Plugs.OAuthScopesPlug do
6 import Plug.Conn
7 import Pleroma.Web.Gettext
8
9 alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
10
11 @behaviour Plug
12
13 def init(%{scopes: _} = options), do: options
14
15 def call(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
16 op = options[:op] || :|
17 token = assigns[:token]
18 matched_scopes = token && filter_descendants(scopes, token.scopes)
19
20 cond do
21 is_nil(token) ->
22 maybe_perform_instance_privacy_check(conn, options)
23
24 op == :| && Enum.any?(matched_scopes) ->
25 conn
26
27 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 defp maybe_perform_instance_privacy_check(%Plug.Conn{} = conn, options) do
64 if options[:skip_instance_privacy_check] do
65 conn
66 else
67 EnsurePublicOrAuthenticatedPlug.call(conn, [])
68 end
69 end
70 end