2019-02-09 07:09:08 -07:00
|
|
|
# Pleroma: A lightweight social networking server
|
2021-01-12 23:49:20 -07:00
|
|
|
# Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
|
2019-02-09 07:09:08 -07:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
2020-06-24 00:57:27 -06:00
|
|
|
defmodule Pleroma.Web.Plugs.OAuthScopesPlug do
|
2019-02-09 07:09:08 -07:00
|
|
|
import Plug.Conn
|
2019-07-10 03:25:58 -06:00
|
|
|
import Pleroma.Web.Gettext
|
2019-02-09 07:09:08 -07:00
|
|
|
|
2020-12-06 03:59:10 -07:00
|
|
|
alias Pleroma.Helpers.AuthHelper
|
2019-09-15 09:22:08 -06:00
|
|
|
|
2020-04-15 12:19:16 -06:00
|
|
|
use Pleroma.Web, :plug
|
|
|
|
|
2019-02-15 09:54:37 -07:00
|
|
|
def init(%{scopes: _} = options), do: options
|
2019-02-09 07:09:08 -07:00
|
|
|
|
2020-04-21 07:29:19 -06:00
|
|
|
@impl true
|
2020-04-15 12:19:16 -06:00
|
|
|
def perform(%Plug.Conn{assigns: assigns} = conn, %{scopes: scopes} = options) do
|
2019-02-15 09:54:37 -07:00
|
|
|
op = options[:op] || :|
|
2019-02-09 07:09:08 -07:00
|
|
|
token = assigns[:token]
|
2019-12-06 10:33:47 -07:00
|
|
|
|
2019-12-15 12:32:42 -07:00
|
|
|
matched_scopes = (token && filter_descendants(scopes, token.scopes)) || []
|
2019-02-15 09:54:37 -07:00
|
|
|
|
|
|
|
cond do
|
2019-12-15 12:32:42 -07:00
|
|
|
token && op == :| && Enum.any?(matched_scopes) ->
|
2019-02-15 09:54:37 -07:00
|
|
|
conn
|
|
|
|
|
2019-12-15 12:32:42 -07:00
|
|
|
token && op == :& && matched_scopes == scopes ->
|
2019-02-15 09:54:37 -07:00
|
|
|
conn
|
|
|
|
|
|
|
|
options[:fallback] == :proceed_unauthenticated ->
|
2020-12-06 03:59:10 -07:00
|
|
|
AuthHelper.drop_auth_info(conn)
|
2019-02-15 09:54:37 -07:00
|
|
|
|
|
|
|
true ->
|
2019-09-08 06:00:03 -06:00
|
|
|
missing_scopes = scopes -- matched_scopes
|
2019-07-10 03:25:58 -06:00
|
|
|
permissions = Enum.join(missing_scopes, " #{op} ")
|
|
|
|
|
|
|
|
error_message =
|
2023-08-01 04:43:50 -06:00
|
|
|
dgettext("errors", "Insufficient permissions: %{permissions}.",
|
|
|
|
permissions: permissions
|
|
|
|
)
|
2019-02-15 09:54:37 -07:00
|
|
|
|
|
|
|
conn
|
|
|
|
|> put_resp_content_type("application/json")
|
2019-07-10 03:25:58 -06:00
|
|
|
|> send_resp(:forbidden, Jason.encode!(%{error: error_message}))
|
2019-02-15 09:54:37 -07:00
|
|
|
|> halt()
|
2019-02-09 07:09:08 -07:00
|
|
|
end
|
|
|
|
end
|
2019-09-08 06:00:03 -06:00
|
|
|
|
2020-09-19 10:16:55 -06:00
|
|
|
@doc "Keeps those of `scopes` which are descendants of `supported_scopes`"
|
2019-09-08 06:00:03 -06:00
|
|
|
def filter_descendants(scopes, supported_scopes) do
|
|
|
|
Enum.filter(
|
|
|
|
scopes,
|
|
|
|
fn scope ->
|
|
|
|
Enum.find(
|
|
|
|
supported_scopes,
|
|
|
|
&(scope == &1 || String.starts_with?(scope, &1 <> ":"))
|
|
|
|
)
|
|
|
|
end
|
|
|
|
)
|
|
|
|
end
|
2019-02-09 07:09:08 -07:00
|
|
|
end
|