logo

pleroma

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

o_auth_scopes_plug.ex (1597B)


  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}.", permissions: permissions)
  27. conn
  28. |> put_resp_content_type("application/json")
  29. |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
  30. |> halt()
  31. end
  32. end
  33. @doc "Keeps those of `scopes` which are descendants of `supported_scopes`"
  34. def filter_descendants(scopes, supported_scopes) do
  35. Enum.filter(
  36. scopes,
  37. fn scope ->
  38. Enum.find(
  39. supported_scopes,
  40. &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
  41. )
  42. end
  43. )
  44. end
  45. end