riverrun / phauxth

Not actively maintained - Authentication library for Phoenix, and other Plug-based, web applications
409 stars 20 forks source link

Error with absinthe (Phoenix 1.4 and Phaux 2.0) #100

Closed tranngocsam closed 5 years ago

tranngocsam commented 5 years ago

I added a plug like this

defmodule DemoWeb.Authentication do
  use Phauxth.Authenticate.Token

  @impl true
  def set_user(user, conn) do
    IO.puts "LINE 5 #{inspect(user)}"
    Absinthe.Plug.put_options(conn, context: %{current_user: user})
  end
end

And in demo_web/router.ex, I added like this

pipeline :graphql do
  plug DemoWeb.Authentication, method: :token
end

scope "/api" do
  pipe_through :graphql

  forward "/graphiql", Absinthe.Plug.GraphiQL, schema: DemoWeb.Schema
end

My schema.ex is like this:

query do
    @desc "Get a list of users"
    field :users, :user_results do
      arg(:filters, :user_filter_input)
      arg(:pagination, :asf_pagination_input)
      resolve fn _parent, args, resolution ->
        if resolution.context.current_user do
          pagination = Demo.Accounts.list_users(args[:filters], args[:pagination])
          result = %{
            data: pagination.entries,
            meta: %{
              total: pagination.total_entries,
              page_number: pagination.page_number,
              per_page: pagination.per_page
            }
          }
          {:ok, result}
        else
          {:error, message: "Unauthorized", code: 403}
        end
      end
    end
  end

But I got (KeyError) key :current_user not found in: %{__absinthe_plug__: %{uploads: %{}}, pubsub: DemoWeb.Endpoint} error with this line resolution.context.current_user, it's because the set_user was not called.

I use Phoenix 1.4 with Phaux 2.0. I didn't get this error with Phoenix 1.3 and Phaux 1.x

What's wrong with my code?

tranngocsam commented 5 years ago

I got it working now.