diff --git a/lib/pleroma/user.ex b/lib/pleroma/user.ex index 747a83e8d..b93ce9c2c 100644 --- a/lib/pleroma/user.ex +++ b/lib/pleroma/user.ex @@ -353,6 +353,24 @@ defp visible_account_status(user) do end end + @spec privileged?(User.t(), atom()) :: boolean() + def privileged?(%User{is_admin: false, is_moderator: false}, _), do: false + + def privileged?( + %User{local: true, is_admin: is_admin, is_moderator: is_moderator}, + privilege_tag + ), + do: + privileged_for?(privilege_tag, is_admin, :admin_privileges) or + privileged_for?(privilege_tag, is_moderator, :moderator_privileges) + + def privileged?(_, _), do: false + + defp privileged_for?(privilege_tag, true, config_role_key), + do: privilege_tag in Config.get([:instance, config_role_key]) + + defp privileged_for?(_, _, _), do: false + @spec superuser?(User.t()) :: boolean() def superuser?(%User{local: true, is_admin: true}), do: true def superuser?(%User{local: true, is_moderator: true}), do: true diff --git a/test/pleroma/user_test.exs b/test/pleroma/user_test.exs index ea1e45e63..192bffaa9 100644 --- a/test/pleroma/user_test.exs +++ b/test/pleroma/user_test.exs @@ -13,7 +13,7 @@ defmodule Pleroma.UserTest do alias Pleroma.Web.ActivityPub.ActivityPub alias Pleroma.Web.CommonAPI - use Pleroma.DataCase + use Pleroma.DataCase, async: false use Oban.Testing, repo: Pleroma.Repo import Pleroma.Factory @@ -1878,6 +1878,47 @@ test "returns :approval_pending for unapproved user" do end end + describe "privileged?/1" do + setup do + clear_config([:instance, :admin_privileges], [:cofe, :suya]) + clear_config([:instance, :moderator_privileges], [:cofe, :suya]) + end + + test "returns false for unprivileged users" do + user = insert(:user, local: true) + + refute User.privileged?(user, :cofe) + end + + test "returns false for remote users" do + user = insert(:user, local: false) + remote_admin_user = insert(:user, local: false, is_admin: true) + + refute User.privileged?(user, :cofe) + refute User.privileged?(remote_admin_user, :cofe) + end + + test "returns true for local moderators if, and only if, they are privileged" do + user = insert(:user, local: true, is_moderator: true) + + assert User.privileged?(user, :cofe) + + clear_config([:instance, :moderator_privileges], []) + + refute User.privileged?(user, :cofe) + end + + test "returns true for local admins if, and only if, they are privileged" do + user = insert(:user, local: true, is_admin: true) + + assert User.privileged?(user, :cofe) + + clear_config([:instance, :admin_privileges], []) + + refute User.privileged?(user, :cofe) + end + end + describe "superuser?/1" do test "returns false for unprivileged users" do user = insert(:user, local: true)