I followed and got good results until lesson 8 of https://www.youtube.com/watch?v=XVeCkV8KBuU&t=489s
With a slight tweak of having Users and Accounts as one entity: Users
I always got the unauthorized error despite IO.inspect conn showing everything in place
Set user file:
defmodule InvoiceApiWeb.Auth.SetUser do
import Plug.Conn
alias InvoiceApiWeb.Auth.ErrorResponse
alias InvoiceApi.Users
def init(_options) do
end
def call(conn , _options) do
if conn.assigns[:user] do
conn
else
user_id = get_session(conn, :user_id)
if user_id == nil, do: raise ErrorResponse.Unauthorized
user = Users.get_user!(user_id)
cond do
user_id && user -> assign( conn, :user, user)
true -> assign(conn, :user, nil)
end
end
end
end
Since you’re always seeing the unauthorized error, I’d suggest double checking that :user_id is set in the session.
Updated to add: If you search for put_session in the tutorial repo, you’ll see how :account_id is set in the accounts controller when creating and refreshing a session so that it can be fetched from the session in the auth plug.
Not sure what your screenshot is supposed to demonstrate. I can only see you are pasting an UUID without properly enclosing it in double quotes first. And then you changed that in the next iex line.
After spamming IO.inspect a bit, I found out it doesn’t even print at the beginning of the show function and I still get 401 from Guardian.
I’m getting restricted by guardian at the router level despite checking that file twice.
Meanwhile, in my router.ex
defmodule InvoiceApiWeb.Router do
use InvoiceApiWeb, :router
use Plug.ErrorHandler
defp handle_errors(conn, %{reason: %Phoenix.Router.NoRouteError{message: >message}}) do
conn |> json(%{errors: message}) |> halt()
end
defp handle_errors(conn, %{reason: %{message: message}}) do
conn |> json(%{errors: message}) |> halt()
end
pipeline :api do
plug :accepts, [“json”]
plug :fetch_session
end
pipeline :auth do
plug InvoiceApiWeb.Auth.Pipeline
plug InvoiceApiWeb.Auth.SetUser
end
scope “/api”, InvoiceApiWeb do
pipe_through :api
post “/users/create”, UserController, :create
post “/users/sign_in”, UserController, :sign_in
end
scope “/api”, InvoiceApiWeb do
pipe_through [:api, :auth]
get “/users/by_id/:id”, UserController, :show
end