logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://anongit.hacktivis.me/git/pleroma.git/

o_auth_scopes_plug.ex (1620B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Web.Plugs.OAuthScopesPlug do
  5. import Plug.Conn
  6. import Pleroma.Web.Gettext
  7. alias Pleroma.Helpers.AuthHelper
  8. use Pleroma.Web, :plug
  9. def init(%{scopes: _} = options), do: options
  10. @impl true
  11. def perform(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
  12. op = options[:op] || :|
  13. token = assigns[:token]
  14. matched_scopes = (token && filter_descendants(scopes, token.scopes)) || []
  15. cond do
  16. token && op == :| && Enum.any?(matched_scopes) ->
  17. conn
  18. token && op == :& && matched_scopes == scopes ->
  19. conn
  20. options[:fallback] == :proceed_unauthenticated ->
  21. AuthHelper.drop_auth_info(conn)
  22. true ->
  23. missing_scopes = scopes -- matched_scopes
  24. permissions = Enum.join(missing_scopes, " #{op} ")
  25. error_message =
  26. dgettext("errors", "Insufficient permissions: %{permissions}.",
  27. permissions: permissions
  28. )
  29. conn
  30. |> put_resp_content_type("application/json")
  31. |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
  32. |> halt()
  33. end
  34. end
  35. @doc "Keeps those of `scopes` which are descendants of `supported_scopes`"
  36. def filter_descendants(scopes, supported_scopes) do
  37. Enum.filter(
  38. scopes,
  39. fn scope ->
  40. Enum.find(
  41. supported_scopes,
  42. &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
  43. )
  44. end
  45. )
  46. end
  47. end