in dev, allow dev FE
[akkoma] / lib / pleroma / web / plugs / o_auth_scopes_plug.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.Web.Plugs.OAuthScopesPlug do
6 import Plug.Conn
7 import Pleroma.Web.Gettext
8
9 alias Pleroma.Helpers.AuthHelper
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 matched_scopes = (token && filter_descendants(scopes, token.scopes)) || []
21
22 cond do
23 token && op == :| && Enum.any?(matched_scopes) ->
24 conn
25
26 token && op == :& && matched_scopes == scopes ->
27 conn
28
29 options[:fallback] == :proceed_unauthenticated ->
30 AuthHelper.drop_auth_info(conn)
31
32 true ->
33 missing_scopes = scopes -- matched_scopes
34 permissions = Enum.join(missing_scopes, " #{op} ")
35
36 error_message =
37 dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
38
39 conn
40 |> put_resp_content_type("application/json")
41 |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
42 |> halt()
43 end
44 end
45
46 @doc "Keeps those of `scopes` which are descendants of `supported_scopes`"
47 def filter_descendants(scopes, supported_scopes) do
48 Enum.filter(
49 scopes,
50 fn scope ->
51 Enum.find(
52 supported_scopes,
53 &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
54 )
55 end
56 )
57 end
58 end