I’m trying to create a controller function that returns a view of the currently logged in user. I use guardian for authentication, and save during log-in the user’s id:
def sign_in(conn, %{"email" => email, "hashed_password" => hashed_password}) do
case Guardian.authenticate(email, hashed_password) do
{:ok, user, token} ->
conn
|> Plug.Conn.put_session(:user_id, user.id)
|> put_status(:ok)
|> render(:show_token, user: user, token: token)
{:error, :unauthorized} -> raise ErrorResponse.Unauthorized, message: "email or password incorrect"
end
end
I then create a function that shows the user corresponding to the session
def show_from_session(conn) do
user_id = get_session(conn, :user_id)
user = Users.get_user!(user_id)
render(conn, "show.json", user: user)
end
The json object is the standard object created by elixir:
def show(%{user: user}) do
%{data: data(user)}
end
Doing this gives me the following message:
[info] GET /api/swimmer/show_logged_in
[debug] Processing with Backend24hWeb.UserController.show_from_session/2
Parameters: %{}
Pipelines: [:api, :swimmer_auth]
[debug] QUERY OK source="users" db=0.3ms queue=0.8ms idle=1007.8ms
SELECT n0."id", n0."email", n0."hashed_password", n0."nom", n0."prenom", n0."inserted_at", n0."updated_at" FROM "users" AS n0 WHERE (n0."id" = $1) ["46180675-91ef-455d-a5a9-8d4b1fb69b06"]
↳ Backend24hWeb.Auth.Guardian.resource_from_claims/1, at: lib/backend24h_web/auth/guardian.ex:15
[info] Sent 500 in 35ms
[error] ** (KeyError) key :assign not found in: %Plug.Conn{
adapter: {Bandit.Adapter,
%Bandit.Adapter{ [truncated]
I’m relatively new to Elixir so i’m not sure i interpret this message correctly, but the error seems to come from the guardian.ex file. But this file doesn’t use assign either.
here’s the ressource_from_claims/1 function:
def resource_from_claims(%{"sub" => id}) do
case Users.get_user!(id) do
nil -> {:error, :not_found}
resource -> {:ok, resource}
end
end
I believe some default implementation of this ressource from claims function might get called by my code, but i don’t understand when or why.
Has anyone encoutered a similar issue ?
Thanks in advance