From b829226cbfc4ded9bafed2bae57ad1de840ff798 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 19 Jul 2020 15:48:26 -0500 Subject: [PATCH] Assign :user whenever :user_id is in session, pass to OAuth form --- lib/pleroma/plugs/ensure_user_key_plug.ex | 10 ++++++++-- lib/pleroma/web/router.ex | 2 +- test/plugs/ensure_user_key_plug_test.exs | 28 +++++++++++++++++++++++++++- 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/lib/pleroma/plugs/ensure_user_key_plug.ex b/lib/pleroma/plugs/ensure_user_key_plug.ex index 9795cdbde..470fe0d95 100644 --- a/lib/pleroma/plugs/ensure_user_key_plug.ex +++ b/lib/pleroma/plugs/ensure_user_key_plug.ex @@ -3,6 +3,7 @@ # SPDX-License-Identifier: AGPL-3.0-only defmodule Pleroma.Plugs.EnsureUserKeyPlug do + alias Pleroma.User import Plug.Conn def init(opts) do @@ -12,7 +13,12 @@ defmodule Pleroma.Plugs.EnsureUserKeyPlug do def call(%{assigns: %{user: _}} = conn, _), do: conn def call(conn, _) do - conn - |> assign(:user, nil) + with user_id <- get_session(conn, :user_id), + true <- is_binary(user_id), + %User{} = user <- User.get_by_id(user_id) do + assign(conn, :user, user) + else + _ -> assign(conn, :user, nil) + end end end diff --git a/lib/pleroma/web/router.ex b/lib/pleroma/web/router.ex index 386308362..05841a8c4 100644 --- a/lib/pleroma/web/router.ex +++ b/lib/pleroma/web/router.ex @@ -276,7 +276,7 @@ defmodule Pleroma.Web.Router do scope "/oauth", Pleroma.Web.OAuth do scope [] do - pipe_through(:oauth) + pipe_through([:oauth, :after_auth]) get("/authorize", OAuthController, :authorize) end diff --git a/test/plugs/ensure_user_key_plug_test.exs b/test/plugs/ensure_user_key_plug_test.exs index 633c05447..9cd3a80f8 100644 --- a/test/plugs/ensure_user_key_plug_test.exs +++ b/test/plugs/ensure_user_key_plug_test.exs @@ -4,8 +4,23 @@ defmodule Pleroma.Plugs.EnsureUserKeyPlugTest do use Pleroma.Web.ConnCase, async: true - alias Pleroma.Plugs.EnsureUserKeyPlug + import Pleroma.Factory + + @session_opts [ + store: :cookie, + key: "_test", + signing_salt: "cooldude" + ] + + setup %{conn: conn} do + conn = + conn + |> Plug.Session.call(Plug.Session.init(@session_opts)) + |> fetch_session() + + %{conn: conn} + end test "if the conn has a user key set, it does nothing", %{conn: conn} do conn = @@ -19,6 +34,17 @@ defmodule Pleroma.Plugs.EnsureUserKeyPlugTest do assert conn == ret_conn end + test "if the session has a user_id, it sets the user", %{conn: conn} do + user = insert(:user) + + conn = + conn + |> put_session(:user_id, user.id) + |> EnsureUserKeyPlug.call(%{}) + + assert conn.assigns[:user] == user + end + test "if the conn has no key set, it sets it to nil", %{conn: conn} do conn = conn