From 3cf17dc402ceab7f823edc263ad09af7013d0646 Mon Sep 17 00:00:00 2001 From: lain Date: Wed, 5 Sep 2018 17:59:19 +0200 Subject: [PATCH] Add EnsureAuthenticatedPlug --- .../plugs/ensure_authenticated_plug.ex | 19 +++++++++++++ test/plugs/ensure_authenticated_plug_test.exs | 27 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 lib/pleroma/plugs/ensure_authenticated_plug.ex create mode 100644 test/plugs/ensure_authenticated_plug_test.exs diff --git a/lib/pleroma/plugs/ensure_authenticated_plug.ex b/lib/pleroma/plugs/ensure_authenticated_plug.ex new file mode 100644 index 000000000..bca44eb2c --- /dev/null +++ b/lib/pleroma/plugs/ensure_authenticated_plug.ex @@ -0,0 +1,19 @@ +defmodule Pleroma.Plugs.EnsureAuthenticatedPlug do + import Plug.Conn + alias Pleroma.User + + def init(options) do + options + end + + def call(%{assigns: %{user: %User{}}} = conn, _) do + conn + end + + def call(conn, _) do + conn + |> put_resp_content_type("application/json") + |> send_resp(403, Jason.encode!(%{error: "Invalid credentials."})) + |> halt + end +end diff --git a/test/plugs/ensure_authenticated_plug_test.exs b/test/plugs/ensure_authenticated_plug_test.exs new file mode 100644 index 000000000..b32817fef --- /dev/null +++ b/test/plugs/ensure_authenticated_plug_test.exs @@ -0,0 +1,27 @@ +defmodule Pleroma.Plugs.EnsureAuthenticatedPlugTest do + use Pleroma.Web.ConnCase, async: true + + alias Pleroma.Plugs.EnsureAuthenticatedPlug + alias Pleroma.User + + test "it halts if no user is assigned", %{conn: conn} do + conn = + conn + |> EnsureAuthenticatedPlug.call(%{}) + + assert conn.status == 403 + assert conn.halted == true + end + + test "it continues if a user is assigned", %{conn: conn} do + conn = + conn + |> assign(:user, %User{}) + + ret_conn = + conn + |> EnsureAuthenticatedPlug.call(%{}) + + assert ret_conn == conn + end +end -- 2.45.2