File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 11defmodule 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
1918end
You can’t perform that action at this time.
0 commit comments