Add SetUserSessionIdPlug.
authorlain <lain@soykaf.club>
Wed, 5 Sep 2018 19:42:42 +0000 (21:42 +0200)
committerlain <lain@soykaf.club>
Wed, 5 Sep 2018 19:42:42 +0000 (21:42 +0200)
lib/pleroma/plugs/set_user_session_id_plug.ex [new file with mode: 0644]
test/plugs/set_user_session_id_plug_test.exs [new file with mode: 0644]

diff --git a/lib/pleroma/plugs/set_user_session_id_plug.ex b/lib/pleroma/plugs/set_user_session_id_plug.ex
new file mode 100644 (file)
index 0000000..adc0a42
--- /dev/null
@@ -0,0 +1,15 @@
+defmodule Pleroma.Plugs.SetUserSessionIdPlug do
+  import Plug.Conn
+  alias Pleroma.User
+
+  def init(opts) do
+    opts
+  end
+
+  def call(%{assigns: %{user: %User{id: id}}} = conn, _) do
+    conn
+    |> put_session(:user_id, id)
+  end
+
+  def call(conn, _), do: conn
+end
diff --git a/test/plugs/set_user_session_id_plug_test.exs b/test/plugs/set_user_session_id_plug_test.exs
new file mode 100644 (file)
index 0000000..5edc0da
--- /dev/null
@@ -0,0 +1,39 @@
+defmodule Pleroma.Plugs.SetUserSessionIdPlugTest do
+  use Pleroma.Web.ConnCase, async: true
+
+  alias Pleroma.Plugs.SetUserSessionIdPlug
+  alias Pleroma.User
+
+  setup %{conn: conn} do
+    session_opts = [
+      store: :cookie,
+      key: "_test",
+      signing_salt: "cooldude"
+    ]
+
+    conn =
+      conn
+      |> Plug.Session.call(Plug.Session.init(session_opts))
+      |> fetch_session
+
+    %{conn: conn}
+  end
+
+  test "doesn't do anything if the user isn't set", %{conn: conn} do
+    ret_conn =
+      conn
+      |> SetUserSessionIdPlug.call(%{})
+
+    assert ret_conn == conn
+  end
+
+  test "sets the user_id in the session to the user id of the user assign", %{conn: conn} do
+    conn =
+      conn
+      |> assign(:user, %User{id: 1})
+      |> SetUserSessionIdPlug.call(%{})
+
+    id = get_session(conn, :user_id)
+    assert id == 1
+  end
+end