Guardian.Plug.current_resource(conn) returns nil

682 Views Asked by At

I am updating Guardian from v0.14 to v1.0.

I am following update guide from official guardian github page and I faced one problem.

In order to update, I slightly changed my authentication logic.

From:

case Myapp.Session.authenticate(session_params) do
  {:ok, user} ->
    {:ok, jwt, _full_claims} = user |> Guardian.encode_and_sign(:token)

    conn
    |> put_status(:created)
    |> render("show.json", jwt: jwt, user: user)

  :error ->
    conn
    |> put_status(:unprocessable_entity)
    |> render("error.json")
end

To:

case Myapp.Session.authenticate(session_params) do
  {:ok, user} ->
    {:ok, jwt, _full_claims} = Core.Guardian.encode_and_sign(user)

    conn
    |> put_status(:created)
    |> render("show.json", jwt: jwt, user: user)

  :error ->
    conn
    |> put_status(:unprocessable_entity)
    |> render("error.json")
end

And I got nil from Guardian.Plug.current_resource(conn)... in order to resolve this problem, I store token in front-end localStorage and pass it to get user information.

But I still think that it is better practice to get user information from current_resource. How can I achieve this?

-- EDIT current_user_controller.ex

def show(conn, _) do
 user = Myapp.Guardian.Plug.current_resource(conn)

 conn
 |> put_status(:ok)
 |> render("show.json", user: user)
end
0

There are 0 best solutions below