Phauxth v1.2.0 Phauxth.Authenticate.Base View Source

Base module for authentication.

This is used by Phauxth.Authenticate and Phauxth.Remember. It can also be used to produce a custom authentication module, as outlined below.

Custom authentication modules

The next sections give examples of extending this module to create custom authentication modules.

Graphql authentication

The following module is another example of how this Base module can be extended, this time to provide authentication for absinthe-elixir:

defmodule AbsintheAuthenticate do
  use Phauxth.Authenticate.Base

  def set_user(user, conn) do
    put_private(conn, :absinthe, %{token: %{current_user: user}})
  end
end

And in the router.ex file, call this plug in the pipeline you want to authenticate (setting the method to :token).

pipeline :api do
  plug :accepts, ["json"]
  plug AbsintheAuthenticate, method: :token
end

Authentication for use with Phoenix channels

In this example, after adding the user struct to the current_user value, a token is added (for use with Phoenix channels).

defmodule MyAppWeb.Authenticate do
  use Phauxth.Authenticate.Base

  def set_user(nil, conn), do: assign(conn, :current_user, nil)
  def set_user(user, conn) do
    token = Phauxth.Token.sign(conn, %{"user_id" => user.email})
    assign(conn, :current_user, user)
    |> assign(:user_token, token)
  end
end

MyAppWeb.Authenticate is called in the same way as Phauxth.Authenticate.

Use Phauxth.Token.verify, in the user_socket.ex file, to verify the token.

Custom session / token implementations

This module uses Plug sessions or Phauxth tokens (based on Phoenix.Token) by default. To use custom sessions or tokens, you need to create your own custom Authenticate module and override the check_session or check_token function.