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.Web.Plugs.OAuthScopesPlug do
7 import Pleroma.Web.Gettext
10 alias Pleroma.Helpers.AuthHelper
12 use Pleroma.Web, :plug
14 def init(%{scopes: _} = options), do: options
17 def perform(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
18 op = options[:op] || :|
19 token = assigns[:token]
21 scopes = transform_scopes(scopes, options)
22 matched_scopes = (token && filter_descendants(scopes, token.scopes)) || []
25 token && op == :| && Enum.any?(matched_scopes) ->
28 token && op == :& && matched_scopes == scopes ->
31 options[:fallback] == :proceed_unauthenticated ->
32 AuthHelper.drop_auth_info(conn)
35 missing_scopes = scopes -- matched_scopes
36 permissions = Enum.join(missing_scopes, " #{op} ")
39 dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
42 |> put_resp_content_type("application/json")
43 |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
48 @doc "Keeps those of `scopes` which are descendants of `supported_scopes`"
49 def filter_descendants(scopes, supported_scopes) do
55 &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
61 @doc "Transforms scopes by applying supported options (e.g. :admin)"
62 def transform_scopes(scopes, options) do
64 Config.oauth_admin_scopes(scopes)