41403047efec8369fc8fbd011b1ac4b2b53c2922
[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 @behaviour Plug
10
11 def init(%{scopes: _} = options), do: options
12
13 def call(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
14 op = options[:op] || :|
15 token = assigns[:token]
16 matched_scopes = token && filter_descendants(scopes, token.scopes)
17
18 cond do
19 is_nil(token) ->
20 conn
21
22 op == :| && Enum.any?(matched_scopes) ->
23 conn
24
25 op == :& && matched_scopes == scopes ->
26 conn
27
28 options[:fallback] == :proceed_unauthenticated ->
29 conn
30 |> assign(:user, nil)
31 |> assign(:token, nil)
32
33 true ->
34 missing_scopes = scopes -- matched_scopes
35 permissions = Enum.join(missing_scopes, " #{op} ")
36
37 error_message =
38 dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
39
40 conn
41 |> put_resp_content_type("application/json")
42 |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
43 |> halt()
44 end
45 end
46
47 @doc "Filters descendants of supported scopes"
48 def filter_descendants(scopes, supported_scopes) do
49 Enum.filter(
50 scopes,
51 fn scope ->
52 Enum.find(
53 supported_scopes,
54 &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
55 )
56 end
57 )
58 end
59 end