VBT.Auth (vbt v0.1.0) View Source

Helpers for implementing authentication in the UI layer (resolvers, sockets, controllers).

This module can be used to simplify the implementation of the authentication logic in the web layer.

Using from GraphQL resolvers

Add this module as a plug in your GraphQL pipeline:

defmodule MyRouter do
  pipeline :graphql_api do
    VBT.Auth
  end

  # ...
end

At this point, you can invoke sign/3 and verify/4 from your resolvers.

It's highly recommended to introduce a helper module in your project to wrap these invocations. For example:

defmodule MySystemWeb.Authentication do
  alias VBT.Auth

  @user_salt "super secret user salt"
  @max_age :erlang.convert_time_unit(:timer.hours(24), :millisecond, :second)

  def new_token(account),
    do: Auth.sign(MySystemWeb.Endpoint, @user_salt, %{id: account.id})

  def fetch_account(verifier, args \\ []) do
    with {:ok, account_data} <- Auth.verify(verifier, @user_salt, @max_age, args),
        do: load_account(account_data.id)
  end

  defp load_account(id) do
    case MySystem.get_account(id) do
      nil -> {:error, :account_not_found}
      account -> {:ok, account}
    end
  end
end

Using from Phoenix sockets

Assuming you have the MySystemWeb.Authentication helper module in place, and that the input is provided as %{"authorization" => "Bearer some_token"}:

defmodule MySystemWeb.UserSocket do
  def connect(args, socket) do
    case MySystemWeb.Authentication.fetch_account(socket, args) do
      {:ok, account} -> {:ok, do_something_with(socket, account)}
      {:error, _reason} -> :error
    end
  end

  # ...
end

Link to this section Summary

Functions

Signs the given data using the secret from the endpoint and the provided salt.

Verifies the signed token, returning decoded data on success.

Link to this section Types

Specs

arg() :: String.t() | args()

Specs

args() :: %{required(String.t()) => arg()} | [{String.t(), arg()}]

Specs

data() :: any()

Specs

endpoint() :: module()

Specs

salt() :: String.t()

Specs

token() :: String.t()

Specs

Specs

verify_error() :: :token_missing | :token_invalid | :token_expired

Link to this section Functions

Link to this function

sign(endpoint, salt, data)

View Source

Specs

sign(endpoint(), salt(), data()) :: token()

Signs the given data using the secret from the endpoint and the provided salt.

Link to this function

verify(verifier, salt, max_age, args \\ [])

View Source

Specs

verify(verifier(), salt(), non_neg_integer(), args()) ::
  {:ok, data()} | {:error, verify_error()}

Verifies the signed token, returning decoded data on success.