From 9bc1e79c5675efb70e45b63f6530194888b182de Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 12 Jul 2021 21:57:52 -0500 Subject: [PATCH] Moderators: add UserIsStaffPlug --- lib/pleroma/web/plugs/user_is_staff_plug.ex | 23 +++++++++ .../web/plugs/user_is_staff_plug_test.exs | 47 +++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 lib/pleroma/web/plugs/user_is_staff_plug.ex create mode 100644 test/pleroma/web/plugs/user_is_staff_plug_test.exs diff --git a/lib/pleroma/web/plugs/user_is_staff_plug.ex b/lib/pleroma/web/plugs/user_is_staff_plug.ex new file mode 100644 index 000000000..49c2d9cca --- /dev/null +++ b/lib/pleroma/web/plugs/user_is_staff_plug.ex @@ -0,0 +1,23 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.Plugs.UserIsStaffPlug do + import Pleroma.Web.TranslationHelpers + import Plug.Conn + + alias Pleroma.User + + def init(options) do + options + end + + def call(%{assigns: %{user: %User{is_admin: true}}} = conn, _), do: conn + def call(%{assigns: %{user: %User{is_moderator: true}}} = conn, _), do: conn + + def call(conn, _) do + conn + |> render_error(:forbidden, "User is not a staff member.") + |> halt() + end +end diff --git a/test/pleroma/web/plugs/user_is_staff_plug_test.exs b/test/pleroma/web/plugs/user_is_staff_plug_test.exs new file mode 100644 index 000000000..a0c4061db --- /dev/null +++ b/test/pleroma/web/plugs/user_is_staff_plug_test.exs @@ -0,0 +1,47 @@ +# Pleroma: A lightweight social networking server +# Copyright © 2017-2021 Pleroma Authors +# SPDX-License-Identifier: AGPL-3.0-only + +defmodule Pleroma.Web.Plugs.UserIsStaffPlugTest do + use Pleroma.Web.ConnCase, async: true + + alias Pleroma.Web.Plugs.UserIsStaffPlug + import Pleroma.Factory + + test "accepts a user that is an admin" do + user = insert(:user, is_admin: true) + + conn = assign(build_conn(), :user, user) + + ret_conn = UserIsStaffPlug.call(conn, %{}) + + assert conn == ret_conn + end + + test "accepts a user that is a moderator" do + user = insert(:user, is_moderator: true) + + conn = assign(build_conn(), :user, user) + + ret_conn = UserIsStaffPlug.call(conn, %{}) + + assert conn == ret_conn + end + + test "denies a user that isn't a staff member" do + user = insert(:user) + + conn = + build_conn() + |> assign(:user, user) + |> UserIsStaffPlug.call(%{}) + + assert conn.status == 403 + end + + test "denies when a user isn't set" do + conn = UserIsStaffPlug.call(build_conn(), %{}) + + assert conn.status == 403 + end +end