2019-05-08 12:52:13 +02:00
|
|
|
# Pleroma: A lightweight social networking server
|
2020-03-02 06:08:45 +01:00
|
|
|
# Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
|
2019-05-08 12:52:13 +02:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
|
|
|
defmodule Pleroma.Web.OAuth.Scopes do
|
|
|
|
@moduledoc """
|
|
|
|
Functions for dealing with scopes.
|
|
|
|
"""
|
|
|
|
|
2020-06-24 08:57:27 +02:00
|
|
|
alias Pleroma.Web.Plugs.OAuthScopesPlug
|
2019-11-29 16:57:19 +01:00
|
|
|
|
2019-05-08 12:52:13 +02:00
|
|
|
@doc """
|
2019-09-08 14:00:03 +02:00
|
|
|
Fetch scopes from request params.
|
2019-05-08 12:52:13 +02:00
|
|
|
|
|
|
|
Note: `scopes` is used by Mastodon — supporting it but sticking to
|
|
|
|
OAuth's standard `scope` wherever we control it
|
|
|
|
"""
|
2020-04-01 21:00:59 +02:00
|
|
|
@spec fetch_scopes(map() | struct(), list()) :: list()
|
|
|
|
|
2019-05-08 12:52:13 +02:00
|
|
|
def fetch_scopes(params, default) do
|
2020-04-24 12:46:59 +02:00
|
|
|
parse_scopes(params["scope"] || params["scopes"] || params[:scopes], default)
|
2019-05-08 12:52:13 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def parse_scopes(scopes, _default) when is_list(scopes) do
|
|
|
|
Enum.filter(scopes, &(&1 not in [nil, ""]))
|
|
|
|
end
|
|
|
|
|
|
|
|
def parse_scopes(scopes, default) when is_binary(scopes) do
|
|
|
|
scopes
|
|
|
|
|> to_list
|
|
|
|
|> parse_scopes(default)
|
|
|
|
end
|
|
|
|
|
|
|
|
def parse_scopes(_, default) do
|
|
|
|
default
|
|
|
|
end
|
|
|
|
|
|
|
|
@doc """
|
|
|
|
Convert scopes string to list
|
|
|
|
"""
|
|
|
|
@spec to_list(binary()) :: [binary()]
|
|
|
|
def to_list(nil), do: []
|
|
|
|
|
|
|
|
def to_list(str) do
|
|
|
|
str
|
|
|
|
|> String.trim()
|
|
|
|
|> String.split(~r/[\s,]+/)
|
|
|
|
end
|
|
|
|
|
|
|
|
@doc """
|
|
|
|
Convert scopes list to string
|
|
|
|
"""
|
|
|
|
@spec to_string(list()) :: binary()
|
|
|
|
def to_string(scopes), do: Enum.join(scopes, " ")
|
|
|
|
|
|
|
|
@doc """
|
|
|
|
Validates scopes.
|
|
|
|
"""
|
2020-01-10 08:52:21 +01:00
|
|
|
@spec validate(list() | nil, list()) ::
|
2019-05-08 12:52:13 +02:00
|
|
|
{:ok, list()} | {:error, :missing_scopes | :unsupported_scopes}
|
2020-01-10 08:52:21 +01:00
|
|
|
def validate(blank_scopes, _app_scopes) when blank_scopes in [nil, []],
|
2019-11-29 16:57:19 +01:00
|
|
|
do: {:error, :missing_scopes}
|
2019-05-08 12:52:13 +02:00
|
|
|
|
2020-01-10 08:52:21 +01:00
|
|
|
def validate(scopes, app_scopes) do
|
2019-11-29 16:57:19 +01:00
|
|
|
case OAuthScopesPlug.filter_descendants(scopes, app_scopes) do
|
2019-09-08 14:00:03 +02:00
|
|
|
^scopes -> {:ok, scopes}
|
2019-05-08 12:52:13 +02:00
|
|
|
_ -> {:error, :unsupported_scopes}
|
|
|
|
end
|
|
|
|
end
|
2019-11-29 16:57:19 +01:00
|
|
|
|
2019-12-05 22:25:44 +01:00
|
|
|
def contains_admin_scopes?(scopes) do
|
2019-11-29 16:57:19 +01:00
|
|
|
scopes
|
|
|
|
|> OAuthScopesPlug.filter_descendants(["admin"])
|
|
|
|
|> Enum.any?()
|
|
|
|
end
|
2019-05-08 12:52:13 +02:00
|
|
|
end
|