Skip to content

Commit 71676d8

Browse files
authored
Merge pull request #703 from banzay/fix-user-fetched-twice
User being fetched twice during authentication sequence
2 parents 7badcf4 + 0feca49 commit 71676d8

2 files changed

Lines changed: 28 additions & 9 deletions

File tree

test/plugs/current_user_test.exs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
defmodule CodeCorps.Plug.CurrentUserTest do
2+
3+
use CodeCorps.ConnCase
4+
5+
test "sets conn.assigns[:current_user] if user is authenticated" do
6+
user = build(:user, first_name: "John");
7+
conn = Guardian.Plug.set_current_resource(
8+
build_conn(),
9+
user
10+
)
11+
result_conn = CodeCorps.Plug.CurrentUser.call(conn, [])
12+
assert result_conn.assigns[:current_user] == user
13+
end
14+
15+
test "simply returns conn if user is not authenticated" do
16+
conn = build_conn()
17+
result_conn = CodeCorps.Plug.CurrentUser.call(conn, [])
18+
assert result_conn == conn
19+
end
20+
end

web/plugs/current_user.ex

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,18 @@
11
defmodule CodeCorps.Plug.CurrentUser do
2-
alias CodeCorps.GuardianSerializer
2+
@moduledoc """
3+
Puts authenticated Guardian user into conn.assigns[:current_user]
4+
"""
35

6+
@spec init(Keyword.t) :: Keyword.t
47
def init(opts), do: opts
58

9+
@spec call(Plug.Conn.t, Keyword.t) :: Plug.Conn.t
610
def call(conn, _opts) do
7-
case Guardian.Plug.current_token(conn) do
11+
case Guardian.Plug.current_resource(conn) do
12+
user = %CodeCorps.User{} ->
13+
Plug.Conn.assign(conn, :current_user, user)
814
nil ->
915
conn
10-
current_token ->
11-
with {:ok, claims} <- Guardian.decode_and_verify(current_token),
12-
{:ok, user} <- GuardianSerializer.from_token(claims["sub"]) do
13-
Plug.Conn.assign(conn, :current_user, user)
14-
else
15-
{:error, _reason} -> conn
16-
end
1716
end
1817
end
1918
end

0 commit comments

Comments
 (0)