#Custom Plug

9 messages · Page 1 of 1 (latest)

wet reef
#

I have a route where I want to implement a plug that will check my auth before GraphQL processing. My problem is that the plug is not being called.

My pipeline looks like this:

pipeline :api do
    plug :accepts, ["json"]
    plug DxAppRcWeb.CheckAuth

    forward "/", Absinthe.Plug, schema: DxAppRcWeb.Schema
  end

The plug looks like this:

defmodule DxAppRcWeb.CheckAuth do
  import Plug.Conn

  alias DxAppRc.Auth.MockCheckAuth

  def init(_default), do: IO.puts("Auth Plug Init")

  def call(conn, opts), do: check_auth(conn, opts)

  def check_auth(conn, _opts) do
    IO.puts("Calling Check Auth...")
    auth_token = conn |> get_req_header("authorization")
    IO.inspect(auth_token, label: "Auth Token")
    validate_auth_token(conn, auth_token)
  end
  #... More business logic
end

There is no output indicating that the Plug has been initialized or is being called per call. Any thoughts/suggestions?

torn orchid
#

hi, just refer mix phx.gen.auth, it creates a module (UserAuth, same as your CheckAuth) then import to router.ex. Then adds a call func as a argument in a scope pipe_through:

    pipe_through [:browser, :redirect_if_user_is_authenticated]```
You can use `:api` instead of `:browser` .
:redirect_if_user_is_authenticated -> It is the function you need to call
stiff knoll
#

You shouldn't really depend on the time when init is called as it is configurable (it can be ran at runtime or at compile time, depending on the configuration)

wet reef
#

The docs say I need to include init, so I'm including it.

stiff knoll
#

Yes, you need to have init/1 function

wet reef
torn orchid
true breach
#

that plug definitely looks like it should produce at least some output when being called, so maybe it's really not being called. Since you're using it inside a pipeline block, my best guess is that you're not actually hitting a route that uses that pipeline?