1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.Web.Plugs.OAuthScopesPlug do
7 import Pleroma.Web.Gettext
9 alias Pleroma.Helpers.AuthHelper
11 use Pleroma.Web, :plug
13 def init(%{scopes: _} = options), do: options
16 def perform(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
17 op = options[:op] || :|
18 token = assigns[:token]
20 matched_scopes = (token && filter_descendants(scopes, token.scopes)) || []
23 token && op == :| && Enum.any?(matched_scopes) ->
26 token && op == :& && matched_scopes == scopes ->
29 options[:fallback] == :proceed_unauthenticated ->
30 AuthHelper.drop_auth_info(conn)
33 missing_scopes = scopes -- matched_scopes
34 permissions = Enum.join(missing_scopes, " #{op} ")
37 dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
40 |> put_resp_content_type("application/json")
41 |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
46 @doc "Keeps those of `scopes` which are descendants of `supported_scopes`"
47 def filter_descendants(scopes, supported_scopes) do
53 &(scope == &1 || String.starts_with?(scope, &1 <> ":"))