logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma

oauth_scopes_plug.ex (2124B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Plugs.OAuthScopesPlug do
  5. import Plug.Conn
  6. import Pleroma.Web.Gettext
  7. alias Pleroma.Config
  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. scopes = transform_scopes(scopes, options)
  15. matched_scopes = (token && filter_descendants(scopes, token.scopes)) || []
  16. cond do
  17. token && op == :| && Enum.any?(matched_scopes) ->
  18. conn
  19. token && op == :& && matched_scopes == scopes ->
  20. conn
  21. options[:fallback] == :proceed_unauthenticated ->
  22. drop_auth_info(conn)
  23. true ->
  24. missing_scopes = scopes -- matched_scopes
  25. permissions = Enum.join(missing_scopes, " #{op} ")
  26. error_message =
  27. dgettext("errors", "Insufficient permissions: %{permissions}.", permissions: permissions)
  28. conn
  29. |> put_resp_content_type("application/json")
  30. |> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
  31. |> halt()
  32. end
  33. end
  34. @doc "Drops authentication info from connection"
  35. def drop_auth_info(conn) do
  36. # To simplify debugging, setting a private variable on `conn` if auth info is dropped
  37. conn
  38. |> put_private(:authentication_ignored, true)
  39. |> assign(:user, nil)
  40. |> assign(:token, nil)
  41. end
  42. @doc "Keeps those of `scopes` which are descendants of `supported_scopes`"
  43. def filter_descendants(scopes, supported_scopes) do
  44. Enum.filter(
  45. scopes,
  46. fn scope ->
  47. Enum.find(
  48. supported_scopes,
  49. &(scope == &1 || String.starts_with?(scope, &1 <> ":"))
  50. )
  51. end
  52. )
  53. end
  54. @doc "Transforms scopes by applying supported options (e.g. :admin)"
  55. def transform_scopes(scopes, options) do
  56. if options[:admin] do
  57. Config.oauth_admin_scopes(scopes)
  58. else
  59. scopes
  60. end
  61. end
  62. end