PhoenixCap (PhoenixCap v0.1.0)

Copy Markdown View Source

Mounts the Cap endpoints and verifies one-time tokens in Phoenix.

Add plug PhoenixCap before your router in endpoint.ex. The plug serves Cap under /cap. Set :at to mount it at a different path.

In a controller, add use PhoenixCap, only: [:create] after use MyAppWeb, :controller to require a token for the create action. Plain use PhoenixCap protects every action in that controller.

Summary

Types

Source of the Phoenix endpoint and its signing configuration.

A successful check consumes the token. A token adapter may return additional errors.

Functions

Adds PhoenixCap.RequireToken to a controller's plug pipeline. Pass only: [:create, :update] to select the protected actions.

Handles requests under the mount and passes other connections to the next plug.

Builds the path prefix for the endpoint plug. The default mount is /cap.

Verifies and consumes a Cap verification token using configured token options.

Verifies and consumes a Cap verification token using a Plug connection, a Phoenix LiveView socket, or a Phoenix endpoint.

Types

context()

@type context() :: Plug.Conn.t() | Phoenix.LiveView.Socket.t() | module()

Source of the Phoenix endpoint and its signing configuration.

verification_result()

@type verification_result() :: :ok | {:error, PhoenixCap.Token.reason()}

A successful check consumes the token. A token adapter may return additional errors.

Functions

__using__(opts)

(macro)

Adds PhoenixCap.RequireToken to a controller's plug pipeline. Pass only: [:create, :update] to select the protected actions.

use MyAppWeb, :controller
use PhoenixCap, only: [:create]

The action receives its usual connection and parameters after a successful check. A missing, invalid, expired or previously consumed token returns HTTP 422.

call(conn, prefix)

@spec call(Plug.Conn.t(), [String.t()]) :: Plug.Conn.t()

Handles requests under the mount and passes other connections to the next plug.

init(opts)

@spec init(keyword()) :: [String.t()]

Builds the path prefix for the endpoint plug. The default mount is /cap.

verify(token)

@spec verify(term()) :: verification_result()

Verifies and consumes a Cap verification token using configured token options.

Configure :token_context with the endpoint that issued the token to use this form from a process that has no connection or LiveView socket.

config :phoenix_cap, token_context: MyAppWeb.Endpoint

verify(context, token)

@spec verify(context(), term()) :: verification_result()

Verifies and consumes a Cap verification token using a Plug connection, a Phoenix LiveView socket, or a Phoenix endpoint.

case PhoenixCap.verify(socket, params["cap-token"]) do
  :ok -> {:noreply, assign(socket, :verified, true)}
  {:error, _reason} -> {:noreply, put_flash(socket, :error, "Please verify again.")}
end

Run this check when the protected action executes. Each verification token can succeed once and expires after 20 minutes.