Merge branch 'chores/bump-copyright' into 'develop'
[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.Config
10 alias Pleroma.Helpers.AuthHelper
11
12 use Pleroma.Web, :plug
13
14 def init(%{scopes: _} = options), do: options
15
16 @impl true
17 def perform(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
18 op = options[:op] || :|
19 token = assigns[:token]
20
21 scopes = transform_scopes(scopes, options)
22 matched_scopes = (token && filter_descendants(scopes, token.scopes)) || []
23
24 cond do
25 token && op == :| && Enum.any?(matched_scopes) ->
26 conn
27
28 token && op == :& && matched_scopes == scopes ->
29 conn
30
31 options[:fallback] == :proceed_unauthenticated ->
32 AuthHelper.drop_auth_info(conn)
33
34 true ->
35 missing_scopes = scopes -- matched_scopes
36 permissions = Enum.join(missing_scopes, " #{op} ")
37
38 error_message =
39 dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
40
41 conn
42 |> put_resp_content_type("application/json")
43 |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
44 |> halt()
45 end
46 end
47
48 @doc "Keeps those of `scopes` which are descendants of `supported_scopes`"
49 def filter_descendants(scopes, supported_scopes) do
50 Enum.filter(
51 scopes,
52 fn scope ->
53 Enum.find(
54 supported_scopes,
55 &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
56 )
57 end
58 )
59 end
60
61 @doc "Transforms scopes by applying supported options (e.g. :admin)"
62 def transform_scopes(scopes, options) do
63 if options[:admin] do
64 Config.oauth_admin_scopes(scopes)
65 else
66 scopes
67 end
68 end
69 end