1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Plugs.OAuthScopesPlug do
7 import Pleroma.Web.Gettext
10 alias Pleroma.Plugs.EnsurePublicOrAuthenticatedPlug
11 alias Pleroma.Plugs.PlugHelper
13 use Pleroma.Web, :plug
17 def init(%{scopes: _} = options), do: options
19 def perform(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
20 op = options[:op] || :|
21 token = assigns[:token]
23 scopes = transform_scopes(scopes, options)
24 matched_scopes = (token && filter_descendants(scopes, token.scopes)) || []
27 token && op == :| && Enum.any?(matched_scopes) ->
30 token && op == :& && matched_scopes == scopes ->
33 options[:fallback] == :proceed_unauthenticated ->
36 |> assign(:token, nil)
37 |> maybe_perform_instance_privacy_check(options)
40 missing_scopes = scopes -- matched_scopes
41 permissions = Enum.join(missing_scopes, " #{op} ")
44 dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
47 |> put_resp_content_type("application/json")
48 |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
53 @doc "Filters descendants of supported scopes"
54 def filter_descendants(scopes, supported_scopes) do
60 &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
66 @doc "Transforms scopes by applying supported options (e.g. :admin)"
67 def transform_scopes(scopes, options) do
69 Config.oauth_admin_scopes(scopes)
75 defp maybe_perform_instance_privacy_check(%Plug.Conn{} = conn, options) do
76 if options[:skip_instance_privacy_check] do
79 EnsurePublicOrAuthenticatedPlug.call(conn, [])